import { useEffect, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import { Document, Page, pdfjs } from "react-pdf";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/hooks/use-toast";
import { FileSignature, CheckCircle2, Loader2, Download, Ban, ChevronLeft, ChevronRight } from "lucide-react";
import SignaturePad from "@/components/SignaturePad";
import { format } from "date-fns";

pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  "pdfjs-dist/build/pdf.worker.min.mjs",
  import.meta.url
).toString();

interface Field {
  id: string;
  field_type: "signature" | "date" | "name";
  page_number: number;
  x_ratio: number;
  y_ratio: number;
  width_ratio: number;
  height_ratio: number;
  required: boolean;
}

export default function PublicSignPage() {
  const { token } = useParams<{ token: string }>();
  const { toast } = useToast();
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [recipient, setRecipient] = useState<any>(null);
  const [envelope, setEnvelope] = useState<any>(null);
  const [fields, setFields] = useState<Field[]>([]);
  const [signature, setSignature] = useState<string | null>(null);
  const [method, setMethod] = useState<"draw" | "type" | "upload">("draw");
  const [agreed, setAgreed] = useState(false);
  const [page, setPage] = useState(1);
  const [numPages, setNumPages] = useState(0);
  const [pageWidth, setPageWidth] = useState(700);
  const containerRef = useRef<HTMLDivElement>(null);

  const projectRef = (import.meta as any).env.VITE_SUPABASE_PROJECT_ID;
  const fnUrl = `https://${projectRef}.supabase.co/functions/v1/avria-sign-public`;

  useEffect(() => {
    const update = () => {
      if (containerRef.current) setPageWidth(Math.min(containerRef.current.clientWidth - 24, 900));
    };
    update();
    window.addEventListener("resize", update);
    return () => window.removeEventListener("resize", update);
  }, []);

  const load = async () => {
    setLoading(true);
    try {
      const res = await fetch(`${fnUrl}?action=lookup&token=${token}`);
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Could not load envelope");
      setRecipient(data.recipient); setEnvelope(data.envelope); setFields(data.fields || []);
    } catch (e: any) {
      toast({ variant: "destructive", title: "Error", description: e.message });
    } finally { setLoading(false); }
  };

  useEffect(() => { if (token) load(); }, [token]);

  const submit = async () => {
    if (!signature) { toast({ variant: "destructive", title: "Add your signature first" }); return; }
    if (!agreed) { toast({ variant: "destructive", title: "Please consent to electronic signing" }); return; }
    setSubmitting(true);
    try {
      const res = await fetch(`${fnUrl}?action=sign`, {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, signature_data_url: signature, signature_method: method }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to sign");
      toast({ title: "Signed Successfully", description: "Thank you. The sender will be notified." });
      load();
    } catch (e: any) {
      toast({ variant: "destructive", title: "Sign failed", description: e.message });
    } finally { setSubmitting(false); }
  };

  if (loading) return (
    <div className="min-h-screen flex items-center justify-center">
      <Loader2 className="h-6 w-6 animate-spin text-primary" />
    </div>
  );

  if (!recipient) return (
    <div className="min-h-screen flex items-center justify-center p-6">
      <Card><CardContent className="p-6 text-center">
        <p className="text-muted-foreground">Invalid or expired signing link.</p>
      </CardContent></Card>
    </div>
  );

  const isVoided = envelope?.status === "voided" || envelope?.voided_at;
  const alreadySigned = recipient.status === "signed";
  const today = format(new Date(), "MM/dd/yyyy");
  const pageFields = fields.filter(f => f.page_number === page);

  if (isVoided) {
    return (
      <div className="min-h-screen flex items-center justify-center p-6 bg-muted/30">
        <Card className="max-w-md">
          <CardContent className="p-8 text-center space-y-3">
            <Ban className="h-12 w-12 text-destructive mx-auto" />
            <p className="font-semibold text-lg">This envelope has been voided</p>
            <p className="text-sm text-muted-foreground">
              The sender has cancelled this signing request and it can no longer be signed.
            </p>
            {envelope?.voided_reason && (
              <p className="text-xs text-muted-foreground border-t pt-3 mt-3">
                Reason: {envelope.voided_reason}
              </p>
            )}
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-muted/30 py-8 px-4">
      <div className="max-w-5xl mx-auto space-y-4">
        <Card>
          <CardHeader className="border-b">
            <div className="flex items-start justify-between">
              <div>
                <CardTitle className="flex items-center gap-2">
                  <FileSignature className="h-5 w-5 text-primary" /> {envelope?.document_name}
                </CardTitle>
                <p className="text-sm text-muted-foreground mt-1">
                  Hello <span className="font-medium text-foreground">{recipient.name}</span>, please review and sign.
                </p>
              </div>
              <Badge variant={alreadySigned ? "default" : "secondary"} className="gap-1">
                {alreadySigned ? <><CheckCircle2 className="h-3 w-3" /> Signed</> : "Pending"}
              </Badge>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            {envelope?.document_url ? (
              <div ref={containerRef} className="bg-muted/20 p-4">
                {fields.length > 0 && (
                  <div className="flex items-center justify-center gap-2 mb-3">
                    <Button type="button" variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>
                      <ChevronLeft className="h-4 w-4" />
                    </Button>
                    <span className="text-sm font-medium">Page {page} / {numPages || "…"}</span>
                    <Button type="button" variant="outline" size="sm" disabled={page >= numPages} onClick={() => setPage(p => p + 1)}>
                      <ChevronRight className="h-4 w-4" />
                    </Button>
                  </div>
                )}

                {fields.length > 0 ? (
                  <div className="flex justify-center">
                    <Document
                      file={envelope.document_url}
                      onLoadSuccess={({ numPages }) => setNumPages(numPages)}
                      loading={<Loader2 className="h-6 w-6 animate-spin text-primary" />}
                    >
                      <div className="relative inline-block shadow-md">
                        <Page pageNumber={page} width={pageWidth} renderTextLayer={false} renderAnnotationLayer={false} />
                        {pageFields.map(f => (
                          <div
                            key={f.id}
                            className="absolute border-2 border-dashed border-primary bg-primary/10 rounded flex items-center justify-center text-[10px] font-semibold uppercase text-primary"
                            style={{
                              left: `${f.x_ratio * 100}%`,
                              top: `${f.y_ratio * 100}%`,
                              width: `${f.width_ratio * 100}%`,
                              height: `${f.height_ratio * 100}%`,
                            }}
                          >
                            {f.field_type === "signature" && signature ? (
                              <img src={signature} alt="signature" className="max-w-full max-h-full object-contain" />
                            ) : f.field_type === "date" ? (
                              <span className="text-foreground text-xs normal-case">{today}</span>
                            ) : f.field_type === "name" ? (
                              <span className="text-foreground text-xs normal-case font-medium">{recipient.name}</span>
                            ) : (
                              <span>Sign Here</span>
                            )}
                          </div>
                        ))}
                      </div>
                    </Document>
                  </div>
                ) : (
                  <iframe src={envelope.document_url} className="w-full h-[600px] border-0 bg-white" title="Document" />
                )}
              </div>
            ) : (
              <div className="p-8 text-center text-muted-foreground">Document unavailable</div>
            )}
          </CardContent>
        </Card>

        {alreadySigned ? (
          <Card>
            <CardContent className="p-6 text-center space-y-3">
              <CheckCircle2 className="h-12 w-12 text-emerald-500 mx-auto" />
              <p className="font-medium">You have signed this document.</p>
              {envelope?.signed_document_url && (
                <Button asChild>
                  <a href={envelope.signed_document_url} target="_blank" rel="noopener noreferrer">
                    <Download className="h-4 w-4 mr-2" /> Download Signed Copy
                  </a>
                </Button>
              )}
            </CardContent>
          </Card>
        ) : (
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Your Signature</CardTitle>
              {fields.length > 0 && (
                <p className="text-xs text-muted-foreground">
                  {fields.filter(f => f.field_type === "signature").length} signature field(s) will be filled across {new Set(fields.map(f => f.page_number)).size} page(s).
                </p>
              )}
            </CardHeader>
            <CardContent className="space-y-4">
              <SignaturePad signerName={recipient.name} onChange={(d, m) => { setSignature(d); setMethod(m); }} />

              <label className="flex items-start gap-2 text-sm cursor-pointer">
                <input type="checkbox" checked={agreed} onChange={e => setAgreed(e.target.checked)} className="mt-1" />
                <span className="text-muted-foreground">
                  I agree that my electronic signature is the legal equivalent of my handwritten signature on this document.
                </span>
              </label>

              <Button onClick={submit} disabled={submitting || !signature} className="w-full gap-2" size="lg">
                {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : <CheckCircle2 className="h-4 w-4" />}
                {submitting ? "Submitting..." : "Sign and Submit"}
              </Button>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}
