import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { CheckCircle2, XCircle, Shield, Clock, FileText } from "lucide-react";
import { format } from "date-fns";
import { toZonedTime } from "date-fns-tz";

const TZ = "America/New_York";

export default function VerifyDocumentPage() {
  const { proofId } = useParams();
  const [proof, setProof] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);

  useEffect(() => {
    let isActive = true;

    const loadProof = async () => {
      setLoading(true);
      setNotFound(false);
      setProof(null);

      if (!proofId) {
        if (!isActive) return;
        setNotFound(true);
        setLoading(false);
        return;
      }

      const { data, error } = await supabase.functions.invoke("get-document-validation-proof", {
        body: { proofId },
      });

      if (!isActive) return;

      if (error || !data) {
        console.error("[VerifyDocumentPage] Failed to load proof", error);
        setNotFound(true);
      } else {
        setProof(data);
      }

      setLoading(false);
    };

    loadProof();

    return () => {
      isActive = false;
    };
  }, [proofId]);

  if (loading) return (
    <div className="min-h-screen flex items-center justify-center bg-background">
      <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
    </div>
  );

  if (notFound) return (
    <div className="min-h-screen flex items-center justify-center bg-background p-6">
      <Card className="max-w-md w-full">
        <CardContent className="py-12 text-center space-y-4">
          <XCircle className="h-16 w-16 text-destructive mx-auto" />
          <h2 className="text-xl font-bold text-foreground">Document Not Found</h2>
          <p className="text-sm text-muted-foreground">
            This verification ID does not match any document in our system.
            The document may not exist or the link may be invalid.
          </p>
        </CardContent>
      </Card>
    </div>
  );

  const genDate = toZonedTime(new Date(proof.generated_at), TZ);

  return (
    <div className="min-h-screen flex items-center justify-center bg-background p-6">
      <Card className="max-w-lg w-full shadow-xl border-2 border-emerald-200">
        <CardHeader className="text-center pb-2">
          <div className="mx-auto mb-3">
            <CheckCircle2 className="h-16 w-16 text-emerald-500" />
          </div>
          <CardTitle className="text-xl font-bold text-foreground">Document Verified</CardTitle>
          <p className="text-sm text-muted-foreground mt-1">
            This document has been authenticated by the system.
          </p>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="bg-muted/50 rounded-lg p-4 space-y-3">
            <div className="flex items-start gap-3">
              <FileText className="h-5 w-5 text-primary mt-0.5 shrink-0" />
              <div>
                <p className="text-xs text-muted-foreground font-medium">Document</p>
                <p className="text-sm font-semibold text-foreground">{proof.document_title}</p>
                <Badge variant="outline" className="mt-1 text-[10px]">{proof.document_type}</Badge>
              </div>
            </div>

            <div className="flex items-start gap-3">
              <Clock className="h-5 w-5 text-primary mt-0.5 shrink-0" />
              <div>
                <p className="text-xs text-muted-foreground font-medium">Generated</p>
                <p className="text-sm font-semibold text-foreground">
                  {format(genDate, "MMMM d, yyyy")}
                </p>
                <p className="text-xs text-muted-foreground">
                  {format(genDate, "h:mm:ss a")} EST
                </p>
              </div>
            </div>

            {proof.associations?.name && (
              <div className="flex items-start gap-3">
                <Shield className="h-5 w-5 text-primary mt-0.5 shrink-0" />
                <div>
                  <p className="text-xs text-muted-foreground font-medium">Association</p>
                  <p className="text-sm font-semibold text-foreground">{proof.associations.name}</p>
                </div>
              </div>
            )}
          </div>

          <div className="text-center space-y-1 pt-2">
            <p className="text-[10px] text-muted-foreground font-mono break-all">
              Verification ID: {proof.id}
            </p>
            <p className="text-[10px] text-muted-foreground font-mono break-all">
              Hash: {proof.verification_hash}
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
