import {useEffect, useState} from 'react';
import {useNavigate, useSearchParams} from 'react-router-dom';
import {AlertTriangle, ArrowRight, Command, Loader2, ShieldCheck, Sparkles, Users} from 'lucide-react';
import {toast} from 'sonner';
import {workspaceAcceptInvitation} from '@/client';
import {AuthLayout} from '@/components/auth/auth-layout';
import {Button} from '@/components/ui/button';
import {AnimatePresence, motion} from 'framer-motion';
import {getApiErrorMessage} from '@/lib/api-error';

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

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

    useEffect(() => {
        if (!token) {
            setStatus('error');
            setErrorMsg('The invitation link is missing a valid security token.');
            return;
        }

        setStatus('loading');

        // 稍微增加一点处理感延迟，提升 UI 的稳重感
        const timer = setTimeout(() => {
            workspaceAcceptInvitation({body: {token}})
                .then((resp) => {
                    setStatus('success');
                    const slug = resp.data?.data?.slug;
                    if (slug) {
                        setWorkspaceSlug(slug);
                        toast.success('Successfully joined the workspace');
                        // 1.5秒后自动跳转，给用户一点时间看成功状态
                        setTimeout(() => navigate(`/w/${slug}`), 2000);
                    }
                })
                .catch((err: unknown) => {
                    setStatus('error');
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    const msg = getApiErrorMessage(err, 'The invitation link has expired or already been used.');
                    setErrorMsg(msg);
                });
        }, 1000);

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

    return (
        <AuthLayout>
            <motion.div
                initial={{opacity: 0, y: 10}}
                animate={{opacity: 1, y: 0}}
                transition={{duration: 0.4}}
                className="w-full max-w-[420px] mx-auto text-center"
            >
                {/* 统一的品牌头部 */}
                <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">
                        Workspace Invitation
                    </h1>
                </div>

                {/* 状态卡片容器 */}
                <div
                    className="bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800/80 rounded-[2.5rem] p-8 md:p-12 shadow-[0_8px_40px_rgba(0,0,0,0.03)] dark:shadow-none relative overflow-hidden">
                    <AnimatePresence mode="wait">
                        {(status === 'idle' || status === 'loading') && (
                            <motion.div
                                key="loading"
                                initial={{opacity: 0}}
                                animate={{opacity: 1}}
                                exit={{opacity: 0, scale: 0.95}}
                                className="flex flex-col items-center py-4"
                            >
                                <div className="relative h-16 w-16 mb-8">
                                    <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>
                                <h2 className="text-zinc-900 dark:text-zinc-100 font-medium mb-2">Validating invite</h2>
                                <p className="text-zinc-500 dark:text-zinc-400 text-sm">
                                    Checking permissions and workspace status...
                                </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-8 relative">
                                    <Users className="h-10 w-10 text-zinc-900 dark:text-zinc-100"/>
                                    <motion.div
                                        initial={{scale: 0}} animate={{scale: 1}}
                                        className="absolute -top-1 -right-1 h-7 w-7 bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 rounded-full flex items-center justify-center shadow-sm text-zinc-900 dark:text-zinc-100"
                                    >
                                        <Sparkles className="size-3.5 fill-current"/>
                                    </motion.div>
                                </div>
                                <h2 className="text-xl font-bold text-zinc-900 dark:text-zinc-100 mb-3">
                                    Welcome Aboard!
                                </h2>
                                <p className="text-zinc-500 dark:text-zinc-400 mb-10 text-sm leading-relaxed">
                                    Invitation accepted. You've been added to the team. We're redirecting you to the
                                    dashboard now.
                                </p>
                                <Button
                                    onClick={() => navigate(`/w/${workspaceSlug || 'me'}`)}
                                    className="w-full h-12 bg-zinc-900 dark:bg-zinc-100 text-white dark:text-zinc-900 hover:bg-zinc-800 dark:hover:bg-white rounded-2xl font-bold transition-all group"
                                >
                                    Proceed Manually
                                    <ArrowRight
                                        className="ml-2 h-4 w-4 group-hover:translate-x-1 transition-transform"/>
                                </Button>
                            </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-8">
                                    <AlertTriangle className="h-10 w-10 text-red-600 dark:text-red-400"/>
                                </div>
                                <h2 className="text-xl font-bold text-zinc-900 dark:text-zinc-100 mb-3">
                                    Invalid Invite
                                </h2>
                                <p className="text-red-600/80 dark:text-red-400/80 mb-10 text-sm leading-relaxed px-4">
                                    {errorMsg}
                                </p>
                                <div className="w-full space-y-3">
                                    <Button
                                        onClick={() => navigate('/')}
                                        variant="outline"
                                        className="w-full h-12 border-zinc-200 dark:border-zinc-800 rounded-2xl font-bold hover:bg-zinc-50 dark:hover:bg-zinc-900 transition-all text-zinc-900 dark:text-zinc-100"
                                    >
                                        Return Home
                                    </Button>
                                    <p className="text-xs text-zinc-400 pt-2">
                                        Need a new link? <a href="mailto:support@gitdata.ai"
                                                            className="text-zinc-900 dark:text-zinc-100 underline underline-offset-2">Contact
                                        workspace admin</a>
                                    </p>
                                </div>
                            </motion.div>
                        )}
                    </AnimatePresence>
                </div>

                <div className="mt-12 flex items-center justify-center gap-8 opacity-30 grayscale pointer-events-none">
                    <div
                        className="flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.2em] text-zinc-500">
                        <ShieldCheck className="size-3.5"/> SECURE JOIN
                    </div>
                    <div
                        className="flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.2em] text-zinc-500">
                        <ShieldCheck className="size-3.5"/> DATA OWNERSHIP
                    </div>
                </div>
            </motion.div>
        </AuthLayout>
    );
}