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

import AppLogoIcon from '@/components/layout/app-logo-icon';
import InputError from '@/components/shared/input-error';
import TextLink from '@/components/shared/text-link';
import { Button } from '@/components/ui/button';
import { Field, FieldDescription, FieldGroup, FieldLabel } from '@/components/ui/field-1';
import { GradientMesh } from '@/components/ui/gradient-mesh';
import { Input } from '@/components/ui/input';
import { getFontClass } from '@/lib/fonts';

// CSRF token is handled automatically in app.tsx

const COUNTDOWN_DURATION = 5 * 60; // 5 minutes in seconds
const STORAGE_KEY = 'password-reset-countdown';

// 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 ForgotPassword({ status }: { status?: string }) {
    const { appName, appLogoUrl, loginBackgroundUrl, loginBackgroundPosition, appFont, appNameColor, heroUseLogo } = usePage().props as any;
    const { data, setData, post, processing, errors } = useForm<Required<{ email: string }>>({
        email: '',
    });

    const [countdown, setCountdown] = useState<number>(0);
    const [isCountdownActive, setIsCountdownActive] = useState<boolean>(false);

    // Show toast when status message is present
    useEffect(() => {
        if (status) {
            toast.success(status);
        }
    }, [status]);

    // Clear countdown if user already changed password
    useEffect(() => {
        if (errors.email?.toLowerCase().includes('already changed')) {
            localStorage.removeItem(STORAGE_KEY);
            setCountdown(0);
            setIsCountdownActive(false);
            toast.info('You have already reset your password. Please log in or request a new reset link.');
        }
    }, [errors.email]);

    // Initialize countdown from localStorage on mount
    useEffect(() => {
        const savedTimestamp = localStorage.getItem(STORAGE_KEY);
        if (savedTimestamp) {
            const elapsed = Math.floor((Date.now() - parseInt(savedTimestamp)) / 1000);
            const remaining = COUNTDOWN_DURATION - elapsed;

            if (remaining > 0) {
                setCountdown(remaining);
                setIsCountdownActive(true);
            } else {
                localStorage.removeItem(STORAGE_KEY);
            }
        }
    }, []);

    // Force dark theme on these pages
    useEffect(() => {
        document.documentElement.classList.add('dark');
        document.documentElement.setAttribute('data-force-dark', 'true');

        // Override any theme changes
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                    const html = document.documentElement;
                    if (!html.classList.contains('dark')) {
                        html.classList.add('dark');
                    }
                }
            });
        });

        observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });

        return () => {
            observer.disconnect();
            document.documentElement.classList.remove('dark');
            document.documentElement.removeAttribute('data-force-dark');
        };
    }, []);

    // Countdown timer effect
    useEffect(() => {
        if (!isCountdownActive || countdown <= 0) {
            if (countdown <= 0 && isCountdownActive) {
                setIsCountdownActive(false);
                localStorage.removeItem(STORAGE_KEY);
            }
            return;
        }

        const timer = setInterval(() => {
            setCountdown((prev) => {
                if (prev <= 1) {
                    setIsCountdownActive(false);
                    localStorage.removeItem(STORAGE_KEY);
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);

        return () => clearInterval(timer);
    }, [isCountdownActive, countdown]);

    const submit: FormEventHandler = (e) => {
        e.preventDefault();

        // Start countdown
        localStorage.setItem(STORAGE_KEY, Date.now().toString());
        setCountdown(COUNTDOWN_DURATION);
        setIsCountdownActive(true);

        post(route('password.email'));
    };

    // Format countdown to MM:SS
    const formatCountdown = (seconds: number): string => {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins}:${secs.toString().padStart(2, '0')}`;
    };

    // Check if the error is a rate limit error
    const isRateLimitError = errors.email?.includes('Too many') || errors.email?.includes('Please wait');

    // Determine if background should be on left or full width
    const backgroundOnLeft = loginBackgroundPosition === 'left';
    const isFullWidth = loginBackgroundPosition === 'full';

    // Check if background is video (only for full-width layout)
    const isVideo = loginBackgroundUrl?.toLowerCase().endsWith('.mp4');

    // Full width layout
    if (isFullWidth) {
        return (
            <>
                <Head title="Forgot password" />
                <Toaster position="top-right" richColors closeButton duration={4000} />

                <div className="relative flex h-svh items-center justify-center">
                    {/* Full width background */}
                    <div className="absolute inset-0 z-0">
                        {loginBackgroundUrl ? (
                            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 form 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">
                            <form className="flex flex-col gap-6" onSubmit={submit}>
                                <FieldGroup>
                                    {/* Logo */}
                                    <div className="flex justify-center">
                                        <Link href={route('home')} className="flex items-center gap-2">
                                            {appLogoUrl ? (
                                                <img
                                                    src={appLogoUrl}
                                                    alt={appName || 'Logo'}
                                                    className="h-32 w-32 object-contain"
                                                    width="128"
                                                    height="128"
                                                    loading="eager"
                                                    fetchPriority="high"
                                                    decoding="sync"
                                                />
                                            ) : (
                                                <AppLogoIcon className="h-32 w-32 fill-current text-[var(--foreground)] dark:text-white" />
                                            )}
                                        </Link>
                                    </div>

                                    {/* Header */}
                                    <div className="flex flex-col items-center gap-1 text-center">
                                        {!heroUseLogo && (
                                            <h1
                                                className={`bg-clip-text pb-1 text-center text-3xl leading-normal font-bold text-transparent drop-shadow-lg ${getFontClass(appFont)}`}
                                                style={{
                                                    backgroundImage: appNameColor
                                                        ? `linear-gradient(to bottom, white, ${appNameColor}, ${appNameColor}dd)`
                                                        : 'linear-gradient(to bottom, white, #fcd34d, #d97706)',
                                                }}
                                            >
                                                {appName}
                                            </h1>
                                        )}
                                        <p className="text-muted-foreground text-sm text-balance">Forgot Password</p>
                                    </div>

                                    {/* Countdown timer display */}
                                    {isCountdownActive && (
                                        <div className="rounded-md border border-blue-200 bg-blue-50 p-4 text-sm text-blue-800 dark:border-blue-800 dark:bg-blue-950/30 dark:text-blue-200">
                                            <div className="flex items-center justify-center gap-2">
                                                <Clock className="h-5 w-5 animate-pulse" />
                                                <div>
                                                    <p className="font-medium">Please wait before requesting another reset link</p>
                                                    <p className="mt-1 font-mono text-lg font-bold">{formatCountdown(countdown)}</p>
                                                </div>
                                            </div>
                                        </div>
                                    )}

                                    {/* Rate limit warning */}
                                    {isRateLimitError && (
                                        <div className="rounded-md border border-yellow-200 bg-yellow-50 p-4 text-sm text-yellow-800 dark:border-yellow-800 dark:bg-yellow-950/30 dark:text-yellow-200">
                                            <p className="font-medium">Rate Limit Exceeded</p>
                                            <p className="mt-1">You can only request 5 password reset links within a 5-minute period.</p>
                                        </div>
                                    )}

                                    {/* Email Field */}
                                    <Field>
                                        <FieldLabel htmlFor="email">Email address</FieldLabel>
                                        <Input
                                            id="email"
                                            type="email"
                                            name="email"
                                            autoComplete="off"
                                            value={data.email}
                                            autoFocus
                                            onChange={(e) => setData('email', e.target.value)}
                                            placeholder="email@example.com"
                                        />
                                        <InputError message={errors.email} />
                                    </Field>

                                    {/* Submit Button */}
                                    <Field>
                                        <Button
                                            type="submit"
                                            className="w-full 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 || isRateLimitError || isCountdownActive}
                                        >
                                            {processing && <LoaderCircle className="h-4 w-4 animate-spin" />}
                                            {isCountdownActive && <Clock className="mr-2 h-4 w-4" />}
                                            {isCountdownActive ? `Wait ${formatCountdown(countdown)}` : 'Email password reset link'}
                                        </Button>
                                    </Field>

                                    {(isRateLimitError || isCountdownActive) && (
                                        <p className="text-muted-foreground text-center text-xs">
                                            {isRateLimitError
                                                ? 'The button will be disabled until the rate limit expires.'
                                                : 'You can request a new link after the countdown ends.'}
                                        </p>
                                    )}

                                    {/* Login Link */}
                                    <FieldDescription className="text-center">
                                        Or, return to <TextLink href={route('login')}>log in</TextLink>
                                    </FieldDescription>
                                </FieldGroup>
                            </form>
                        </div>
                    </div>
                </div>
            </>
        );
    }

    return (
        <>
            <Head title="Forgot password" />
            <Toaster position="top-right" richColors closeButton duration={4000} />

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

                {/* Forgot Password Form */}
                <div className="flex flex-col gap-4 p-6 md:p-10">
                    {/* Form Container */}
                    <div className="scrollbar-hide flex w-full flex-1 items-center justify-center overflow-y-auto">
                        <div className="w-full max-w-sm">
                            <form className="flex flex-col gap-6" onSubmit={submit}>
                                <FieldGroup>
                                    {/* Logo */}
                                    <div className="flex justify-center">
                                        <Link href={route('home')} className="flex items-center gap-2">
                                            {appLogoUrl ? (
                                                <img
                                                    src={appLogoUrl}
                                                    alt={appName || 'Logo'}
                                                    className="h-32 w-32 object-contain"
                                                    width="128"
                                                    height="128"
                                                    loading="eager"
                                                    fetchPriority="high"
                                                    decoding="sync"
                                                />
                                            ) : (
                                                <AppLogoIcon className="h-32 w-32 fill-current text-[var(--foreground)] dark:text-white" />
                                            )}
                                        </Link>
                                    </div>

                                    {/* Header */}
                                    <div className="flex flex-col items-center gap-1 text-center">
                                        {!heroUseLogo && (
                                            <h1
                                                className={`bg-clip-text pb-1 text-center text-3xl leading-normal font-bold text-transparent drop-shadow-lg ${getFontClass(appFont)}`}
                                                style={{
                                                    backgroundImage: appNameColor
                                                        ? `linear-gradient(to bottom, white, ${appNameColor}, ${appNameColor}dd)`
                                                        : 'linear-gradient(to bottom, white, #fcd34d, #d97706)',
                                                }}
                                            >
                                                {appName}
                                            </h1>
                                        )}
                                        <p className="text-muted-foreground text-sm text-balance">Forgot Password</p>
                                    </div>

                                    {/* Countdown timer display */}
                                    {isCountdownActive && (
                                        <div className="rounded-md border border-blue-200 bg-blue-50 p-4 text-sm text-blue-800 dark:border-blue-800 dark:bg-blue-950/30 dark:text-blue-200">
                                            <div className="flex items-center justify-center gap-2">
                                                <Clock className="h-5 w-5 animate-pulse" />
                                                <div>
                                                    <p className="font-medium">Please wait before requesting another reset link</p>
                                                    <p className="mt-1 font-mono text-lg font-bold">{formatCountdown(countdown)}</p>
                                                </div>
                                            </div>
                                        </div>
                                    )}

                                    {/* Rate limit warning */}
                                    {isRateLimitError && (
                                        <div className="rounded-md border border-yellow-200 bg-yellow-50 p-4 text-sm text-yellow-800 dark:border-yellow-800 dark:bg-yellow-950/30 dark:text-yellow-200">
                                            <p className="font-medium">Rate Limit Exceeded</p>
                                            <p className="mt-1">You can only request 5 password reset links within a 5-minute period.</p>
                                        </div>
                                    )}

                                    {/* Email Field */}
                                    <Field>
                                        <FieldLabel htmlFor="email">Email address</FieldLabel>
                                        <Input
                                            id="email"
                                            type="email"
                                            name="email"
                                            autoComplete="off"
                                            value={data.email}
                                            autoFocus
                                            onChange={(e) => setData('email', e.target.value)}
                                            placeholder="email@example.com"
                                        />
                                        <InputError message={errors.email} />
                                    </Field>

                                    {/* Submit Button */}
                                    <Field>
                                        <Button
                                            type="submit"
                                            className="w-full 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 || isRateLimitError || isCountdownActive}
                                        >
                                            {processing && <LoaderCircle className="h-4 w-4 animate-spin" />}
                                            {isCountdownActive && <Clock className="mr-2 h-4 w-4" />}
                                            {isCountdownActive ? `Wait ${formatCountdown(countdown)}` : 'Email password reset link'}
                                        </Button>
                                    </Field>

                                    {(isRateLimitError || isCountdownActive) && (
                                        <p className="text-muted-foreground text-center text-xs">
                                            {isRateLimitError
                                                ? 'The button will be disabled until the rate limit expires.'
                                                : 'You can request a new link after the countdown ends.'}
                                        </p>
                                    )}

                                    {/* Login Link */}
                                    <FieldDescription className="text-center">
                                        Or, return to <TextLink href={route('login')}>log in</TextLink>
                                    </FieldDescription>
                                </FieldGroup>
                            </form>
                        </div>
                    </div>
                </div>

                {/* Background - conditionally last */}
                {!backgroundOnLeft && <BackgroundComponent loginBackgroundUrl={loginBackgroundUrl} />}
            </div>
        </>
    );
}
