import {useState, useEffect} from "react";
import {Link, useSearchParams} from "react-router-dom";
import {ArrowLeft, CheckCircle2, Eye, EyeOff, Loader2, ShieldAlert} from "lucide-react";
import {toast} from "sonner";
import {apiUserConfirmPasswordReset} 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 ConfirmPasswordResetPage() {
    const [searchParams] = useSearchParams();
    const token = searchParams.get("token") ?? "";

    const [form, setForm] = useState({new_password: "", confirm_password: ""});
    const [showPassword, setShowPassword] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [done, setDone] = useState(false);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        if (!token) {
            setError("Missing reset token. Please use the link from your email.");
        }
    }, [token]);

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

        if (!form.new_password) {
            setError("New password is required.");
            return;
        }
        if (form.new_password.length < 8) {
            setError("Password must be at least 8 characters.");
            return;
        }
        if (!/[A-Z]/.test(form.new_password)) {
            setError("Password must contain at least one uppercase letter.");
            return;
        }
        if (!/[a-z]/.test(form.new_password)) {
            setError("Password must contain at least one lowercase letter.");
            return;
        }
        if (!/[0-9]/.test(form.new_password)) {
            setError("Password must contain at least one digit.");
            return;
        }
        if (form.new_password !== form.confirm_password) {
            setError("Passwords do not match.");
            return;
        }

        setIsLoading(true);
        try {
            const resp = await apiUserConfirmPasswordReset({
                body: {token, new_password: form.new_password},
            });
            if (resp.data?.code !== 0) {
                throw new Error(resp.data?.message || "Failed to reset password.");
            }
            setDone(true);
            toast.success("Password reset successful!");
        } catch (err: unknown) {
            const msg = getApiErrorMessage(err, "Failed to reset password. The link may have expired.");
            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">
                    {!done ? (
                        <motion.div
                            key="reset-form"
                            initial={{opacity: 0, x: -10}}
                            animate={{opacity: 1, x: 0}}
                            exit={{opacity: 0, x: 10}}
                        >
                            {/* Header */}
                            <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">
                                    <ShieldAlert 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">
                                        Set new password
                                    </h1>
                                    <p className="mt-2 text-sm text-zinc-500 dark:text-zinc-400">
                                        Create a strong password for your account.
                                    </p>
                                </div>
                            </div>

                            {/* Card form */}
                            <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">
                                    {/* Token error (no token in URL) */}
                                    {!token && (
                                        <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>Missing reset token. Please use the link from your email.</p>
                                        </motion.div>
                                    )}

                                    {/* New password */}
                                    <div className="space-y-2">
                                        <label htmlFor="new_password"
                                               className="text-sm font-medium text-zinc-700 dark:text-zinc-300 ml-0.5">
                                            New password
                                        </label>
                                        <div className="relative">
                                            <Input
                                                id="new_password"
                                                type={showPassword ? "text" : "password"}
                                                placeholder="At least 8 characters"
                                                value={form.new_password}
                                                onChange={(e) => {
                                                    setForm({...form, new_password: e.target.value});
                                                    if (error) setError(null);
                                                }}
                                                className="h-10 pr-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 || !token}
                                            />
                                            <button
                                                type="button"
                                                onClick={() => setShowPassword((v) => !v)}
                                                className="absolute right-3 top-1/2 -translate-y-1/2 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors"
                                            >
                                                {showPassword ? (
                                                    <EyeOff className="size-4"/>
                                                ) : (
                                                    <Eye className="size-4"/>
                                                )}
                                            </button>
                                        </div>
                                    </div>

                                    {/* Confirm password */}
                                    <div className="space-y-2">
                                        <label htmlFor="confirm_password"
                                               className="text-sm font-medium text-zinc-700 dark:text-zinc-300 ml-0.5">
                                            Confirm password
                                        </label>
                                        <Input
                                            id="confirm_password"
                                            type={showPassword ? "text" : "password"}
                                            placeholder="Repeat your password"
                                            value={form.confirm_password}
                                            onChange={(e) => {
                                                setForm({...form, confirm_password: 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 || !token}
                                        />
                                    </div>

                                    {/* Error message */}
                                    {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 || !token}
                                        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"/>
                                        ) : (
                                            "Reset Password"
                                        )}
                                    </Button>
                                </form>
                            </div>

                            {/* Footer link */}
                            <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="done-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-emerald-100 dark:bg-emerald-900/30 mb-6">
                                    <CheckCircle2 className="h-8 w-8 text-emerald-600 dark:text-emerald-400"/>
                                </div>
                                <h1 className="text-2xl font-bold tracking-tight text-zinc-900 dark:text-zinc-100 mb-3">
                                    Password reset complete
                                </h1>
                                <p className="text-zinc-500 dark:text-zinc-400 mb-8 leading-relaxed">
                                    Your password has been updated. You can now sign in with your new password.
                                </p>

                                <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"
                                >
                                    Sign in
                                </Link>
                            </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"/> Password Updated
                                </div>
                                <div
                                    className="flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-widest text-zinc-500">
                                    <CheckCircle2 className="size-3"/> Secure Connection
                                </div>
                            </div>
                        </motion.div>
                    )}
                </AnimatePresence>
            </motion.div>
        </AuthLayout>
    );
}
