import {useState} from "react";
import {Link} from "react-router-dom";
import {ArrowLeft, ArrowRight, CheckCircle2, Command, Loader2, Mail, ShieldAlert} from "lucide-react";
import {toast} from "sonner";
import {apiUserRequestPasswordReset} from "@/client";
import {getApiErrorMessage} from "@/lib/api-error";
import {AuthLayout} from "@/components/auth/auth-layout";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {AnimatePresence, motion} from "framer-motion";

export function PasswordResetPage() {
    const [form, setForm] = useState({email: ""});
    const [isLoading, setIsLoading] = useState(false);
    const [sent, setSent] = useState(false);
    const [error, setError] = useState<string | null>(null);

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

        if (!form.email.trim()) {
            setError("Email address is required.");
            return;
        }
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
            setError("Please enter a valid email address.");
            return;
        }

        setIsLoading(true);
        try {
            const resp = await apiUserRequestPasswordReset({body: {email: form.email}});
            if (resp.data?.code !== 0) {
                throw new Error(resp.data?.message || "Failed to send reset email.");
            }
            setSent(true);
            toast.success("Reset link sent!");
        } catch (err: unknown) {
            const msg = getApiErrorMessage(err, "Failed to send reset email.");
            setError(msg);
            toast.error(msg);
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <AuthLayout>
            <motion.div
                initial={{opacity: 0, y: 10}}
                animate={{opacity: 1, y: 0}}
                transition={{duration: 0.4}}
                className="w-full max-w-[380px] mx-auto"
            >
                <AnimatePresence mode="wait">
                    {!sent ? (
                        <motion.div
                            key="reset-form"
                            initial={{opacity: 0, x: -10}}
                            animate={{opacity: 1, x: 0}}
                            exit={{opacity: 0, x: 10}}
                        >
                            {/* 头部 */}
                            <div className="flex flex-col items-center text-center mb-8 space-y-4">
                                <div
                                    className="h-12 w-12 bg-zinc-900 dark:bg-zinc-100 rounded-2xl flex items-center justify-center shadow-sm">
                                    <Command className="h-6 w-6 text-white dark:text-zinc-900"/>
                                </div>
                                <div>
                                    <h1 className="text-2xl font-semibold tracking-tight text-zinc-900 dark:text-zinc-100">
                                        Reset password
                                    </h1>
                                    <p className="mt-2 text-sm text-zinc-500 dark:text-zinc-400">
                                        Enter your email and we'll send you a link to get back into your account.
                                    </p>
                                </div>
                            </div>

                            {/* 卡片表单 */}
                            <div
                                className="bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800/80 rounded-3xl p-6 md:p-8 shadow-[0_8px_30px_rgb(0,0,0,0.02)]">
                                <form onSubmit={handleSubmit} className="space-y-5">
                                    <div className="space-y-2">
                                        <label htmlFor="email"
                                               className="text-sm font-medium text-zinc-700 dark:text-zinc-300 ml-0.5">
                                            Email address
                                        </label>
                                        <Input
                                            id="email"
                                            type="email"
                                            placeholder="name@example.com"
                                            value={form.email}
                                            onChange={(e) => {
                                                setForm({email: e.target.value});
                                                if (error) setError(null);
                                            }}
                                            className="h-10 bg-zinc-50/50 dark:bg-zinc-900/50 border-zinc-200 dark:border-zinc-800 rounded-xl focus-visible:ring-1 focus-visible:ring-zinc-400"
                                            disabled={isLoading}
                                        />
                                    </div>

                                    {error && (
                                        <motion.div
                                            initial={{opacity: 0, scale: 0.98}}
                                            animate={{opacity: 1, scale: 1}}
                                            className="flex items-start gap-2 p-3 text-sm text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-950/20 border border-red-100 dark:border-red-900/30 rounded-xl"
                                        >
                                            <ShieldAlert className="size-4 mt-0.5 shrink-0"/>
                                            <p>{error}</p>
                                        </motion.div>
                                    )}

                                    <Button
                                        type="submit"
                                        disabled={isLoading}
                                        className="w-full h-11 bg-zinc-900 dark:bg-zinc-100 text-white dark:text-zinc-900 hover:bg-zinc-800 dark:hover:bg-white rounded-xl font-bold transition-all group shadow-sm"
                                    >
                                        {isLoading ? (
                                            <Loader2 className="size-4 animate-spin"/>
                                        ) : (
                                            <span className="flex items-center justify-center gap-2">
                                                Send Reset Link
                                                <ArrowRight
                                                    className="size-4 opacity-70 group-hover:translate-x-0.5 transition-transform"/>
                                            </span>
                                        )}
                                    </Button>
                                </form>
                            </div>

                            {/* 底部链接 */}
                            <div className="mt-8 text-center">
                                <Link
                                    to="/auth/login"
                                    className="inline-flex items-center gap-2 text-sm font-medium text-zinc-500 hover:text-zinc-900 dark:hover:text-zinc-200 transition-colors"
                                >
                                    <ArrowLeft className="size-4"/>
                                    Back to sign in
                                </Link>
                            </div>
                        </motion.div>
                    ) : (
                        <motion.div
                            key="sent-state"
                            initial={{opacity: 0, scale: 0.95}}
                            animate={{opacity: 1, scale: 1}}
                            className="text-center"
                        >
                            {/* 成功状态显示 */}
                            <div
                                className="bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800/80 rounded-3xl p-8 md:p-10 shadow-[0_8px_30px_rgb(0,0,0,0.02)]">
                                <div
                                    className="inline-flex h-16 w-16 items-center justify-center rounded-full bg-zinc-100 dark:bg-zinc-900 mb-6">
                                    <Mail className="h-8 w-8 text-zinc-900 dark:text-zinc-100"/>
                                </div>
                                <h1 className="text-2xl font-bold tracking-tight text-zinc-900 dark:text-zinc-100 mb-3">
                                    Check your email
                                </h1>
                                <p className="text-zinc-500 dark:text-zinc-400 mb-8 leading-relaxed">
                                    We've sent a secure link to <span
                                    className="font-semibold text-zinc-900 dark:text-zinc-200">{form.email}</span>.
                                    Click the link to reset your passphrase.
                                </p>

                                <div className="space-y-4">
                                    <Link
                                        to="/auth/login"
                                        className="w-full h-11 flex items-center justify-center rounded-xl font-bold transition-all bg-zinc-900 text-white hover:bg-zinc-800 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-white text-sm"
                                    >Return to Sign In</Link>
                                    <p className="text-xs text-zinc-400">
                                        Didn't receive the email? Check your spam folder or{" "}
                                        <button
                                            onClick={() => setSent(false)}
                                            className="text-zinc-900 dark:text-zinc-200 font-bold hover:underline"
                                        >
                                            try again
                                        </button>
                                    </p>
                                </div>
                            </div>

                            <div className="mt-10 flex items-center justify-center gap-6 opacity-30 grayscale">
                                <div
                                    className="flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-widest text-zinc-500">
                                    <CheckCircle2 className="size-3"/> Secure Link
                                </div>
                                <div
                                    className="flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-widest text-zinc-500">
                                    <CheckCircle2 className="size-3"/> 24h Expiry
                                </div>
                            </div>
                        </motion.div>
                    )}
                </AnimatePresence>
            </motion.div>
        </AuthLayout>
    );
}