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 { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Loader2, Shield, CheckCircle2, AlertTriangle, Lock } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

export default function BoardVotePublicPage() {
  const { voteId } = useParams();
  const [searchParams] = useSearchParams();
  const token = searchParams.get("token") || "";
  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 [selected, setSelected] = useState<string>("");
  const [submitted, setSubmitted] = useState(false);

  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_board_vote_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.board_vote_id !== voteId) {
        setError("This link doesn't match the requested vote.");
        setLoading(false);
        return;
      }
      setInfo(row);
      if (row.voted_at) setSubmitted(true);
      setLoading(false);
    })();
  }, [token, voteId]);

  const handleSubmit = async () => {
    if (!selected) return;
    setSubmitting(true);
    const { data, error: e } = await supabase.rpc("record_board_vote_by_token", {
      p_token: token,
      p_option: selected,
    });
    setSubmitting(false);
    const result = (data || {}) as { ok?: boolean; error?: string; already_voted?: boolean };
    if (e || !result.ok) {
      const msg = result.error || e?.message || "Could not record vote";
      if (result.already_voted) {
        setSubmitted(true);
        toast({ title: "Already voted", description: msg });
      } else {
        toast({ title: "Error", description: msg, variant: "destructive" });
      }
      return;
    }
    setSubmitted(true);
    toast({ title: "Vote recorded", description: "Thank you!" });
  };

  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>
    );
  }

  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 board vote — for {info?.member_name || "Board Member"}
        </div>
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span>{info?.vote_title}</span>
              <Badge variant={info?.vote_status === "open" ? "default" : "secondary"}>{info?.vote_status}</Badge>
            </CardTitle>
            {info?.association_name && (
              <p className="text-sm text-muted-foreground">{info.association_name}</p>
            )}
          </CardHeader>
          <CardContent className="space-y-5">
            {info?.vote_description && (
              <div className="bg-muted p-3 rounded-md border whitespace-pre-wrap text-sm">{info.vote_description}</div>
            )}

            <div className="bg-amber-50 border border-amber-200 text-amber-900 rounded-md p-3 text-sm">
              <p className="font-medium mb-1">For recording purposes</p>
              <p>This vote is being collected electronically and will be formally <strong>ratified at a later board meeting</strong>.</p>
            </div>

            {submitted ? (
              <div className="text-center py-6 space-y-2">
                <CheckCircle2 className="mx-auto h-12 w-12 text-green-600" />
                <p className="font-medium">Your vote has been recorded.</p>
                {info?.vote_option && (
                  <p className="text-sm text-muted-foreground">Recorded choice: <strong>{info.vote_option}</strong></p>
                )}
                <p className="text-xs text-muted-foreground">You may close this window.</p>
              </div>
            ) : info?.vote_status !== "open" ? (
              <p className="text-center py-4 text-muted-foreground">Voting is closed for this item.</p>
            ) : (
              <>
                <div>
                  <p className="font-medium mb-2">Cast your vote:</p>
                  <RadioGroup value={selected} onValueChange={setSelected} className="gap-2">
                    {(info?.vote_options || []).map((opt: string) => (
                      <div key={opt} className="flex items-center gap-2 border rounded-md p-3 hover:bg-muted/50">
                        <RadioGroupItem value={opt} id={`opt-${opt}`} />
                        <Label htmlFor={`opt-${opt}`} className="flex-1 cursor-pointer">{opt}</Label>
                      </div>
                    ))}
                  </RadioGroup>
                </div>
                <Button onClick={handleSubmit} disabled={!selected || submitting} className="w-full">
                  {submitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />} Submit Vote
                </Button>
                <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>
  );
}
