"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button, Input, Card } from "@/components/ui";

export default function LoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [mode, setMode] = useState<"login" | "signup">("login");
  // Shown after signup — user must verify before they can sign in.
  const [emailSent, setEmailSent] = useState(false);
  // Set when sign-in is blocked because the account isn't verified.
  const [needsVerification, setNeedsVerification] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email || !password) return;
    setLoading(true);
    setError("");
    setNeedsVerification(false);

    try {
      const res = await fetch("/api/auth/signin", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password, action: mode }),
      });
      const data = await res.json();

      if (!res.ok) {
        if (data.needsVerification) {
          // Sign-in blocked: account exists but email not verified.
          setNeedsVerification(true);
          setError(data.error || "Please verify your email.");
        } else {
          setError(data.error || "Failed to sign in");
        }
        return;
      }

      // Signup success -> no session yet, must verify email.
      if (data.needsVerification) {
        setEmailSent(true);
        return;
      }

      // Sign-in success.
      router.push(data.familyId ? "/home" : "/onboarding");
    } catch {
      setError("Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  const handleResend = async () => {
    setLoading(true);
    try {
      await fetch("/api/auth/resend-verification", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      setEmailSent(true);
      setNeedsVerification(false);
    } finally {
      setLoading(false);
    }
  };

  // ----- "Check your email" screen -----
  if (emailSent) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-rose-50 to-amber-50 dark:from-gray-900 dark:to-gray-800 flex items-center justify-center p-4">
        <Card className="max-w-md w-full text-center" padding="lg">
          <div className="text-4xl mb-4">&#x2709;&#xFE0F;</div>
          <h1 className="text-2xl font-bold mb-2 dark:text-white">Check your email</h1>
          <p className="text-gray-600 dark:text-gray-400 mb-4">
            We sent a verification link to <strong>{email}</strong>. Click it to
            activate your account.
          </p>
          <p className="text-sm text-gray-500">The link expires in 24 hours.</p>
        </Card>
      </div>
    );
  }

  // ----- Login / Signup form -----
  return (
    <div className="min-h-screen bg-gradient-to-br from-rose-50 to-amber-50 dark:from-gray-900 dark:to-gray-800 flex items-center justify-center p-4">
      <Card className="max-w-md w-full" padding="lg">
        <h1 className="text-2xl font-bold text-center mb-6 dark:text-white">
          {mode === "login" ? "Welcome Back" : "Create Account"}
        </h1>

        {/* Google — full server-side OAuth round trip. */}
        <button
          type="button"
          onClick={() => { window.location.href = "/api/auth/google"; }}
          className="w-full flex items-center justify-center gap-2 border border-gray-300 dark:border-gray-600 rounded-lg py-3 mb-4 font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-800"
        >
          <svg className="w-5 h-5" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
            <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
            <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05"/>
            <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
          </svg>
          Continue with Google
        </button>

        <div className="flex items-center gap-3 my-4">
          <div className="flex-1 h-px bg-gray-200 dark:bg-gray-700" />
          <span className="text-xs text-gray-400">or</span>
          <div className="flex-1 h-px bg-gray-200 dark:bg-gray-700" />
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <Input label="Email" type="email" value={email}
                 onChange={(e) => setEmail(e.target.value)} required />
          <Input label="Password" type="password" value={password}
                 onChange={(e) => setPassword(e.target.value)}
                 required minLength={8} error={error || undefined} />
          <Button type="submit" fullWidth size="lg" loading={loading}>
            {mode === "login" ? "Sign In" : "Sign Up"}
          </Button>
        </form>

        {needsVerification && (
          <button type="button" onClick={handleResend}
                  className="w-full text-sm text-rose-500 font-medium mt-3">
            Resend verification email
          </button>
        )}

        <p className="text-center mt-4 text-sm text-gray-500 dark:text-gray-400">
          {mode === "login" ? "No account? " : "Already have an account? "}
          <button type="button"
                  onClick={() => {
                    setMode(mode === "login" ? "signup" : "login");
                    setError(""); setNeedsVerification(false);
                  }}
                  className="text-rose-500 font-medium">
            {mode === "login" ? "Sign Up" : "Sign In"}
          </button>
        </p>
      </Card>
    </div>
  );
}
