import { useEffect, useState } from "react";
import { useParams, useNavigate, Link } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { Loader2, CheckCircle2, XCircle } from "lucide-react";

type CodeInfo = {
  id: string;
  role: string;
  owner_id: string | null;
  expires_at: string | null;
  redeemed_at: string | null;
  owner_first_name: string | null;
  owner_last_name: string | null;
  owner_email: string | null;
  association_name: string | null;
};

export default function CodeRegistrationPage() {
  const { code } = useParams<{ code: string }>();
  const navigate = useNavigate();
  const { toast } = useToast();

  const [loading, setLoading] = useState(true);
  const [info, setInfo] = useState<CodeInfo | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(false);

  const [email, setEmail] = useState("");
  const [fullName, setFullName] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  useEffect(() => {
    const load = async () => {
      if (!code) return;
      const { data, error } = await supabase.rpc("lookup_signup_code", { p_code: code.toUpperCase() });
      if (error || !data || (data as any[]).length === 0) {
        setError("This sign-up code is invalid.");
      } else {
        const row = (data as any[])[0] as CodeInfo;
        if (row.redeemed_at) setError("This code has already been used.");
        else if (row.expires_at && new Date(row.expires_at) < new Date()) setError("This code has expired.");
        else {
          setInfo(row);
          if (row.owner_email) setEmail(row.owner_email);
          if (row.owner_first_name || row.owner_last_name) {
            setFullName(`${row.owner_first_name || ""} ${row.owner_last_name || ""}`.trim());
          }
        }
      }
      setLoading(false);
    };
    load();
  }, [code]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (password !== confirmPassword) {
      toast({ title: "Passwords don't match", variant: "destructive" });
      return;
    }
    if (password.length < 8) {
      toast({ title: "Password must be at least 8 characters", variant: "destructive" });
      return;
    }
    setSubmitting(true);
    const { data, error } = await supabase.functions.invoke("redeem-signup-code", {
      body: { code: code?.toUpperCase(), email, password, full_name: fullName },
    });
    setSubmitting(false);
    if (error || (data as any)?.error) {
      toast({ title: "Registration failed", description: (data as any)?.error || error?.message, variant: "destructive" });
      return;
    }
    setSuccess(true);
    // Sign in immediately
    const { data: signInData, error: signInError } = await supabase.auth.signInWithPassword({ email, password });
    if (signInError || !signInData?.user) {
      toast({ title: "Account created", description: "Please sign in." });
      setTimeout(() => navigate("/auth"), 1500);
      return;
    }

    // Route the new user based on their assigned role
    const assignedRole = (info?.role || (data as any)?.role || "homeowner") as string;
    const destination = (() => {
      switch (assignedRole) {
        case "admin":
        case "manager":
          return "/dashboard";
        case "legal":
          return "/legal";
        case "master_board_member":
          return "/master-board";
        case "rv_boat_lot":
        case "homeowner":
        case "board_member":
        case "arc_member":
        case "fining_member":
        default:
          return "/homeowner";
      }
    })();
    setTimeout(() => navigate(destination), 1200);
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4 bg-secondary/40">
        <Card className="max-w-md w-full">
          <CardHeader className="text-center">
            <XCircle className="h-12 w-12 text-destructive mx-auto mb-2" />
            <CardTitle>Code Unavailable</CardTitle>
            <CardDescription>{error}</CardDescription>
          </CardHeader>
          <CardContent>
            <Button asChild className="w-full"><Link to="/auth">Go to Sign In</Link></Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (success) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4 bg-secondary/40">
        <Card className="max-w-md w-full">
          <CardHeader className="text-center">
            <CheckCircle2 className="h-12 w-12 text-primary mx-auto mb-2" />
            <CardTitle>Welcome!</CardTitle>
            <CardDescription>Your account has been created and verified.</CardDescription>
          </CardHeader>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-4 bg-secondary/40">
      <Card className="max-w-md w-full">
        <CardHeader>
          <CardTitle>Complete Your Registration</CardTitle>
          <CardDescription>
            {info?.association_name ? `${info.association_name} — ` : ""}
            Your email will be verified automatically.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <Label htmlFor="fullName">Full Name</Label>
              <Input id="fullName" value={fullName} onChange={(e) => setFullName(e.target.value)} required />
            </div>
            <div>
              <Label htmlFor="email">Email</Label>
              <Input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
            </div>
            <div>
              <Label htmlFor="password">Password</Label>
              <Input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} />
            </div>
            <div>
              <Label htmlFor="confirmPassword">Confirm Password</Label>
              <Input id="confirmPassword" type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} required minLength={8} />
            </div>
            <Button type="submit" className="w-full" disabled={submitting}>
              {submitting ? <><Loader2 className="h-4 w-4 mr-2 animate-spin" />Creating account…</> : "Create Account"}
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
