import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { ArrowRight, Briefcase, Shield, Sparkles, UserRound } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import type { FormEventHandler } from 'react';
import InputError from '@/components/input-error';
import PasswordInput from '@/components/password-input';
import TextLink from '@/components/text-link';
import AppLogoIcon from '@/components/app-logo-icon';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinner';
import { home } from '@/routes';
import { store } from '@/routes/login';
import { request } from '@/routes/password';
import { useI18n } from '@/hooks/use-i18n';
import { cn } from '@/lib/utils';

type LoginPersona = 'employee' | 'client';

type Props = {
    status?: string;
    canResetPassword: boolean;
};

type LoginFormData = {
    email: string;
    password: string;
    remember: boolean;
    login_persona: LoginPersona;
};

export default function Login({ status, canResetPassword }: Props) {
    const { t, locale } = useI18n();
    const { name } = usePage<{ name: string }>().props;
    const [persona, setPersona] = useState<LoginPersona>('employee');

    const { data, setData, post, processing, errors, reset } = useForm<LoginFormData>({
        email: '',
        password: '',
        remember: false,
        login_persona: 'employee',
    });

    useEffect(() => {
        setData('login_persona', persona);
    }, [persona, setData]);

    const submit: FormEventHandler<HTMLFormElement> = (e) => {
        e.preventDefault();
        post(store.url(), {
            preserveScroll: true,
            onSuccess: () => {
                reset('password');
            },
        });
    };

    const badgeDate = useMemo(
        () =>
            new Intl.DateTimeFormat(
                locale === 'ro' ? 'ro-RO' : locale === 'bg' ? 'bg-BG' : 'en-GB',
                {
                month: 'long',
                year: 'numeric',
            }).format(new Date()),
        [locale],
    );

    const year = new Date().getFullYear();

    return (
        <div className="relative flex min-h-dvh flex-col bg-background text-foreground">
            <Head title={t('auth.login.meta.head_title')} />

            <div className="grid flex-1 lg:grid-cols-2">
                {/* Marketing column */}
                <div className="relative hidden min-h-dvh overflow-hidden border-border bg-card px-10 py-14 text-card-foreground lg:flex lg:flex-col lg:border-r">
                    <div
                        aria-hidden
                        className="pointer-events-none absolute -right-20 top-20 h-72 w-72 rounded-full bg-primary/15 blur-3xl"
                    />
                    <div
                        aria-hidden
                        className="pointer-events-none absolute bottom-16 left-8 h-56 w-56 rounded-full bg-primary/10 blur-3xl"
                    />

                    <div className="relative z-10 flex min-h-0 flex-1 flex-col">
                        <Link
                            href={home()}
                            className="inline-flex shrink-0 items-center gap-3 text-lg font-semibold tracking-tight"
                        >
                            <span className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary text-primary-foreground shadow-sm">
                                <AppLogoIcon className="size-6 text-primary-foreground" />
                            </span>
                            <span className="flex flex-col leading-tight">
                                <div className="flex items-center">
                                    <span>elevio</span>
                                    <span className="text-primary font-semibold ml-1 text-lg">
                                        one
                                    </span>
                                </div>
                                <span className="text-xs font-normal text-muted-foreground">{t('auth.login.brand.tagline')}</span>
                            </span>
                        </Link>

                        <div className="flex min-h-0 flex-1 flex-col justify-center py-10">
                            <div className="max-w-md space-y-6">
                                <span className="inline-flex items-center gap-1.5 rounded-full border border-border bg-background/80 px-3 py-1 text-xs font-medium text-muted-foreground backdrop-blur">
                                    <Sparkles className="h-3.5 w-3.5 text-primary" />
                                    {t('auth.login.hero.badge', { date: badgeDate })}
                                </span>
                                <h2 className="text-balance text-3xl font-semibold tracking-tight md:text-4xl">
                                    <span className="text-foreground">{t('auth.login.hero.title_lead')}</span>{' '}
                                    <span className="text-primary">{t('auth.login.hero.title_accent')}</span>
                                </h2>
                                <p className="text-pretty text-sm leading-relaxed text-muted-foreground md:text-base">
                                    {t('auth.login.hero.description')}
                                </p>
                            </div>

                            <div className="relative z-10 mt-12 grid max-w-lg grid-cols-3 gap-3">
                                {[
                                    { value: t('auth.login.stats.users_value'), label: t('auth.login.stats.users_label') },
                                    { value: t('auth.login.stats.uptime_value'), label: t('auth.login.stats.uptime_label') },
                                    { value: t('auth.login.stats.security_value'), label: t('auth.login.stats.security_label') },
                                ].map((stat) => (
                                    <div
                                        key={stat.label}
                                        className="rounded-xl border border-border bg-background/60 px-3 py-4 text-center backdrop-blur-sm"
                                    >
                                        <p className="text-lg font-semibold tabular-nums text-foreground">{stat.value}</p>
                                        <p className="mt-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
                                            {stat.label}
                                        </p>
                                    </div>
                                ))}
                            </div>
                        </div>

                        <p className="relative z-10 shrink-0 pt-6 text-left text-[11px] leading-relaxed text-muted-foreground">
                            <span className="inline-flex max-w-lg items-start gap-1.5">
                                <Shield className="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" aria-hidden />
                                <span>{t('auth.login.footer.security_note')}</span>
                            </span>
                        </p>
                    </div>
                </div>

                {/* Form column */}
                <div className="relative flex flex-col justify-center px-6 py-12 sm:px-10 lg:px-12">
                    <div
                        aria-hidden
                        className="pointer-events-none absolute inset-x-0 top-0 h-64 bg-[radial-gradient(ellipse_70%_60%_at_50%_-10%,hsl(var(--primary)/0.12),transparent)] lg:hidden"
                    />

                    <div className="relative z-10 mx-auto w-full max-w-lg space-y-8">
                        <div className="flex items-center justify-between gap-4 lg:hidden">
                            <Link href={home()} className="inline-flex items-center gap-2 font-semibold">
                                <span className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary text-primary-foreground">
                                    <AppLogoIcon className="size-5 text-primary-foreground" />
                                </span>
                                <span>{name}</span>
                            </Link>
                        </div>

                        <div className="rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-surface)] sm:p-8">
                            {status ? (
                                <div className="mb-6 rounded-lg border border-success/30 bg-success-soft px-4 py-3 text-center text-sm font-medium text-success-soft-foreground">
                                    {status}
                                </div>
                            ) : null}
                            <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                                {t('auth.login.persona.heading')}
                            </p>
                            <div className="mt-3 grid grid-cols-2 gap-2 rounded-xl bg-muted/80 p-1">
                                <button
                                    type="button"
                                    onClick={() => setPersona('employee')}
                                    className={cn(
                                        'flex items-center justify-center gap-2 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors',
                                        persona === 'employee'
                                            ? 'bg-primary text-primary-foreground shadow-sm'
                                            : 'text-muted-foreground hover:text-foreground',
                                    )}
                                >
                                    <Briefcase className="h-4 w-4 shrink-0" />
                                    {t('auth.login.persona.employee')}
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setPersona('client')}
                                    className={cn(
                                        'flex items-center justify-center gap-2 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors',
                                        persona === 'client'
                                            ? 'bg-primary text-primary-foreground shadow-sm'
                                            : 'text-muted-foreground hover:text-foreground',
                                    )}
                                >
                                    <UserRound className="h-4 w-4 shrink-0" />
                                    {t('auth.login.persona.client')}
                                </button>
                            </div>

                            <p className="mt-4 text-sm text-muted-foreground">
                                {persona === 'employee'
                                    ? t('auth.login.persona.context_employee')
                                    : t('auth.login.persona.context_client')}
                            </p>

                            <form onSubmit={submit} className="mt-8 flex flex-col gap-6">
                                <div className="grid gap-5">
                            <div className="grid gap-2">
                                        <Label htmlFor="email">{t('auth.login.form.email_label')}</Label>
                                <Input
                                    id="email"
                                    type="email"
                                    name="email"
                                    required
                                    autoFocus
                                    tabIndex={1}
                                    autoComplete="email"
                                            placeholder={t('auth.login.form.email_placeholder')}
                                            value={data.email}
                                            onChange={(e) => setData('email', e.target.value)}
                                />
                                <InputError message={errors.email} />
                            </div>

                            <div className="grid gap-2">
                                        <div className="flex items-center gap-2">
                                            <Label htmlFor="password">{t('auth.login.form.password_label')}</Label>
                                            {canResetPassword ? (
                                        <TextLink
                                            href={request()}
                                                    className="ml-auto text-xs font-medium"
                                            tabIndex={5}
                                        >
                                                    {t('auth.login.form.forgot_password')}
                                        </TextLink>
                                            ) : null}
                                </div>
                                <PasswordInput
                                    id="password"
                                    name="password"
                                    required
                                    tabIndex={2}
                                    autoComplete="current-password"
                                            placeholder={t('auth.login.form.password_placeholder')}
                                            showPasswordAriaLabel={t('auth.login.form.password_show')}
                                            hidePasswordAriaLabel={t('auth.login.form.password_hide')}
                                            value={data.password}
                                            onChange={(e) => setData('password', e.target.value)}
                                />
                                <InputError message={errors.password} />
                            </div>

                                    <div className="flex items-center gap-3">
                                <Checkbox
                                    id="remember"
                                    name="remember"
                                    tabIndex={3}
                                            checked={data.remember}
                                            onCheckedChange={(v) => setData('remember', v === true)}
                                />
                                        <Label htmlFor="remember" className="text-sm font-normal leading-snug">
                                            {t('auth.login.form.remember')}
                                        </Label>
                            </div>

                            <Button
                                type="submit"
                                        className="h-11 w-full gap-2 text-base font-semibold shadow-sm"
                                tabIndex={4}
                                disabled={processing}
                                data-test="login-button"
                            >
                                        {processing ? (
                                            <>
                                                <Spinner />
                                                {t('auth.login.form.submit_loading')}
                                            </>
                                        ) : (
                                            <>
                                                {t('auth.login.form.submit')}
                                                <ArrowRight className="h-4 w-4" />
                                            </>
                                        )}
                            </Button>
                                </div>
                            </form>
                        </div>

                        <p className="text-center text-[11px] text-muted-foreground tabular-nums">
                            {t('auth.login.footer.copyright', { year, app: name })}
                            {' · '}
                            <a href="#" className="hover:text-foreground">
                                {t('auth.login.footer.terms')}
                            </a>
                            {' · '}
                            <a href="#" className="hover:text-foreground">
                                {t('auth.login.footer.privacy')}
                            </a>
                        </p>
                            </div>
                </div>
            </div>
        </div>
    );
}
