import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import acmLogoFull from "@/assets/acm-logo-full.png";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { useToast } from "@/hooks/use-toast";
import { ArrowLeft, CheckCircle2, Loader2 } from "lucide-react";

export default function ResetPasswordPage() {
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [canReset, setCanReset] = useState(false);
  const [completed, setCompleted] = useState(false);
  const isInvite = new URLSearchParams(window.location.search).get("mode") === "invite";
  const navigate = useNavigate();
  const { toast } = useToast();

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

    const checkRecoverySession = async () => {
      const { data: { session } } = await supabase.auth.getSession();
      if (!active) return;

      setCanReset(Boolean(session));
      setLoading(false);
    };

    const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
      if (!active) return;

      setCanReset(Boolean(session));
      setLoading(false);
    });

    void checkRecoverySession();

    return () => {
      active = false;
      subscription.unsubscribe();
    };
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (newPassword.length < 6) {
      toast({ title: "Password too short", description: "Password must be at least 6 characters.", variant: "destructive" });
      return;
    }

    if (newPassword !== confirmPassword) {
      toast({ title: "Passwords do not match", description: "Please make sure both passwords match.", variant: "destructive" });
      return;
    }

    setSaving(true);
    try {
      const { error } = await supabase.auth.updateUser({ password: newPassword });
      if (error) throw error;

      await supabase.auth.signOut({ scope: "local" });
      setCompleted(true);
    } catch (error: any) {
      toast({ title: "Password reset failed", description: error.message, variant: "destructive" });
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center bg-secondary p-4">
        <img src={acmLogoFull} alt="Avria Community Management" className="mb-6 h-16 w-auto" />
        <Card className="w-full max-w-md">
          <CardContent className="flex flex-col items-center gap-4 pt-8 pb-8 text-center">
            <Loader2 className="h-10 w-10 animate-spin text-primary" />
            <div>
              <p className="font-semibold">Preparing your reset link</p>
              <p className="text-sm text-muted-foreground">Please wait a moment…</p>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (completed) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center bg-secondary p-4">
        <img src={acmLogoFull} alt="Avria Community Management" className="mb-6 h-16 w-auto" />
        <Card className="w-full max-w-md">
          <CardContent className="flex flex-col items-center gap-4 pt-8 pb-8 text-center">
            <CheckCircle2 className="h-14 w-14 text-primary" />
            <div className="space-y-2">
              <h1 className="text-xl font-semibold">{isInvite ? "Account ready" : "Password updated"}</h1>
              <p className="text-sm text-muted-foreground">{isInvite ? "Your account password has been set successfully. You can now sign in." : "Your password has been reset successfully. You can now sign in with your new password."}</p>
            </div>
            <Button onClick={() => navigate("/auth")} className="w-full">
              Go to Sign In
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (!canReset) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center bg-secondary p-4">
        <img src={acmLogoFull} alt="Avria Community Management" className="mb-6 h-16 w-auto" />
        <Card className="w-full max-w-md">
          <CardHeader className="text-center">
            <CardTitle>{isInvite ? "Invite link unavailable" : "Reset link unavailable"}</CardTitle>
            <CardDescription>{isInvite ? "This invitation link is invalid, expired, or has already been used." : "This password reset link is invalid, expired, or has already been used."}</CardDescription>
          </CardHeader>
          <CardContent>
            <Button variant="outline" onClick={() => navigate("/auth")} className="w-full">
              <ArrowLeft className="mr-2 h-4 w-4" /> Back to Sign In
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen flex-col items-center justify-center bg-secondary p-4">
      <img src={acmLogoFull} alt="Avria Community Management" className="mb-6 h-16 w-auto" />
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <CardTitle>{isInvite ? "Set Your Password" : "Set a New Password"}</CardTitle>
          <CardDescription>{isInvite ? "Choose a password to accept your invitation and finish setting up your account." : "Choose a new password to finish resetting your account."}</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="new-password">New Password</Label>
              <Input
                id="new-password"
                type="password"
                placeholder="••••••••"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                required
                minLength={6}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="confirm-password">Confirm Password</Label>
              <Input
                id="confirm-password"
                type="password"
                placeholder="••••••••"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                required
                minLength={6}
              />
            </div>
            <Button type="submit" className="w-full" disabled={saving || !newPassword || !confirmPassword}>
              {saving ? "Updating Password..." : "Update Password"}
            </Button>
            <Button type="button" variant="outline" onClick={() => navigate("/auth")} className="w-full">
              <ArrowLeft className="mr-2 h-4 w-4" /> Back to Sign In
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}