import { Head, Link, useForm } from '@inertiajs/react';
import { ExternalLink, FileText } from 'lucide-react';
import type { FormEvent } from 'react';
import { useMemo, useState } from 'react';
import { ConfirmActionModal } from '@/components/confirm-action-modal';
import Heading from '@/components/heading';
import InputError from '@/components/input-error';
import { RichTextEditor } from '@/components/rich-text-editor';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';

type LegalDocument = {
    key: string;
    title: string;
    body: string;
    href: string;
};

type Props = {
    documents: LegalDocument[];
};

type FormData = {
    documents: LegalDocument[];
};

export default function LegalDocuments({ documents }: Props) {
    const form = useForm<FormData>({
        documents,
    });
    const [activeKey, setActiveKey] = useState(documents[0]?.key ?? '');
    const [saveConfirmOpen, setSaveConfirmOpen] = useState(false);

    const activeDocument = useMemo(
        () =>
            form.data.documents.find(
                (document) => document.key === activeKey,
            ) ?? form.data.documents[0],
        [activeKey, form.data.documents],
    );

    function updateDocument(key: string, patch: Partial<LegalDocument>) {
        form.setData(
            'documents',
            form.data.documents.map((document) =>
                document.key === key ? { ...document, ...patch } : document,
            ),
        );
    }

    function submit(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        setSaveConfirmOpen(true);
    }

    function executeSave() {
        form.put('/admin/documentos-legales', {
            preserveScroll: true,
            onFinish: () => setSaveConfirmOpen(false),
        });
    }

    return (
        <>
            <Head title="Documentos legales" />

            <div className="space-y-6">
                <div className="flex flex-wrap items-start justify-between gap-4">
                    <Heading
                        title="Documentos legales"
                        description="Edita los términos, la política de privacidad y el contrato que ven los usuarios antes de continuar."
                    />
                    {activeDocument ? (
                        <Button asChild type="button" variant="outline">
                            <Link href={activeDocument.href} target="_blank">
                                <ExternalLink className="size-4" />
                                Ver documento
                            </Link>
                        </Button>
                    ) : null}
                </div>

                <form className="space-y-6" onSubmit={submit}>
                    <Card>
                        <CardHeader>
                            <div className="flex gap-3">
                                <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
                                    <FileText className="size-5" aria-hidden />
                                </div>
                                <div className="min-w-0 space-y-1">
                                    <CardTitle>Contenido legal</CardTitle>
                                    <CardDescription>
                                        El contenido se guarda como HTML
                                        saneado. Pega texto plano y usa la barra
                                        del editor para dar formato.
                                    </CardDescription>
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent className="grid gap-6 lg:grid-cols-[17rem_1fr]">
                            <div className="flex gap-2 overflow-x-auto lg:flex-col lg:overflow-visible">
                                {form.data.documents.map((document) => (
                                    <button
                                        key={document.key}
                                        className={cn(
                                            'min-w-max rounded-lg border px-4 py-3 text-left text-sm transition-colors lg:min-w-0',
                                            document.key === activeDocument?.key
                                                ? 'border-primary bg-primary/10 text-foreground'
                                                : 'border-border bg-background text-muted-foreground hover:bg-muted/60 hover:text-foreground',
                                        )}
                                        type="button"
                                        onClick={() =>
                                            setActiveKey(document.key)
                                        }
                                    >
                                        <span className="block font-medium">
                                            {document.title}
                                        </span>
                                        <span className="mt-1 block text-xs opacity-80">
                                            {document.key}
                                        </span>
                                    </button>
                                ))}
                            </div>

                            {activeDocument ? (
                                <div className="space-y-5">
                                    <div className="grid gap-2">
                                        <Label
                                            htmlFor={`title-${activeDocument.key}`}
                                        >
                                            Título
                                        </Label>
                                        <Input
                                            id={`title-${activeDocument.key}`}
                                            value={activeDocument.title}
                                            onChange={(event) =>
                                                updateDocument(
                                                    activeDocument.key,
                                                    {
                                                        title: event.target
                                                            .value,
                                                    },
                                                )
                                            }
                                        />
                                        <InputError
                                            message={
                                                form.errors[
                                                    `documents.${form.data.documents.findIndex((document) => document.key === activeDocument.key)}.title`
                                                ]
                                            }
                                        />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label
                                            htmlFor={`body-${activeDocument.key}`}
                                        >
                                            Contenido
                                        </Label>
                                        <RichTextEditor
                                            id={`body-${activeDocument.key}`}
                                            value={activeDocument.body}
                                            onChange={(body) =>
                                                updateDocument(
                                                    activeDocument.key,
                                                    { body },
                                                )
                                            }
                                        />
                                        <InputError
                                            message={
                                                form.errors[
                                                    `documents.${form.data.documents.findIndex((document) => document.key === activeDocument.key)}.body`
                                                ]
                                            }
                                        />
                                    </div>
                                </div>
                            ) : null}
                        </CardContent>
                    </Card>

                    <div className="sticky bottom-0 z-10 -mx-1 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-background/95 px-4 py-3 shadow-sm backdrop-blur supports-[backdrop-filter]:bg-background/80 sm:-mx-2">
                        <p className="text-sm text-muted-foreground">
                            {form.isDirty
                                ? 'Hay cambios sin guardar.'
                                : 'Todos los cambios están guardados.'}
                        </p>
                        <Button
                            disabled={form.processing || !form.isDirty}
                            type="submit"
                        >
                            {form.processing
                                ? 'Guardando...'
                                : 'Guardar documentos'}
                        </Button>
                    </div>
                </form>
            </div>

            <ConfirmActionModal
                open={saveConfirmOpen}
                onOpenChange={setSaveConfirmOpen}
                title="Guardar documentos legales"
                description="Los cambios serán visibles para los usuarios en las páginas públicas y desde login/registro."
                confirmLabel="Guardar"
                processing={form.processing}
                onConfirm={executeSave}
            />
        </>
    );
}

LegalDocuments.layout = {
    breadcrumbs: [
        { title: 'Administración', href: '/admin' },
        { title: 'Documentos legales', href: '/admin/documentos-legales' },
    ],
};
