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

type SetPasswordForm = {
    token: string;
    name: string;
    password: string;
    password_confirmation: string;
};

interface SetPasswordProps {
    token: string;
    valid: boolean;
    email?: string;
    name?: string;
    message?: string;
}

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

    // Memoize background URL to prevent re-renders
    const bgUrl = useMemo(() => loginBackgroundUrl, [loginBackgroundUrl]);

    // 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.setup.store'), {
            onSuccess: () => {
                toast.success('Password has been set successfully!');
            },
            onFinish: () => reset('password', 'password_confirmation'),
        });
    };

    // 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 = bgUrl?.toLowerCase().endsWith('.mp4');

    // Invalid token view
    if (!valid) {
        // Full width layout
        if (isFullWidth) {
            return (
                <>
                    <Head title="Link Expired" />
                    <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">
                            {bgUrl ? (
                                isVideo ? (
                                    <video autoPlay loop muted playsInline className="h-full w-full object-cover">
                                        <source src={bgUrl} type="video/mp4" />
                                    </video>
                                ) : (
                                    <img src={bgUrl} alt="" className="h-full w-full object-cover" />
                                )
                            ) : (
                                <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">
                                <div className="flex flex-col gap-6">
                                    <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">Link Expired or Invalid</p>
                                        </div>

                                        {/* Error Message */}
                                        <div className="rounded-md border border-red-200 bg-red-50 p-4 text-sm text-red-800 dark:border-red-800 dark:bg-red-950/30 dark:text-red-200">
                                            <p className="font-medium">Invalid Link</p>
                                            <p className="mt-1">
                                                {message || 'This password setup link has expired or is invalid. Please request a new one.'}
                                            </p>
                                        </div>

                                        {/* Register Again Button */}
                                        <Field>
                                            <Button asChild className="w-full">
                                                <Link href={route('register')}>Register Again</Link>
                                            </Button>
                                        </Field>

                                        {/* Go to Login Button */}
                                        <Field>
                                            <Button variant="outline" asChild className="w-full">
                                                <Link href={route('login')}>Go to Login</Link>
                                            </Button>
                                        </Field>
                                    </FieldGroup>
                                </div>
                            </div>
                        </div>
                    </div>
                </>
            );
        }

        // Side layout (default)
        return (
            <>
                <Head title="Link Expired" />
                <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={bgUrl} />}

                    {/* Error Content */}
                    <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">
                                <div className="flex flex-col gap-6">
                                    <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">Link Expired or Invalid</p>
                                        </div>

                                        {/* Error Message */}
                                        <div className="rounded-md border border-red-200 bg-red-50 p-4 text-sm text-red-800 dark:border-red-800 dark:bg-red-950/30 dark:text-red-200">
                                            <p className="font-medium">Invalid Link</p>
                                            <p className="mt-1">
                                                {message || 'This password setup link has expired or is invalid. Please request a new one.'}
                                            </p>
                                        </div>

                                        {/* Register Again Button */}
                                        <Field>
                                            <Button asChild className="w-full">
                                                <Link href={route('register')}>Register Again</Link>
                                            </Button>
                                        </Field>

                                        {/* Go to Login Button */}
                                        <Field>
                                            <Button variant="outline" asChild className="w-full">
                                                <Link href={route('login')}>Go to Login</Link>
                                            </Button>
                                        </Field>
                                    </FieldGroup>
                                </div>
                            </div>
                        </div>
                    </div>

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

    // Valid token - show password form
    const content = (
        <>
            <Head title={`Set Password - ${appName}`} />
            <Toaster position="top-right" richColors closeButton duration={4000} />

            <div className="flex flex-col gap-4 p-6 md:p-10">
                <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">Set Your Password</p>
                                </div>

                                {/* Email Field (read-only display) */}
                                {email && (
                                    <Field>
                                        <FieldLabel htmlFor="email">Email</FieldLabel>
                                        <Input id="email" type="email" value={email} readOnly className="bg-muted" tabIndex={-1} />
                                    </Field>
                                )}

                                {/* Username Field */}
                                <Field>
                                    <FieldLabel htmlFor="name">Username</FieldLabel>
                                    <Input
                                        id="name"
                                        type="text"
                                        required
                                        autoFocus
                                        tabIndex={1}
                                        autoComplete="username"
                                        value={data.name}
                                        onChange={(e) => {
                                            // Only allow alphanumeric, no spaces or symbols
                                            const value = e.target.value.replace(/[^a-zA-Z0-9]/g, '');
                                            setData('name', value);
                                        }}
                                        placeholder="Choose a username"
                                        pattern="[a-zA-Z0-9]+"
                                        title="Username can only contain letters and numbers, no spaces or symbols"
                                    />
                                    <InputError message={errors.name} />
                                </Field>

                                {/* Password Field */}
                                <Field>
                                    <FieldLabel htmlFor="password">Password</FieldLabel>
                                    <Input
                                        id="password"
                                        type="password"
                                        required
                                        tabIndex={2}
                                        autoComplete="new-password"
                                        value={data.password}
                                        onChange={(e) => setData('password', e.target.value)}
                                        placeholder="Create a strong 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 your 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" />}
                                        Create Account
                                    </Button>
                                </Field>

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

    // Full width layout
    if (isFullWidth) {
        return (
            <div className="relative flex h-svh items-center justify-center">
                {/* Full width background */}
                <div className="absolute inset-0 z-0">
                    {bgUrl ? (
                        isVideo ? (
                            <video autoPlay loop muted playsInline className="h-full w-full object-cover">
                                <source src={bgUrl} type="video/mp4" />
                            </video>
                        ) : (
                            <img src={bgUrl} alt="" className="h-full w-full object-cover" />
                        )
                    ) : (
                        <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 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">
                        {content}
                    </div>
                </div>
            </div>
        );
    }

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

            {/* Set 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">{content}</div>
                </div>
            </div>

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