import { useState, useEffect, useCallback } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { FileSignature, RefreshCw, Send, CheckCircle2, Clock, AlertCircle, Download, Eye, Ban, Trash2, MoreHorizontal } 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 {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription,
  AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { format } from "date-fns";
import AvriaSignSendDialog from "@/components/AvriaSignSendDialog";

const statusVariant = (s: string): "default" | "secondary" | "outline" | "destructive" => {
  switch (s) {
    case "completed": return "default";
    case "sent": return "secondary";
    case "viewed": 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 "viewed": return <Send className="h-3.5 w-3.5" />;
    case "declined": case "voided": return <Ban className="h-3.5 w-3.5" />;
    default: return <Clock className="h-3.5 w-3.5" />;
  }
};

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

  const [voidTarget, setVoidTarget] = useState<any | null>(null);
  const [voidReason, setVoidReason] = useState("");
  const [voidBusy, setVoidBusy] = useState(false);

  const [deleteTarget, setDeleteTarget] = useState<any | null>(null);
  const [deleteBusy, setDeleteBusy] = useState(false);

  const fetchEnvelopes = useCallback(async () => {
    setLoading(true);
    const { data, error } = await supabase
      .from("signature_envelopes" as any)
      .select("*, signature_recipients(*), associations(name)")
      .order("created_at", { ascending: false });
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
    } else {
      setEnvelopes((data as any[]) || []);
    }
    setLoading(false);
  }, [toast]);

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

  const handleVoid = async () => {
    if (!voidTarget) return;
    setVoidBusy(true);
    try {
      const { data: userRes } = await supabase.auth.getUser();
      const { error } = await supabase.from("signature_envelopes" as any).update({
        status: "voided",
        voided_at: new Date().toISOString(),
        voided_reason: voidReason || null,
        voided_by: userRes?.user?.id || null,
      }).eq("id", voidTarget.id);
      if (error) throw error;
      await supabase.from("signature_events" as any).insert({
        envelope_id: voidTarget.id,
        event_type: "voided",
        details: { reason: voidReason || null },
      });
      toast({ title: "Envelope Voided", description: "Recipients can no longer sign this document." });
      setVoidTarget(null); setVoidReason("");
      fetchEnvelopes();
    } catch (e: any) {
      toast({ variant: "destructive", title: "Void failed", description: e.message });
    } finally {
      setVoidBusy(false);
    }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    setDeleteBusy(true);
    try {
      const { error } = await supabase.from("signature_envelopes" as any).delete().eq("id", deleteTarget.id);
      if (error) throw error;
      toast({ title: "Envelope Deleted" });
      setDeleteTarget(null);
      fetchEnvelopes();
    } catch (e: any) {
      toast({ variant: "destructive", title: "Delete failed", description: e.message });
    } finally {
      setDeleteBusy(false);
    }
  };

  const stats = {
    total: envelopes.length,
    sent: envelopes.filter(e => e.status === "sent" || e.status === "viewed").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" /> Avria Sign
          </h1>
          <p className="text-sm text-muted-foreground mt-1">Send documents for in-house electronic signature with stamped certificates.</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="icon" onClick={fetchEnvelopes} title="Refresh">
            <RefreshCw className="h-4 w-4" />
          </Button>
          <Button onClick={() => setSendOpen(true)} className="gap-2">
            <Send className="h-4 w-4" /> Send for Signature
          </Button>
        </div>
      </div>

      <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 / Viewed", 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>

      <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-[140px]">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {envelopes.map(env => {
                    const isFinal = env.status === "completed" || env.status === "voided";
                    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">
                            {(env.signature_recipients || []).map((r: any) => (
                              <Badge key={r.id} variant={r.status === "signed" ? "default" : "outline"} className="text-xs gap-1">
                                {r.status === "signed" && <CheckCircle2 className="h-2.5 w-2.5" />}
                                {r.name}
                              </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>
                          <div className="flex gap-1 items-center">
                            {env.document_url && (
                              <Button variant="ghost" size="icon" className="h-8 w-8" asChild title="View original">
                                <a href={env.document_url} target="_blank" rel="noopener noreferrer">
                                  <Eye className="h-3.5 w-3.5" />
                                </a>
                              </Button>
                            )}
                            {env.signed_document_url && (
                              <Button variant="ghost" size="icon" className="h-8 w-8" asChild title="Download signed">
                                <a href={env.signed_document_url} target="_blank" rel="noopener noreferrer">
                                  <Download className="h-3.5 w-3.5" />
                                </a>
                              </Button>
                            )}
                            <DropdownMenu>
                              <DropdownMenuTrigger asChild>
                                <Button variant="ghost" size="icon" className="h-8 w-8" title="More">
                                  <MoreHorizontal className="h-3.5 w-3.5" />
                                </Button>
                              </DropdownMenuTrigger>
                              <DropdownMenuContent align="end">
                                {!isFinal && (
                                  <DropdownMenuItem onClick={() => setVoidTarget(env)} className="text-amber-600">
                                    <Ban className="h-3.5 w-3.5 mr-2" /> Void Envelope
                                  </DropdownMenuItem>
                                )}
                                {!isFinal && <DropdownMenuSeparator />}
                                <DropdownMenuItem onClick={() => setDeleteTarget(env)} className="text-destructive">
                                  <Trash2 className="h-3.5 w-3.5 mr-2" /> Delete Permanently
                                </DropdownMenuItem>
                              </DropdownMenuContent>
                            </DropdownMenu>
                          </div>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      <AvriaSignSendDialog open={sendOpen} onOpenChange={setSendOpen} onSuccess={fetchEnvelopes} />

      {/* Void dialog */}
      <Dialog open={!!voidTarget} onOpenChange={(o) => !o && setVoidTarget(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2"><Ban className="h-5 w-5 text-amber-600" /> Void Envelope</DialogTitle>
            <DialogDescription>
              Voiding "{voidTarget?.document_name}" prevents recipients from signing. This action is logged in the audit trail.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-2">
            <Label>Reason (optional, included in audit log)</Label>
            <Textarea value={voidReason} onChange={e => setVoidReason(e.target.value)} placeholder="e.g., Document needs revision" rows={3} />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setVoidTarget(null)} disabled={voidBusy}>Cancel</Button>
            <Button onClick={handleVoid} disabled={voidBusy} className="bg-amber-600 hover:bg-amber-700 text-white">
              {voidBusy ? "Voiding…" : "Void Envelope"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete confirm */}
      <AlertDialog open={!!deleteTarget} onOpenChange={(o) => !o && setDeleteTarget(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete envelope permanently?</AlertDialogTitle>
            <AlertDialogDescription>
              This permanently removes "{deleteTarget?.document_name}", all signatures, audit events, and field placements. This cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={deleteBusy}>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} disabled={deleteBusy} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
              {deleteBusy ? "Deleting…" : "Delete Permanently"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
