"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Lock, Sparkles } from "lucide-react";

export default function LoginPage() {
    const [password, setPassword] = useState("");
    const [initPassword, setInitPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [error, setError] = useState("");
    const [isInitialized, setIsInitialized] = useState<boolean | null>(null);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [rememberMe, setRememberMe] = useState(false);
    const [duration, setDuration] = useState("1");
    const router = useRouter();

    useEffect(() => {
        const loadStatus = async () => {
            try {
                const res = await fetch("/api/settings/status", { cache: "no-store" });
                if (!res.ok) {
                    setIsInitialized(true);
                    return;
                }
                const data = await res.json();
                setIsInitialized(Boolean(data.initialized));
            } catch {
                setIsInitialized(true);
            }
        };
        loadStatus();
    }, []);

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();
        if (isSubmitting) return;
        setError("");
        setIsSubmitting(true);

        try {
            const res = await fetch("/api/auth/login", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    password,
                    rememberMe,
                    durationDays: parseInt(duration, 10),
                }),
            });

            if (res.ok) {
                router.push("/");
            } else {
                const data = await res.json();
                setError(data.error || "登录失败");
            }
        } catch {
            setError("发生错误，请重试");
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleInitialize = async (e: React.FormEvent) => {
        e.preventDefault();
        if (isSubmitting) return;
        setError("");

        if (initPassword.length < 6) {
            setError("密码至少 6 位");
            return;
        }

        if (initPassword !== confirmPassword) {
            setError("两次输入的密码不一致");
            return;
        }

        setIsSubmitting(true);
        try {
            const initRes = await fetch("/api/settings/init", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ password: initPassword }),
            });
            const initData = await initRes.json().catch(() => ({}));
            if (!initRes.ok) {
                setError(initData.error || "初始化失败");
                return;
            }

            const loginRes = await fetch("/api/auth/login", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    password: initPassword,
                    rememberMe: false,
                    durationDays: 1,
                }),
            });
            const loginData = await loginRes.json().catch(() => ({}));
            if (!loginRes.ok) {
                setError(loginData.error || "初始化成功，但自动登录失败，请手动登录");
                setIsInitialized(true);
                setPassword(initPassword);
                return;
            }

            router.push("/");
        } catch {
            setError("初始化失败，请重试");
        } finally {
            setIsSubmitting(false);
        }
    };

    if (isInitialized === null) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-background p-4">
                <div className="ui-card ui-enter w-full max-w-md p-8 text-center text-muted-foreground">加载中...</div>
            </div>
        );
    }

    return (
        <div className="min-h-screen flex items-center justify-center bg-background p-4">
            <div className="ui-card ui-enter w-full max-w-md space-y-8 p-8 shadow-xl">
                <div className="text-center space-y-2">
                    <div className="ui-float inline-flex items-center justify-center w-16 h-16 bg-primary rounded-2xl text-primary-foreground mb-4 shadow-sm">
                        <Sparkles size={32} />
                    </div>
                    <h1 className="text-3xl font-bold tracking-tight">{isInitialized ? "欢迎回来" : "首次初始化"}</h1>
                    <p className="text-muted-foreground">{isInitialized ? "请输入访问密码以继续。" : "请先设置访问密码，完成后将自动登录。"}</p>
                </div>

                <form onSubmit={isInitialized ? handleLogin : handleInitialize} className="space-y-4">
                    <div className="space-y-2">
                        {isInitialized ? (
                            <div className="relative">
                                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
                                <input
                                    type="password"
                                    placeholder="访问密码"
                                    value={password}
                                    onChange={(e) => setPassword(e.target.value)}
                                    className="ui-input pl-10 pr-4 py-3"
                                    required
                                />
                            </div>
                        ) : (
                            <>
                                <div className="relative">
                                    <Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
                                    <input
                                        type="password"
                                        placeholder="设置访问密码（至少6位）"
                                        value={initPassword}
                                        onChange={(e) => setInitPassword(e.target.value)}
                                        className="ui-input pl-10 pr-4 py-3"
                                        required
                                    />
                                </div>
                                <div className="relative">
                                    <Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
                                    <input
                                        type="password"
                                        placeholder="确认访问密码"
                                        value={confirmPassword}
                                        onChange={(e) => setConfirmPassword(e.target.value)}
                                        className="ui-input pl-10 pr-4 py-3"
                                        required
                                    />
                                </div>
                            </>
                        )}
                        {error && <p className="text-sm text-destructive font-medium">{error}</p>}
                    </div>

                    {isInitialized && (
                        <div className="flex items-center justify-between text-sm px-1">
                            <label className="flex items-center gap-2 cursor-pointer text-muted-foreground hover:text-foreground transition-colors select-none">
                                <input
                                    type="checkbox"
                                    checked={rememberMe}
                                    onChange={(e) => setRememberMe(e.target.checked)}
                                    className="w-4 h-4 rounded border-input bg-background/50 text-primary focus:ring-primary/50"
                                />
                                记住我
                            </label>

                            {rememberMe && (
                                <select
                                    value={duration}
                                    onChange={(e) => setDuration(e.target.value)}
                                    className="ui-select w-auto py-1 text-xs"
                                >
                                    <option value="1">1天</option>
                                    <option value="7">7天</option>
                                    <option value="30">30天</option>
                                </select>
                            )}
                        </div>
                    )}

                    <button type="submit" disabled={isSubmitting} className="ui-btn-primary w-full py-3 font-semibold shadow-md">
                        {isSubmitting ? "处理中..." : isInitialized ? "登录" : "完成初始化"}
                    </button>
                </form>

                <div className="text-center text-xs text-muted-foreground">NoteAI - 你的私人第二大脑</div>
            </div>
        </div>
    );
}
