// @ts-ignore - Inertia types are available at runtime
import { GoogleIcon } from '@/components/icons/google-icon';
import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { LoaderCircle } from 'lucide-react';
import { FormEventHandler, memo, useEffect } 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 { Checkbox } from '@/components/ui/checkbox';
import { Field, FieldDescription, FieldGroup, FieldLabel, FieldSeparator } from '@/components/ui/field-1';
import { Input } from '@/components/ui/input';
import { ProtojahBg, ProtojahFormBg } from '@/components/ui/protojah-bg';
import { getFontClass } from '@/lib/fonts';
// CSRF token is handled automatically in app.tsx

// 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="relative hidden h-full 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"
                    />
                )
            ) : (
                <ProtojahBg />
            )}
        </div>
    );
});

type LoginForm = {
    username: string;
    password: string;
    remember: boolean;
};

interface LoginProps {
    status?: string;
    canResetPassword: boolean;
    googleLoginEnabled: boolean;
}

export default function Login({ status, canResetPassword, googleLoginEnabled }: LoginProps) {
    const { appName, appLogoUrl, loginBackgroundUrl, loginBackgroundPosition, appFont, appNameColor, heroUseLogo, flash } = usePage().props as any;
    const { data, setData, post, processing, errors, reset } = useForm<Required<LoginForm>>({
        username: '',
        password: '',
        remember: false,
    });

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

            // Clear password reset countdown from localStorage if password was successfully reset
            if (status.toLowerCase().includes('password') && status.toLowerCase().includes('reset')) {
                localStorage.removeItem('password-reset-countdown');
            }
        }
    }, [status]);

    // 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('login'), {
            onFinish: () => reset('password'),
        });
    };

    // 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="Log in" />
                <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"
                                />
                            )
                        ) : (
                            <ProtojahBg />
                        )}
                        {/* 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="scrollbar-hide max-h-[90svh] overflow-y-auto rounded-xl p-8 shadow-2xl backdrop-blur-sm"
                            style={{
                                background: 'rgba(8, 8, 8, 0.85)',
                                border: '1px solid rgba(201, 168, 76, 0.15)',
                                boxShadow: '0 0 40px rgba(201, 168, 76, 0.1)',
                            }}
                        >
                            <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">Login Account</p>
                                    </div>

                                    {/* Username Field */}
                                    <Field>
                                        <FieldLabel htmlFor="username">Username</FieldLabel>
                                        <Input
                                            id="username"
                                            type="text"
                                            required
                                            autoFocus
                                            tabIndex={1}
                                            autoComplete="username"
                                            value={data.username}
                                            onChange={(e) => setData('username', e.target.value)}
                                            placeholder="Your username"
                                        />
                                        <InputError message={errors.username} />
                                    </Field>

                                    {/* Password Field */}
                                    <Field>
                                        <div className="flex items-center">
                                            <FieldLabel htmlFor="password">Password</FieldLabel>
                                            {canResetPassword && (
                                                <TextLink href={route('password.request')} className="ml-auto text-sm" tabIndex={5}>
                                                    Forgot your password?
                                                </TextLink>
                                            )}
                                        </div>
                                        <Input
                                            id="password"
                                            type="password"
                                            required
                                            tabIndex={2}
                                            autoComplete="current-password"
                                            value={data.password}
                                            onChange={(e) => setData('password', e.target.value)}
                                            placeholder="Password"
                                        />
                                        <InputError message={errors.password} />
                                    </Field>

                                    {/* Remember Me */}
                                    <div className="flex items-center space-x-3">
                                        <Checkbox
                                            id="remember"
                                            name="remember"
                                            checked={data.remember}
                                            onClick={() => setData('remember', !data.remember)}
                                            tabIndex={3}
                                        />
                                        <FieldLabel htmlFor="remember">Remember me</FieldLabel>
                                    </div>

                                    {/* Submit Button */}
                                    <Field>
                                        <Button type="submit" className="w-full" tabIndex={4} disabled={processing}>
                                            {processing && <LoaderCircle className="h-4 w-4 animate-spin" />}
                                            Login
                                        </Button>
                                    </Field>

                                    {/* Google Auth Button */}
                                    {googleLoginEnabled && (
                                        <>
                                            <FieldSeparator>Or continue with</FieldSeparator>
                                            <Field>
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    className="w-full"
                                                    tabIndex={5}
                                                    onClick={() => (window.location.href = route('auth.google'))}
                                                >
                                                    <GoogleIcon className="mr-2 h-4 w-4" />
                                                    Login with Google
                                                </Button>
                                            </Field>
                                        </>
                                    )}

                                    {/* Sign Up Link */}
                                    <FieldDescription className="text-center">
                                        Don&apos;t have an account?{' '}
                                        <TextLink href={route('register')} tabIndex={6}>
                                            Sign up
                                        </TextLink>
                                    </FieldDescription>
                                </FieldGroup>
                            </form>
                        </div>
                    </div>
                </div>
            </>
        );
    }

    return (
        <>
            <Head title="Log in" />
            <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} />}

                {/* Login Form */}
                <div className="relative flex flex-col gap-4 p-6 md:p-10">
                    <ProtojahFormBg className="absolute inset-0" />
                    {/* 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">Login Account</p>
                                    </div>

                                    {/* Username Field */}
                                    <Field>
                                        <FieldLabel htmlFor="username">Username</FieldLabel>
                                        <Input
                                            id="username"
                                            type="text"
                                            required
                                            autoFocus
                                            tabIndex={1}
                                            autoComplete="username"
                                            value={data.username}
                                            onChange={(e) => setData('username', e.target.value)}
                                            placeholder="Your username"
                                        />
                                        <InputError message={errors.username} />
                                    </Field>

                                    {/* Password Field */}
                                    <Field>
                                        <div className="flex items-center">
                                            <FieldLabel htmlFor="password">Password</FieldLabel>
                                            {canResetPassword && (
                                                <TextLink href={route('password.request')} className="ml-auto text-sm" tabIndex={5}>
                                                    Forgot your password?
                                                </TextLink>
                                            )}
                                        </div>
                                        <Input
                                            id="password"
                                            type="password"
                                            required
                                            tabIndex={2}
                                            autoComplete="current-password"
                                            value={data.password}
                                            onChange={(e) => setData('password', e.target.value)}
                                            placeholder="Password"
                                        />
                                        <InputError message={errors.password} />
                                    </Field>

                                    {/* Remember Me */}
                                    <div className="flex items-center space-x-3">
                                        <Checkbox
                                            id="remember"
                                            name="remember"
                                            checked={data.remember}
                                            onClick={() => setData('remember', !data.remember)}
                                            tabIndex={3}
                                        />
                                        <FieldLabel htmlFor="remember">Remember me</FieldLabel>
                                    </div>

                                    {/* Submit Button */}
                                    <Field>
                                        <Button type="submit" className="w-full" tabIndex={4} disabled={processing}>
                                            {processing && <LoaderCircle className="h-4 w-4 animate-spin" />}
                                            Login
                                        </Button>
                                    </Field>

                                    {/* Google Auth Button */}
                                    {googleLoginEnabled && (
                                        <>
                                            <FieldSeparator>Or continue with</FieldSeparator>
                                            <Field>
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    className="w-full"
                                                    tabIndex={5}
                                                    onClick={() => (window.location.href = route('auth.google'))}
                                                >
                                                    <GoogleIcon className="mr-2 h-4 w-4" />
                                                    Login with Google
                                                </Button>
                                            </Field>
                                        </>
                                    )}

                                    {/* Sign Up Link */}
                                    <FieldDescription className="text-center">
                                        Don&apos;t have an account?{' '}
                                        <TextLink href={route('register')} tabIndex={6}>
                                            Sign up
                                        </TextLink>
                                    </FieldDescription>
                                </FieldGroup>
                            </form>
                        </div>
                    </div>
                </div>

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