"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { KeyRound, Mail } from "lucide-react";
import { useRouter } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

export default function ResetPasswordPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [recoveryMode, setRecoveryMode] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [requestLoading, setRequestLoading] = useState(false);
  const [updateLoading, setUpdateLoading] = useState(false);

  useEffect(() => {
    let mounted = true;
    let unsubscribe: (() => void) | null = null;

    async function loadSession() {
      const hasRecoveryParams =
        window.location.hash.includes("type=recovery") ||
        window.location.search.includes("type=recovery") ||
        window.location.search.includes("code=");

      if (!hasRecoveryParams) return;

      try {
        const supabase = createClient();
        const {
          data: { subscription },
        } = supabase.auth.onAuthStateChange((event, session) => {
          if (!mounted) return;

          if (event === "PASSWORD_RECOVERY" || !!session?.user) {
            setRecoveryMode(true);
          }
        });
        unsubscribe = () => subscription.unsubscribe();

        const {
          data: { session },
        } = await supabase.auth.getSession();

        if (mounted && session?.user) {
          setRecoveryMode(true);
        }
      } catch {
        // If auth is temporarily unreachable, keep the page in request-reset mode.
      }
    }

    void loadSession();

    return () => {
      mounted = false;
      unsubscribe?.();
    };
  }, []);

  async function handleRequestReset(event: React.FormEvent) {
    event.preventDefault();
    if (!email.trim() || requestLoading) return;

    setError(null);
    setMessage(null);
    setRequestLoading(true);

    try {
      const response = await fetch("/api/auth/password-reset", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: email.trim() }),
      });
      const result = (await response.json()) as { error?: string };

      if (!response.ok) {
        setError(result.error || "Recovery Link konnte nicht gesendet werden.");
        setRequestLoading(false);
        return;
      }
    } catch {
      setError("Der Auth-Dienst ist gerade nicht erreichbar. Prüfe deine Internetverbindung und die Supabase-Konfiguration.");
      setRequestLoading(false);
      return;
    }

    setMessage(`Recovery link sent to ${email.trim()}.`);
    setRequestLoading(false);
  }

  async function handleUpdatePassword(event: React.FormEvent) {
    event.preventDefault();
    if (!password || !confirmPassword || updateLoading) return;

    if (password !== confirmPassword) {
      setError("Passwords do not match.");
      return;
    }

    setError(null);
    setMessage(null);
    setUpdateLoading(true);

    const supabase = createClient();
    try {
      const { error: updateError } = await supabase.auth.updateUser({
        password,
      });

      if (updateError) {
        setError(updateError.message);
        setUpdateLoading(false);
        return;
      }
    } catch {
      setError("Der Auth-Dienst ist gerade nicht erreichbar. Bitte versuche es gleich noch einmal.");
      setUpdateLoading(false);
      return;
    }

    await supabase.auth.signOut();
    router.push("/login?message=Password updated. Sign in with your new password.");
    router.refresh();
  }

  return (
    <>
      <div className="mb-8">
        <h1 className="text-2xl font-bold tracking-tight lg:hidden">Mindavio</h1>
        <h2 className="mt-2 text-xl font-semibold lg:mt-0 lg:text-2xl">
          {recoveryMode ? "Set a new password" : "Reset your password"}
        </h2>
        <p className="mt-1 text-sm text-muted-foreground">
          {recoveryMode
            ? "Choose a fresh password for your account."
            : "We will email you a secure recovery link."}
        </p>
      </div>

      {!recoveryMode ? (
        <form onSubmit={handleRequestReset} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              type="email"
              placeholder="you@example.com"
              value={email}
              onChange={(event) => setEmail(event.target.value)}
              required
              autoFocus
            />
          </div>

          {error && <p className="text-sm text-destructive">{error}</p>}
          {message && <p className="text-sm text-emerald-600">{message}</p>}

          <Button type="submit" className="w-full" disabled={requestLoading}>
            <Mail className="h-4 w-4" />
            {requestLoading ? "Sending..." : "Send recovery link"}
          </Button>
        </form>
      ) : (
        <form onSubmit={handleUpdatePassword} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="password">New password</Label>
            <Input
              id="password"
              type="password"
              placeholder="At least 12 characters"
              value={password}
              onChange={(event) => setPassword(event.target.value)}
              required
              minLength={12}
              autoComplete="new-password"
              autoFocus
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="confirm-password">Confirm password</Label>
            <Input
              id="confirm-password"
              type="password"
              placeholder="Repeat your new password"
              value={confirmPassword}
              onChange={(event) => setConfirmPassword(event.target.value)}
              required
              minLength={12}
              autoComplete="new-password"
            />
          </div>

          {error && <p className="text-sm text-destructive">{error}</p>}
          {message && <p className="text-sm text-emerald-600">{message}</p>}

          <Button type="submit" className="w-full" disabled={updateLoading}>
            <KeyRound className="h-4 w-4" />
            {updateLoading ? "Updating..." : "Update password"}
          </Button>
        </form>
      )}

      <p className="mt-6 text-center text-sm text-muted-foreground">
        Back to{" "}
        <Link href="/login" className="font-medium text-foreground hover:underline">
          Sign in
        </Link>
      </p>
    </>
  );
}
