import { useState, useEffect, useCallback } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { FileSignature, RefreshCw, ExternalLink, Clock, CheckCircle2, Send, AlertCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { format } from "date-fns";
import DocuSignSendDialog from "@/components/DocuSignSendDialog";
import { extractDocuSignFunctionError } from "@/lib/docusign";

const statusVariant = (s: string) => {
  switch (s) {
    case "completed": return "default";
    case "sent": return "secondary";
    case "delivered": return "outline";
    case "declined": case "voided": return "destructive";
    default: return "secondary";
  }
};

const statusIcon = (s: string) => {
  switch (s) {
    case "completed": return <CheckCircle2 className="h-3.5 w-3.5" />;
    case "sent": case "delivered": return <Send className="h-3.5 w-3.5" />;
    case "declined": case "voided": return <AlertCircle className="h-3.5 w-3.5" />;
    default: return <Clock className="h-3.5 w-3.5" />;
  }
};

export default function DocuSignEnvelopesPage() {
  const { toast } = useToast();
  const [envelopes, setEnvelopes] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [sendOpen, setSendOpen] = useState(false);

  const fetchEnvelopes = useCallback(async () => {
    setLoading(true);
    const { data, error } = await supabase
      .from("docusign_envelopes")
      .select("*, associations(name)")
      .order("created_at", { ascending: false });

    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
    } else {
      setEnvelopes(data || []);
    }
    setLoading(false);
  }, [toast]);

  useEffect(() => {
    fetchEnvelopes();
  }, [fetchEnvelopes]);

  const refreshStatus = async (envelopeId: string) => {
    try {
      const { data, error } = await supabase.functions.invoke("docusign-send", {
        body: { action: "status", envelope_id: envelopeId },
      });
      if (error) throw error;
      if (data?.error) throw new Error(data.error);
      toast({ title: "Status Updated", description: `Envelope status: ${data.status}` });
      fetchEnvelopes();
    } catch (err: any) {
      const parsedError = await extractDocuSignFunctionError(err);

      if (parsedError.code === "consent_required" && parsedError.consentUrl) {
        window.open(parsedError.consentUrl, "_blank", "noopener,noreferrer");
      }

      toast({
        variant: "destructive",
        title: parsedError.code === "consent_required" ? "DocuSign consent required" : "Error",
        description: parsedError.code === "consent_required"
          ? "Approve DocuSign access in the opened tab, then refresh status again."
          : parsedError.message,
      });
    }
  };

  const stats = {
    total: envelopes.length,
    sent: envelopes.filter((e) => e.status === "sent" || e.status === "delivered").length,
    completed: envelopes.filter((e) => e.status === "completed").length,
    pending: envelopes.filter((e) => !["completed", "declined", "voided"].includes(e.status)).length,
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <FileSignature className="h-6 w-6 text-primary" /> DocuSign
          </h1>
          <p className="text-sm text-muted-foreground mt-1">Send documents for electronic signature and track status.</p>
        </div>
        <Button onClick={() => setSendOpen(true)} className="gap-2">
          <Send className="h-4 w-4" /> Send for Signature
        </Button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {[
          { label: "Total Envelopes", value: stats.total, color: "text-foreground" },
          { label: "Awaiting Signature", value: stats.pending, color: "text-amber-600" },
          { label: "Completed", value: stats.completed, color: "text-emerald-600" },
          { label: "Sent", value: stats.sent, color: "text-blue-600" },
        ].map((s) => (
          <Card key={s.label}>
            <CardContent className="p-4">
              <p className="text-xs text-muted-foreground">{s.label}</p>
              <p className={`text-2xl font-bold ${s.color}`}>{s.value}</p>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Table */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">Envelopes</CardTitle>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex justify-center py-8">
              <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
            </div>
          ) : envelopes.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">
              <FileSignature className="h-12 w-12 mx-auto mb-3 opacity-30" />
              <p className="font-medium">No envelopes yet</p>
              <p className="text-sm">Send your first document for signature.</p>
            </div>
          ) : (
            <div className="rounded-md border overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Document</TableHead>
                    <TableHead>Association</TableHead>
                    <TableHead>Recipients</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Sent</TableHead>
                    <TableHead className="w-[80px]">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {envelopes.map((env) => {
                    let recipientList: any[] = [];
                    try {
                      recipientList = typeof env.recipients === "string"
                        ? JSON.parse(env.recipients)
                        : env.recipients || [];
                    } catch { /* ignore */ }

                    return (
                      <TableRow key={env.id}>
                        <TableCell className="font-medium">{env.document_name}</TableCell>
                        <TableCell className="text-sm text-muted-foreground">
                          {env.associations?.name || "—"}
                        </TableCell>
                        <TableCell>
                          <div className="flex flex-wrap gap-1">
                            {recipientList.map((r: any, i: number) => (
                              <Badge key={i} variant="outline" className="text-xs">
                                {r.name || r.email}
                              </Badge>
                            ))}
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge variant={statusVariant(env.status)} className="gap-1 capitalize">
                            {statusIcon(env.status)} {env.status}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-sm text-muted-foreground">
                          {env.sent_at ? format(new Date(env.sent_at), "MM/dd/yyyy") : "—"}
                        </TableCell>
                        <TableCell>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8"
                            onClick={() => refreshStatus(env.envelope_id)}
                            title="Refresh status"
                          >
                            <RefreshCw className="h-3.5 w-3.5" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      <DocuSignSendDialog
        open={sendOpen}
        onOpenChange={setSendOpen}
        onSuccess={fetchEnvelopes}
      />
    </div>
  );
}
