import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { LoaderCircle, Mail, RefreshCw } from 'lucide-react';
import { FormEventHandler, memo, useEffect, useMemo, useRef, useState } from 'react';
import { Toaster, toast } from 'sonner';

import AppLogoIcon from '@/components/layout/app-logo-icon';
import { Button } from '@/components/ui/button';
import { GradientMesh } from '@/components/ui/gradient-mesh';

interface Props {
    email: string;
    canResend: boolean;
}

// Memoized background component to prevent re-renders
const BackgroundComponent = memo(function BackgroundComponent({ loginBackgroundUrl }: { loginBackgroundUrl: string | null }) {
    const isVideo = loginBackgroundUrl?.toLowerCase().endsWith('.mp4');

    return (
        <div className="bg-muted relative hidden lg:block">
            {loginBackgroundUrl ? (
                isVideo ? (
                    <video autoPlay loop muted playsInline className="absolute inset-0 h-full w-full object-cover">
                        <source src={loginBackgroundUrl} type="video/mp4" />
                    </video>
                ) : (
                    <img
                        src={loginBackgroundUrl}
                        alt=""
                        className="absolute inset-0 h-full w-full object-cover"
                        loading="lazy"
                        decoding="async"
                        fetchPriority="low"
                    />
                )
            ) : (
                <GradientMesh
                    colors={['#bcecf6', '#00aaff', '#ffd447']}
                    distortion={8}
                    swirl={0.2}
                    speed={1}
                    rotation={90}
                    waveAmp={0.2}
                    waveFreq={20}
                    waveSpeed={0.2}
                    grain={0.06}
                />
            )}
        </div>
    );
});

export default function ActivationPending({ email, canResend }: Props) {
    const { appName, appLogoUrl, loginBackgroundUrl, loginBackgroundPosition, heroUseLogo: _heroUseLogo } = usePage().props as any;
    const { post, processing } = useForm({});
    const [countdown, setCountdown] = useState(canResend ? 0 : 60);
    const observerRef = useRef<MutationObserver | null>(null);

    useEffect(() => {
        if (countdown > 0) {
            const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
            return () => clearTimeout(timer);
        }
    }, [countdown]);

    // Optimized dark theme effect - same as login/register
    useEffect(() => {
        const html = document.documentElement;

        // Add dark theme only if not already present
        if (!html.classList.contains('dark')) {
            html.classList.add('dark');
        }
        html.setAttribute('data-force-dark', 'true');

        // Create observer
        if (!observerRef.current) {
            observerRef.current = new MutationObserver((mutations) => {
                for (const mutation of mutations) {
                    if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                        if (!html.classList.contains('dark')) {
                            html.classList.add('dark');
                        }
                        break;
                    }
                }
            });

            observerRef.current.observe(html, { attributes: true, attributeFilter: ['class'] });
        }

        return () => {
            if (observerRef.current) {
                observerRef.current.disconnect();
                observerRef.current = null;
            }
            html.classList.remove('dark');
            html.removeAttribute('data-force-dark');
        };
    }, []);

    // Memoize background settings - same as register
    const backgroundSettings = useMemo(
        () => ({
            onLeft: loginBackgroundPosition === 'left',
            isFullWidth: loginBackgroundPosition === 'full',
            isVideo: loginBackgroundUrl?.toLowerCase().endsWith('.mp4'),
        }),
        [loginBackgroundPosition, loginBackgroundUrl],
    );

    const handleResend: FormEventHandler = (e) => {
        e.preventDefault();
        post('/activation/resend', {
            onSuccess: () => {
                toast.success('Activation email resent successfully!');
                setCountdown(60);
            },
            onError: () => {
                toast.error('Failed to send email. Please try again.');
            },
        });
    };

    // Full width layout - same as login/register
    if (backgroundSettings.isFullWidth) {
        return (
            <>
                <Head title={`Account Activation - ${appName}`} />
                <Toaster position="top-right" richColors closeButton duration={4000} />

                <div className="relative flex h-svh items-center justify-center py-8">
                    {/* Full width background */}
                    <div className="absolute inset-0 z-0">
                        {loginBackgroundUrl ? (
                            backgroundSettings.isVideo ? (
                                <video autoPlay loop muted playsInline className="h-full w-full object-cover">
                                    <source src={loginBackgroundUrl} type="video/mp4" />
                                </video>
                            ) : (
                                <img
                                    src={loginBackgroundUrl}
                                    alt=""
                                    className="h-full w-full object-cover"
                                    loading="lazy"
                                    decoding="async"
                                    fetchPriority="low"
                                />
                            )
                        ) : (
                            <GradientMesh
                                colors={['#bcecf6', '#00aaff', '#ffd447']}
                                distortion={8}
                                swirl={0.2}
                                speed={1}
                                rotation={90}
                                waveAmp={0.2}
                                waveFreq={20}
                                waveSpeed={0.2}
                                grain={0.06}
                            />
                        )}
                        {/* Overlay for readability */}
                        <div className="absolute inset-0 bg-black/40" />
                    </div>

                    {/* Centered card */}
                    <div className="relative z-10 mx-4 w-full max-w-md">
                        <div className="bg-background/25 scrollbar-hide max-h-[90svh] overflow-y-auto rounded-xl p-8 shadow-2xl backdrop-blur-sm">
                            <div className="flex flex-col items-center gap-6 text-center">
                                {/* Logo */}
                                <Link href="/" className="flex items-center">
                                    {appLogoUrl ? (
                                        <img src={appLogoUrl} alt={appName || 'Logo'} className="h-24 w-24 object-contain" />
                                    ) : (
                                        <AppLogoIcon className="h-24 w-24 fill-current text-white" />
                                    )}
                                </Link>

                                {/* Icon */}
                                <div className="bg-primary/20 flex h-20 w-20 items-center justify-center rounded-full">
                                    <Mail className="text-primary h-10 w-10" />
                                </div>

                                {/* Header */}
                                <div className="space-y-2">
                                    <h1 className="text-2xl font-bold text-white">Account Activation Required</h1>
                                    <p className="text-muted-foreground text-sm">We have sent an activation email to:</p>
                                    <p className="font-medium text-white">{email}</p>
                                </div>

                                {/* Instructions */}
                                <div className="bg-muted/30 w-full rounded-lg p-4">
                                    <p className="text-muted-foreground text-sm">
                                        Please check your email inbox and click the activation link to activate your account. Don&apos;t forget to
                                        check your spam folder if you can&apos;t find the email.
                                    </p>
                                </div>

                                {/* Resend button */}
                                <form onSubmit={handleResend} className="w-full">
                                    <Button
                                        type="submit"
                                        variant="outline"
                                        className="w-full border-none bg-gradient-to-r from-[#7a5c1e] via-[#c9a84c] to-[#7a5c1e] text-black shadow-[0_0_15px_rgba(201,168,76,0.3)] hover:from-[#8a6c2e] hover:via-[#d9b85c] hover:to-[#8a6c2e]"
                                        disabled={processing || countdown > 0}
                                    >
                                        {processing ? <LoaderCircle className="mr-2 h-4 w-4 animate-spin" /> : <RefreshCw className="mr-2 h-4 w-4" />}
                                        {countdown > 0 ? `Resend Email (${countdown}s)` : 'Resend Email'}
                                    </Button>
                                </form>

                                {/* Back to login link */}
                                <Link href="/login" className="text-muted-foreground text-sm transition-colors hover:text-white">
                                    Back to Login
                                </Link>
                            </div>
                        </div>
                    </div>
                </div>
            </>
        );
    }

    // Split layout (left or right) - same as login/register/set-password
    return (
        <>
            <Head title={`Account Activation - ${appName}`} />
            <Toaster position="top-right" richColors closeButton duration={4000} />

            <div className={`grid h-svh ${backgroundSettings.onLeft ? 'lg:grid-cols-[75%_25%]' : 'lg:grid-cols-[25%_75%]'} overflow-hidden`}>
                {/* Background - conditionally first for left layout */}
                {backgroundSettings.onLeft && <BackgroundComponent loginBackgroundUrl={loginBackgroundUrl} />}

                {/* Content */}
                <div className="flex flex-col gap-4 overflow-y-auto p-6 md:p-10">
                    <div className="flex justify-center gap-2 md:justify-start">
                        <Link href="/" className="flex items-center gap-2 font-medium">
                            {appLogoUrl ? (
                                <img src={appLogoUrl} alt={appName || 'Logo'} className="h-12 w-12 object-contain" />
                            ) : (
                                <AppLogoIcon className="h-8 w-8 fill-current" />
                            )}
                        </Link>
                    </div>

                    <div className="flex flex-1 items-center justify-center">
                        <div className="w-full max-w-md">
                            <div className="flex flex-col items-center gap-6 text-center">
                                {/* Icon */}
                                <div className="bg-primary/10 flex h-20 w-20 items-center justify-center rounded-full">
                                    <Mail className="text-primary h-10 w-10" />
                                </div>

                                {/* Header */}
                                <div className="space-y-2">
                                    <h1 className="text-2xl font-bold">Account Activation Required</h1>
                                    <p className="text-muted-foreground text-sm">We have sent an activation email to:</p>
                                    <p className="text-primary font-medium">{email}</p>
                                </div>

                                {/* Instructions */}
                                <div className="bg-muted/50 w-full rounded-lg p-4">
                                    <p className="text-muted-foreground text-sm">
                                        Please check your email inbox and click the activation link to activate your account. Don&apos;t forget to
                                        check your spam folder if you can&apos;t find the email.
                                    </p>
                                </div>

                                {/* Resend button */}
                                <form onSubmit={handleResend} className="w-full">
                                    <Button
                                        type="submit"
                                        variant="outline"
                                        className="w-full border-none bg-gradient-to-r from-[#7a5c1e] via-[#c9a84c] to-[#7a5c1e] text-black shadow-[0_0_15px_rgba(201,168,76,0.3)] hover:from-[#8a6c2e] hover:via-[#d9b85c] hover:to-[#8a6c2e]"
                                        disabled={processing || countdown > 0}
                                    >
                                        {processing ? <LoaderCircle className="mr-2 h-4 w-4 animate-spin" /> : <RefreshCw className="mr-2 h-4 w-4" />}
                                        {countdown > 0 ? `Resend Email (${countdown}s)` : 'Resend Email'}
                                    </Button>
                                </form>

                                {/* Back to login link */}
                                <Link href="/login" className="text-muted-foreground hover:text-foreground text-sm transition-colors">
                                    Back to Login
                                </Link>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Background - conditionally last for right layout */}
                {!backgroundSettings.onLeft && <BackgroundComponent loginBackgroundUrl={loginBackgroundUrl} />}
            </div>
        </>
    );
}
