import { Form, Head } from '@inertiajs/react';
import { UploadCloud } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import type { ChangeEvent, ReactNode } from 'react';
import { PageHeader } from '@/components/page-header';
import InputError from '@/components/input-error';
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 { dashboard } from '@/routes';
import { edit, update } from '@/routes/admin/settings';

type AppSettings = {
    name: string;
    password_expiry_days: number;
    max_failed_login_attempts: number;
    lockout_minutes: number;
    logo_url: string | null;
};

type Props = {
    settings: AppSettings;
    canUpdate: boolean;
};

const MAX_LOGO_BYTES = 2 * 1024 * 1024;

const card =
    'flex flex-col gap-4 rounded-2xl border border-primary/10 bg-card p-5';

function Section({
    title,
    description,
    children,
}: {
    title: string;
    description?: string;
    children: ReactNode;
}) {
    return (
        <section className={card}>
            <div className="space-y-1">
                <h2 className="text-base font-semibold">{title}</h2>
                {description && (
                    <p className="text-sm text-muted-foreground">
                        {description}
                    </p>
                )}
            </div>
            <div className="grid gap-4 sm:grid-cols-2">{children}</div>
        </section>
    );
}

function Field({
    id,
    label,
    error,
    hint,
    children,
    className,
}: {
    id: string;
    label: string;
    error?: string;
    hint?: string;
    children: ReactNode;
    className?: string;
}) {
    return (
        <div className={`grid gap-2 ${className ?? ''}`}>
            <Label htmlFor={id}>{label}</Label>
            {children}
            {hint && <p className="text-xs text-muted-foreground">{hint}</p>}
            <InputError message={error} />
        </div>
    );
}

export default function AppSettingsPage({ settings, canUpdate }: Props) {
    const [preview, setPreview] = useState<string | null>(null);
    const [removeLogo, setRemoveLogo] = useState(false);
    const logoInput = useRef<HTMLInputElement>(null);
    const [logoDragging, setLogoDragging] = useState(false);
    const [logoError, setLogoError] = useState<string | null>(null);

    useEffect(() => {
        return () => {
            if (preview) {
                URL.revokeObjectURL(preview);
            }
        };
    }, [preview]);

    const onLogoChange = (event: ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        setLogoError(null);

        if (!file) {
            setPreview(null);

            return;
        }

        if (file.size > MAX_LOGO_BYTES) {
            setLogoError('Le logo ne doit pas dépasser 2 Mo.');
            event.target.value = '';
            setPreview(null);

            return;
        }

        setRemoveLogo(false);
        setPreview(URL.createObjectURL(file));
    };

    const shownLogo = removeLogo ? null : (preview ?? settings.logo_url);
    const text = (name: keyof AppSettings) => ({
        id: name,
        name,
        defaultValue: (settings[name] as string | number | null) ?? '',
        disabled: !canUpdate,
    });

    return (
        <>
            <Head title="Paramètres" />

            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                <PageHeader
                    className="mb-0"
                    title="Paramètres de l'application"
                    description="Identité et politique de sécurité"
                />

                <Form
                    {...update.form()}
                    className="w-full max-w-3xl space-y-6"
                    options={{ preserveScroll: true }}
                >
                    {({ processing, errors }) => (
                        <>
                            <Section title="Identité de l'application">
                                <Field
                                    id="name"
                                    label="Nom de l'application"
                                    error={errors.name}
                                    className="sm:col-span-2"
                                >
                                    <Input {...text('name')} required />
                                </Field>

                                <div className="grid gap-2 sm:col-span-2">
                                    <Label htmlFor="logo">Logo</Label>
                                    <div className="flex items-center gap-4">
                                        <div className="flex size-20 shrink-0 items-center justify-center overflow-hidden rounded-xl border bg-muted/30">
                                            {shownLogo ? (
                                                <img
                                                    src={shownLogo}
                                                    alt="Logo de l'application"
                                                    className="size-full object-contain"
                                                />
                                            ) : (
                                                <span className="text-xs text-muted-foreground">
                                                    Aucun
                                                </span>
                                            )}
                                        </div>
                                        <div className="grid min-w-0 flex-1 gap-2">
                                            <input
                                                ref={logoInput}
                                                id="logo"
                                                name="logo"
                                                type="file"
                                                accept="image/png,image/jpeg,image/webp"
                                                disabled={!canUpdate}
                                                onChange={onLogoChange}
                                                className="sr-only"
                                                tabIndex={-1}
                                            />
                                            <label
                                                htmlFor="logo"
                                                onDragOver={(e) => {
                                                    e.preventDefault();
                                                    setLogoDragging(true);
                                                }}
                                                onDragLeave={() =>
                                                    setLogoDragging(false)
                                                }
                                                onDrop={(e) => {
                                                    e.preventDefault();
                                                    setLogoDragging(false);

                                                    if (
                                                        !canUpdate ||
                                                        !logoInput.current ||
                                                        e.dataTransfer.files
                                                            .length === 0
                                                    ) {
                                                        return;
                                                    }

                                                    const transfer =
                                                        new DataTransfer();
                                                    transfer.items.add(
                                                        e.dataTransfer.files[0],
                                                    );
                                                    logoInput.current.files =
                                                        transfer.files;
                                                    logoInput.current.dispatchEvent(
                                                        new Event('change', {
                                                            bubbles: true,
                                                        }),
                                                    );
                                                }}
                                                className={`flex min-h-20 flex-col items-center justify-center gap-1 rounded-lg border-2 border-dashed p-3 text-center hover:bg-muted ${canUpdate ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'} ${logoDragging ? 'border-primary bg-muted' : ''}`}
                                            >
                                                <UploadCloud className="size-6 text-muted-foreground" />
                                                <span className="text-sm font-medium">
                                                    Ajouter un logo
                                                </span>
                                                <span className="text-xs text-muted-foreground">
                                                    ou glissez-le ici
                                                </span>
                                            </label>
                                            <p className="text-xs text-muted-foreground">
                                                PNG, JPG ou WebP, 2 Mo maximum.
                                            </p>
                                        </div>
                                    </div>
                                    {settings.logo_url && canUpdate && (
                                        <label className="flex items-center gap-2 text-sm">
                                            <Checkbox
                                                checked={removeLogo}
                                                onCheckedChange={(checked) =>
                                                    setRemoveLogo(
                                                        checked === true,
                                                    )
                                                }
                                            />
                                            Supprimer le logo
                                        </label>
                                    )}
                                    {removeLogo && (
                                        <input
                                            type="hidden"
                                            name="remove_logo"
                                            value="1"
                                        />
                                    )}
                                    <InputError
                                        message={logoError ?? errors.logo}
                                    />
                                </div>
                            </Section>

                            <Section title="Sécurité">
                                <Field
                                    id="password_expiry_days"
                                    label="Expiration du mot de passe (jours)"
                                    hint="0 = jamais"
                                    error={errors.password_expiry_days}
                                >
                                    <Input
                                        type="number"
                                        min={0}
                                        max={365}
                                        {...text('password_expiry_days')}
                                        required
                                    />
                                </Field>
                                <Field
                                    id="max_failed_login_attempts"
                                    label="Tentatives de connexion échouées max."
                                    hint="Entre 3 et 20"
                                    error={errors.max_failed_login_attempts}
                                >
                                    <Input
                                        type="number"
                                        min={3}
                                        max={20}
                                        {...text('max_failed_login_attempts')}
                                        required
                                    />
                                </Field>
                                <Field
                                    id="lockout_minutes"
                                    label="Durée de verrouillage (minutes)"
                                    hint="Entre 1 et 1440"
                                    error={errors.lockout_minutes}
                                >
                                    <Input
                                        type="number"
                                        min={1}
                                        max={1440}
                                        {...text('lockout_minutes')}
                                        required
                                    />
                                </Field>
                            </Section>

                            {canUpdate && (
                                <Button type="submit" disabled={processing}>
                                    {processing
                                        ? 'Enregistrement…'
                                        : 'Enregistrer'}
                                </Button>
                            )}
                        </>
                    )}
                </Form>
            </div>
        </>
    );
}

AppSettingsPage.layout = {
    breadcrumbs: [
        { title: 'Tableau de bord', href: dashboard() },
        { title: 'Paramètres', href: edit() },
    ],
};
