import { useEffect, useState } from "react";
import { useParams, useSearchParams } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Loader2, Shield, CheckCircle2, XCircle, AlertTriangle, Lock, ExternalLink } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

export default function BillApprovePublicPage() {
  const { billId } = useParams();
  const [searchParams] = useSearchParams();
  const token = searchParams.get("token") || "";
  const presetAction = searchParams.get("action") || ""; // "approve" | "deny"
  const { toast } = useToast();

  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [info, setInfo] = useState<any>(null);
  const [notes, setNotes] = useState("");
  const [done, setDone] = useState<{ action: string } | null>(null);

  useEffect(() => {
    if (!token) {
      setError("Missing token. Please use the secure link from your email.");
      setLoading(false);
      return;
    }
    (async () => {
      const { data, error: e } = await supabase.rpc("lookup_bill_approval_by_token", { p_token: token });
      if (e || !data || data.length === 0) {
        setError("Invalid or expired secure link.");
        setLoading(false);
        return;
      }
      const row = data[0];
      if (row.bill_id !== billId) {
        setError("This link doesn't match the requested bill.");
        setLoading(false);
        return;
      }
      setInfo(row);
      if (row.acted_at) setDone({ action: row.action });
      setLoading(false);
    })();
  }, [token, billId]);

  const submit = async (action: "approved" | "denied") => {
    setSubmitting(true);
    const { data, error: e } = await supabase.rpc("record_bill_approval_by_token", {
      p_token: token, p_action: action, p_notes: notes || null,
    });
    setSubmitting(false);
    const result = (data || {}) as { ok?: boolean; error?: string; already_voted?: boolean; action?: string };
    if (e || !result.ok) {
      if (result.already_voted) {
        setDone({ action: result.action || action });
        toast({ title: "Already recorded", description: result.error || "You already responded." });
        return;
      }
      toast({ title: "Error", description: result.error || e?.message || "Could not record response", variant: "destructive" });
      return;
    }
    setDone({ action });
    toast({ title: action === "approved" ? "Bill approved" : "Bill denied", description: "Thank you — your response was recorded." });
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-secondary/40">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }
  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-secondary/40 p-4">
        <Card className="max-w-md w-full">
          <CardContent className="py-10 text-center space-y-3">
            <AlertTriangle className="mx-auto h-10 w-10 text-destructive" />
            <p className="text-destructive font-medium">{error}</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(Number(info?.amount || 0));

  return (
    <div className="min-h-screen bg-secondary/40 py-10 px-4">
      <div className="max-w-xl mx-auto space-y-4">
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <Lock className="h-4 w-4" /> Secure bill approval — for {info?.member_name || "Board Member"}
        </div>
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between gap-2">
              <span>Bill Approval</span>
              <Badge variant={info?.bill_status === "pending" ? "default" : "secondary"} className="capitalize">{info?.bill_status}</Badge>
            </CardTitle>
            {info?.association_name && (
              <p className="text-sm text-muted-foreground">{info.association_name}</p>
            )}
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="rounded-md border bg-muted/40 p-3 text-sm space-y-1">
              {info?.vendor_name && <div><span className="text-muted-foreground">Vendor:</span> <strong>{info.vendor_name}</strong></div>}
              {info?.invoice_number && <div><span className="text-muted-foreground">Invoice #:</span> {info.invoice_number}</div>}
              <div><span className="text-muted-foreground">Amount:</span> <strong>{money}</strong></div>
              {info?.bill_date && <div><span className="text-muted-foreground">Bill date:</span> {info.bill_date}</div>}
              {info?.due_date && <div><span className="text-muted-foreground">Due date:</span> {info.due_date}</div>}
              {info?.description && <div className="pt-1"><span className="text-muted-foreground">Description:</span> {info.description}</div>}
              {info?.attachment_url && (
                <div className="pt-2">
                  <a href={info.attachment_url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-primary underline text-xs">
                    <ExternalLink className="h-3 w-3" /> View attached invoice
                  </a>
                </div>
              )}
            </div>

            {done ? (
              <div className="text-center py-6 space-y-2">
                {done.action === "approved" ? (
                  <CheckCircle2 className="mx-auto h-12 w-12 text-green-600" />
                ) : (
                  <XCircle className="mx-auto h-12 w-12 text-destructive" />
                )}
                <p className="font-medium">Your response has been recorded: <span className="capitalize">{done.action}</span>.</p>
                <p className="text-xs text-muted-foreground">You may close this window.</p>
              </div>
            ) : info?.bill_status !== "pending" ? (
              <p className="text-center py-4 text-muted-foreground">This bill is no longer pending and cannot be voted on.</p>
            ) : (
              <>
                <div>
                  <label className="text-sm font-medium">Notes (optional)</label>
                  <Textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={3} placeholder="Add a comment for the record…" />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <Button
                    onClick={() => submit("approved")}
                    disabled={submitting}
                    className="bg-green-600 hover:bg-green-700"
                  >
                    {submitting ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <CheckCircle2 className="h-4 w-4 mr-2" />}
                    Approve
                  </Button>
                  <Button
                    onClick={() => submit("denied")}
                    disabled={submitting}
                    variant="destructive"
                  >
                    {submitting ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <XCircle className="h-4 w-4 mr-2" />}
                    Deny
                  </Button>
                </div>
                {presetAction && (
                  <p className="text-xs text-muted-foreground text-center">
                    Tap <strong>{presetAction === "approve" ? "Approve" : "Deny"}</strong> to confirm your choice from the email.
                  </p>
                )}
                <p className="text-xs text-muted-foreground flex items-start gap-1.5">
                  <Shield className="h-3.5 w-3.5 mt-0.5 shrink-0" />
                  This is a secure link tied to your board seat. Do not share or forward it.
                </p>
              </>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
