import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { LoaderCircle } from 'lucide-react';
import { FormEventHandler, memo, useEffect } from 'react';
import { Toaster, toast } 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

// Memoized background component for side layouts
const SideBackgroundComponent = memo(function SideBackgroundComponent({ 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>
    );
});

// Memoized full-width background component
const FullWidthBackgroundComponent = memo(function FullWidthBackgroundComponent({ loginBackgroundUrl }: { loginBackgroundUrl: string | null }) {
    const isVideo = loginBackgroundUrl?.toLowerCase().endsWith('.mp4');

    return (
        <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>
    );
});

type ResetPasswordForm = {
    token: string;
    email: string;
    password: string;
    password_confirmation: string;
};

interface ResetPasswordProps {
    token: string;
    email: string;
}

export default function ResetPassword({ token, email }: ResetPasswordProps) {
    const { appName, appLogoUrl, loginBackgroundUrl, loginBackgroundPosition, appFont, appNameColor, heroUseLogo, flash } = usePage().props as any;
    const { data, setData, post, processing, errors, reset } = useForm<Required<ResetPasswordForm>>({
        token: token,
        email: email,
        password: '',
        password_confirmation: '',
    });

    // Show toast for flash messages
    useEffect(() => {
        if (flash?.success) {
            toast.success(flash.success);
        }
        if (flash?.error) {
            toast.error(flash.error);
        }
        if (flash?.info) {
            toast.info(flash.info);
        }
        if (flash?.warning) {
            toast.warning(flash.warning);
        }
    }, [flash]);

    // 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');
        };
    }, []);

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        post(route('password.store'), {
            onSuccess: () => {
                toast.success('Password has been reset successfully!');
                // Clear password reset countdown from localStorage after successful reset
                localStorage.removeItem('password-reset-countdown');
            },
            onFinish: () => reset('password', 'password_confirmation'),
        });
    };

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

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

                <div className="relative flex h-svh items-center justify-center">
                    {/* Full width background - memoized */}
                    <FullWidthBackgroundComponent loginBackgroundUrl={loginBackgroundUrl} />

                    {/* 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">Reset Password</p>
                                    </div>

                                    {/* Email Field */}
                                    <Field>
                                        <FieldLabel htmlFor="email">Email</FieldLabel>
                                        <Input
                                            id="email"
                                            type="email"
                                            required
                                            autoFocus
                                            tabIndex={1}
                                            autoComplete="email"
                                            value={data.email}
                                            readOnly
                                            placeholder="Your email"
                                            className="bg-muted"
                                        />
                                        <InputError message={errors.email} />
                                    </Field>

                                    {/* Password Field */}
                                    <Field>
                                        <FieldLabel htmlFor="password">New Password</FieldLabel>
                                        <Input
                                            id="password"
                                            type="password"
                                            required
                                            tabIndex={2}
                                            autoComplete="new-password"
                                            value={data.password}
                                            onChange={(e) => setData('password', e.target.value)}
                                            placeholder="New password"
                                        />
                                        <InputError message={errors.password} />
                                    </Field>

                                    {/* Confirm Password Field */}
                                    <Field>
                                        <FieldLabel htmlFor="password_confirmation">Confirm Password</FieldLabel>
                                        <Input
                                            id="password_confirmation"
                                            type="password"
                                            required
                                            tabIndex={3}
                                            autoComplete="new-password"
                                            value={data.password_confirmation}
                                            onChange={(e) => setData('password_confirmation', e.target.value)}
                                            placeholder="Confirm new password"
                                        />
                                        <InputError message={errors.password_confirmation} />
                                    </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]"
                                            tabIndex={4}
                                            disabled={processing}
                                        >
                                            {processing && <LoaderCircle className="h-4 w-4 animate-spin" />}
                                            Reset Password
                                        </Button>
                                    </Field>

                                    {/* Back to Login Link */}
                                    <FieldDescription className="text-center">
                                        Remember your password?{' '}
                                        <TextLink href={route('login')} tabIndex={5}>
                                            Log in
                                        </TextLink>
                                    </FieldDescription>
                                </FieldGroup>
                            </form>
                        </div>
                    </div>
                </div>
            </>
        );
    }

    return (
        <>
            <Head title="Reset 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 && <SideBackgroundComponent loginBackgroundUrl={loginBackgroundUrl} />}

                {/* Reset 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">Reset Password</p>
                                    </div>

                                    {/* Email Field */}
                                    <Field>
                                        <FieldLabel htmlFor="email">Email</FieldLabel>
                                        <Input
                                            id="email"
                                            type="email"
                                            required
                                            autoFocus
                                            tabIndex={1}
                                            autoComplete="email"
                                            value={data.email}
                                            readOnly
                                            placeholder="Your email"
                                            className="bg-muted"
                                        />
                                        <InputError message={errors.email} />
                                    </Field>

                                    {/* Password Field */}
                                    <Field>
                                        <FieldLabel htmlFor="password">New Password</FieldLabel>
                                        <Input
                                            id="password"
                                            type="password"
                                            required
                                            tabIndex={2}
                                            autoComplete="new-password"
                                            value={data.password}
                                            onChange={(e) => setData('password', e.target.value)}
                                            placeholder="New password"
                                        />
                                        <InputError message={errors.password} />
                                    </Field>

                                    {/* Confirm Password Field */}
                                    <Field>
                                        <FieldLabel htmlFor="password_confirmation">Confirm Password</FieldLabel>
                                        <Input
                                            id="password_confirmation"
                                            type="password"
                                            required
                                            tabIndex={3}
                                            autoComplete="new-password"
                                            value={data.password_confirmation}
                                            onChange={(e) => setData('password_confirmation', e.target.value)}
                                            placeholder="Confirm new password"
                                        />
                                        <InputError message={errors.password_confirmation} />
                                    </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]"
                                            tabIndex={4}
                                            disabled={processing}
                                        >
                                            {processing && <LoaderCircle className="h-4 w-4 animate-spin" />}
                                            Reset Password
                                        </Button>
                                    </Field>

                                    {/* Back to Login Link */}
                                    <FieldDescription className="text-center">
                                        Remember your password?{' '}
                                        <TextLink href={route('login')} tabIndex={5}>
                                            Log in
                                        </TextLink>
                                    </FieldDescription>
                                </FieldGroup>
                            </form>
                        </div>
                    </div>
                </div>

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