import {useEffect, useState} from 'react';
import {Link, useSearchParams} from 'react-router-dom';
import {AlertCircle, ArrowRight, Command, Loader2, MailCheck, ShieldCheck} from 'lucide-react';
import {toast} from 'sonner';
import {apiEmailVerify} from '@/client';
import {AuthLayout} from '@/components/auth/auth-layout';
import {AnimatePresence, motion} from 'framer-motion';
import {getApiErrorMessage} from '@/lib/api-error';

type Status = 'idle' | 'loading' | 'success' | 'error';

export function VerifyEmailPage() {
    const [searchParams] = useSearchParams();
    const token = searchParams.get('token');
    const [status, setStatus] = useState<Status>('idle');
    const [errorMsg, setErrorMsg] = useState('');

    useEffect(() => {
        if (!token) {
            setStatus('error');
            setErrorMsg('Verification token is missing or malformed.');
            return;
        }

        setStatus('loading');
        // 模拟一点延迟以展示优雅的加载状态
        const timer = setTimeout(() => {
            apiEmailVerify({body: {token}})
                .then(() => {
                    setStatus('success');
                    toast.success('Identity verified successfully.');
                })
                .catch((err: unknown) => {
                    setStatus('error');
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    const msg = getApiErrorMessage(err, 'The verification link has expired or is invalid.');
                    setErrorMsg(msg);
                });
        }, 800);

        return () => clearTimeout(timer);
    }, [token]);

    return (
        <AuthLayout>
            <motion.div
                initial={{opacity: 0, y: 10}}
                animate={{opacity: 1, y: 0}}
                transition={{duration: 0.4}}
                className="w-full max-w-[400px] mx-auto text-center"
            >
                {/* 统一的 Logo 头部 */}
                <div className="flex flex-col items-center mb-10">
                    <div
                        className="h-12 w-12 bg-zinc-900 dark:bg-zinc-100 rounded-2xl flex items-center justify-center shadow-sm mb-6">
                        <Command className="h-6 w-6 text-white dark:text-zinc-900"/>
                    </div>
                    <h1 className="text-2xl font-bold tracking-tight text-zinc-900 dark:text-zinc-100">
                        Email Verification
                    </h1>
                </div>

                {/* 状态容器 */}
                <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)]">
                    <AnimatePresence mode="wait">
                        {status === 'loading' && (
                            <motion.div
                                key="loading"
                                initial={{opacity: 0}} animate={{opacity: 1}} exit={{opacity: 0}}
                                className="flex flex-col items-center py-4"
                            >
                                <div className="relative h-16 w-16 mb-6">
                                    <div
                                        className="absolute inset-0 rounded-full border-2 border-zinc-100 dark:border-zinc-800"/>
                                    <Loader2
                                        className="h-16 w-16 animate-spin text-zinc-900 dark:text-zinc-100 stroke-[1.5px]"/>
                                </div>
                                <p className="text-zinc-500 dark:text-zinc-400 animate-pulse">
                                    Verifying secure token...
                                </p>
                            </motion.div>
                        )}

                        {status === 'success' && (
                            <motion.div
                                key="success"
                                initial={{opacity: 0, scale: 0.95}}
                                animate={{opacity: 1, scale: 1}}
                                className="flex flex-col items-center"
                            >
                                <div
                                    className="h-20 w-20 rounded-full bg-zinc-50 dark:bg-zinc-900 flex items-center justify-center mb-6">
                                    <MailCheck className="h-10 w-10 text-zinc-900 dark:text-zinc-100"/>
                                </div>
                                <h2 className="text-lg font-bold text-zinc-900 dark:text-zinc-100 mb-2">
                                    Identity Confirmed
                                </h2>
                                <p className="text-zinc-500 dark:text-zinc-400 mb-8 text-sm leading-relaxed">
                                    Your email has been successfully verified. You now have full access to the GitDataAI
                                    platform.
                                </p>
                                <Link
                                    to="/"
                                    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 group"
                                >
                                    Go to Dashboard
                                    <ArrowRight
                                        className="ml-2 h-4 w-4 group-hover:translate-x-0.5 transition-transform"/>
                                </Link>
                            </motion.div>
                        )}

                        {status === 'error' && (
                            <motion.div
                                key="error"
                                initial={{opacity: 0, scale: 0.95}}
                                animate={{opacity: 1, scale: 1}}
                                className="flex flex-col items-center"
                            >
                                <div
                                    className="h-20 w-20 rounded-full bg-red-50 dark:bg-red-950/20 flex items-center justify-center mb-6">
                                    <AlertCircle className="h-10 w-10 text-red-600 dark:text-red-400"/>
                                </div>
                                <h2 className="text-lg font-bold text-zinc-900 dark:text-zinc-100 mb-2">
                                    Verification Failed
                                </h2>
                                <p className="text-red-600/80 dark:text-red-400/80 mb-8 text-sm leading-relaxed">
                                    {errorMsg}
                                </p>
                                <div className="w-full space-y-3">
                                    <Link
                                        to="/settings/account"
                                        className="w-full h-11 flex items-center justify-center rounded-xl font-bold border border-zinc-200 dark:border-zinc-800 hover:bg-zinc-50 dark:hover:bg-zinc-900 text-sm"
                                    >Back to Settings</Link>
                                    <p className="text-xs text-zinc-400">
                                        Need help? <Link to="/support"
                                                         className="text-zinc-900 dark:text-zinc-100 underline underline-offset-2">Contact
                                        engineering support</Link>
                                    </p>
                                </div>
                            </motion.div>
                        )}
                    </AnimatePresence>
                </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">
                        <ShieldCheck className="size-3"/> Encrypted Link
                    </div>
                    <div
                        className="flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-widest text-zinc-500">
                        <ShieldCheck className="size-3"/> SOC2 Compliant
                    </div>
                </div>
            </motion.div>
        </AuthLayout>
    );
}