import { Head, useForm } from '@inertiajs/react';
import { AlertTriangle, History, ImageIcon, ImageUp } from 'lucide-react';
import type { FormEvent } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { ConfirmActionModal } from '@/components/confirm-action-modal';
import Heading from '@/components/heading';
import { InertiaPaginatorFooter } from '@/components/inertia-paginator-footer';
import type { InertiaPaginatorSlice } from '@/components/inertia-paginator-footer';
import InputError from '@/components/input-error';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';

type SnapshotRow = {
    id: number;
    image_url: string;
    original_name: string;
    size_bytes: number;
    closing_date: string | null;
    note: string | null;
    is_active: boolean;
    uploaded_by: string | null;
    uploaded_at: string | null;
    replaced_by: string | null;
    replaced_at: string | null;
};

type Props = {
    active: SnapshotRow | null;
    history: InertiaPaginatorSlice & { data: SnapshotRow[] };
    max_upload_mb: number;
};

type FormData = {
    image: File | null;
    closing_date: string;
    note: string;
};

function todayIso(): string {
    const now = new Date();
    const offset = now.getTimezoneOffset() * 60000;

    return new Date(now.getTime() - offset).toISOString().slice(0, 10);
}

function formatDateTime(iso: string | null): string {
    return iso
        ? new Date(iso).toLocaleString('es', {
              dateStyle: 'medium',
              timeStyle: 'short',
          })
        : '—';
}

function formatClosingDate(date: string | null): string {
    // `YYYY-MM-DD` sin hora: se fija al mediodía para que la zona horaria no cambie el día.
    return date
        ? new Date(`${date}T12:00:00`).toLocaleDateString('es', {
              dateStyle: 'long',
          })
        : '—';
}

export default function ProviderClosing({
    active,
    history,
    max_upload_mb,
}: Props) {
    const form = useForm<FormData>({
        image: null,
        closing_date: todayIso(),
        note: '',
    });
    const [confirmOpen, setConfirmOpen] = useState(false);
    const [viewing, setViewing] = useState<SnapshotRow | null>(null);
    const fileInput = useRef<HTMLInputElement>(null);

    const preview = useMemo(
        () => (form.data.image ? URL.createObjectURL(form.data.image) : null),
        [form.data.image],
    );

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

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

    function executeUpload() {
        form.post('/admin/cierre-proveedor', {
            forceFormData: true,
            preserveScroll: true,
            onSuccess: () => {
                form.reset();

                if (fileInput.current) {
                    fileInput.current.value = '';
                }
            },
            onFinish: () => setConfirmOpen(false),
        });
    }

    return (
        <>
            <Head title="Operativa VT Markets Ultima Markets" />

            <div className="space-y-6">
                <Heading
                    title="Operativa VT Markets Ultima Markets"
                    description="Publica la captura de MetaTrader de la operativa de VT Markets y Ultima Markets. Los inversionistas solo ven la imagen activa; al subir una nueva, la anterior pasa al historial."
                />

                <div className="grid gap-6 lg:grid-cols-2">
                    <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">
                                    <ImageIcon className="size-5" aria-hidden />
                                </div>
                                <div className="min-w-0 space-y-1">
                                    <CardTitle>Imagen activa</CardTitle>
                                    <CardDescription>
                                        Es la que ven hoy los inversionistas.
                                    </CardDescription>
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent>
                            {active ? (
                                <div className="space-y-3">
                                    <button
                                        className="block w-full overflow-hidden rounded-lg border bg-muted/30"
                                        type="button"
                                        onClick={() => setViewing(active)}
                                    >
                                        <img
                                            alt="Operativa VT Markets Ultima Markets activa"
                                            className="mx-auto max-h-[28rem] w-auto object-contain"
                                            src={active.image_url}
                                        />
                                    </button>
                                    <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">
                                        <dt className="text-muted-foreground">
                                            Cierre del
                                        </dt>
                                        <dd>
                                            {formatClosingDate(
                                                active.closing_date,
                                            )}
                                        </dd>
                                        <dt className="text-muted-foreground">
                                            Subida por
                                        </dt>
                                        <dd>
                                            {active.uploaded_by ?? '—'} ·{' '}
                                            {formatDateTime(active.uploaded_at)}
                                        </dd>
                                        {active.note ? (
                                            <>
                                                <dt className="text-muted-foreground">
                                                    Nota
                                                </dt>
                                                <dd className="whitespace-pre-line">
                                                    {active.note}
                                                </dd>
                                            </>
                                        ) : null}
                                    </dl>
                                </div>
                            ) : (
                                <p className="rounded-lg border border-dashed px-4 py-10 text-center text-sm text-muted-foreground">
                                    Aún no se ha publicado ninguna imagen. Los
                                    inversionistas ven un aviso de que todavía
                                    no hay cierre disponible.
                                </p>
                            )}
                        </CardContent>
                    </Card>

                    <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">
                                    <ImageUp className="size-5" aria-hidden />
                                </div>
                                <div className="min-w-0 space-y-1">
                                    <CardTitle>Publicar nueva imagen</CardTitle>
                                    <CardDescription>
                                        Reemplaza la imagen activa. JPG, PNG o
                                        WEBP de hasta {max_upload_mb} MB.
                                    </CardDescription>
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent>
                            <form className="space-y-5" onSubmit={submit}>
                                <div className="flex gap-3 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-sm">
                                    <AlertTriangle
                                        className="mt-0.5 size-4 shrink-0 text-amber-500"
                                        aria-hidden
                                    />
                                    <p>
                                        Recorta la captura antes de subirla: las
                                        pantallas de MetaTrader suelen mostrar
                                        el número de cuenta, el servidor y el
                                        balance del proveedor, y todos los
                                        inversionistas los verían.
                                    </p>
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="image">Captura</Label>
                                    <Input
                                        ref={fileInput}
                                        accept="image/jpeg,image/png,image/webp"
                                        id="image"
                                        name="image"
                                        required
                                        type="file"
                                        onChange={(event) =>
                                            form.setData(
                                                'image',
                                                event.target.files?.item(0) ??
                                                    null,
                                            )
                                        }
                                    />
                                    <InputError message={form.errors.image} />
                                    {preview ? (
                                        <img
                                            alt="Vista previa"
                                            className="mx-auto max-h-64 w-auto rounded-lg border object-contain"
                                            src={preview}
                                        />
                                    ) : null}
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="closing_date">
                                        Fecha del cierre
                                    </Label>
                                    <Input
                                        id="closing_date"
                                        max={todayIso()}
                                        name="closing_date"
                                        required
                                        type="date"
                                        value={form.data.closing_date}
                                        onChange={(event) =>
                                            form.setData(
                                                'closing_date',
                                                event.target.value,
                                            )
                                        }
                                    />
                                    <InputError
                                        message={form.errors.closing_date}
                                    />
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="note">
                                        Nota interna{' '}
                                        <span className="text-muted-foreground">
                                            (opcional, no la ven los
                                            inversionistas)
                                        </span>
                                    </Label>
                                    <Textarea
                                        id="note"
                                        maxLength={500}
                                        name="note"
                                        rows={3}
                                        value={form.data.note}
                                        onChange={(event) =>
                                            form.setData(
                                                'note',
                                                event.target.value,
                                            )
                                        }
                                    />
                                    <InputError message={form.errors.note} />
                                </div>

                                <div className="flex justify-end">
                                    <Button
                                        disabled={
                                            form.processing || !form.data.image
                                        }
                                        type="submit"
                                    >
                                        {form.processing
                                            ? 'Publicando…'
                                            : 'Publicar imagen'}
                                    </Button>
                                </div>
                            </form>
                        </CardContent>
                    </Card>
                </div>

                <Card className="gap-0 overflow-hidden pb-0">
                    <CardHeader className="pb-4">
                        <div className="flex gap-3">
                            <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
                                <History className="size-5" aria-hidden />
                            </div>
                            <div className="min-w-0 space-y-1">
                                <CardTitle>Historial de cambios</CardTitle>
                                <CardDescription>
                                    Todas las imágenes publicadas, quién las
                                    subió y quién las reemplazó.
                                </CardDescription>
                            </div>
                        </div>
                    </CardHeader>
                    <CardContent className="p-0">
                        {history.data.length === 0 ? (
                            <p className="border-t px-6 py-8 text-center text-sm text-muted-foreground">
                                Sin cambios registrados.
                            </p>
                        ) : (
                            <div className="overflow-x-auto border-t">
                                <table className="w-full min-w-[44rem] text-sm">
                                    <thead className="bg-muted/40 text-left text-xs text-muted-foreground">
                                        <tr>
                                            <th className="px-4 py-3 font-medium">
                                                Imagen
                                            </th>
                                            <th className="px-4 py-3 font-medium">
                                                Cierre del
                                            </th>
                                            <th className="px-4 py-3 font-medium">
                                                Subida
                                            </th>
                                            <th className="px-4 py-3 font-medium">
                                                Estado
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {history.data.map((row) => (
                                            <tr
                                                key={row.id}
                                                className="border-t align-top"
                                            >
                                                <td className="px-4 py-3">
                                                    <button
                                                        aria-label={`Ver imagen #${row.id}`}
                                                        className="block overflow-hidden rounded-md border bg-muted/30"
                                                        type="button"
                                                        onClick={() =>
                                                            setViewing(row)
                                                        }
                                                    >
                                                        <img
                                                            alt=""
                                                            className="h-16 w-12 object-cover"
                                                            loading="lazy"
                                                            src={row.image_url}
                                                        />
                                                    </button>
                                                </td>
                                                <td className="px-4 py-3">
                                                    {formatClosingDate(
                                                        row.closing_date,
                                                    )}
                                                    {row.note ? (
                                                        <p className="mt-1 max-w-xs text-xs whitespace-pre-line text-muted-foreground">
                                                            {row.note}
                                                        </p>
                                                    ) : null}
                                                </td>
                                                <td className="px-4 py-3">
                                                    <p>
                                                        {row.uploaded_by ?? '—'}
                                                    </p>
                                                    <p className="text-xs text-muted-foreground">
                                                        {formatDateTime(
                                                            row.uploaded_at,
                                                        )}
                                                    </p>
                                                </td>
                                                <td className="px-4 py-3">
                                                    {row.is_active ? (
                                                        <Badge>Activa</Badge>
                                                    ) : (
                                                        <>
                                                            <Badge variant="outline">
                                                                Reemplazada
                                                            </Badge>
                                                            <p className="mt-1 text-xs text-muted-foreground">
                                                                {formatDateTime(
                                                                    row.replaced_at,
                                                                )}
                                                                {row.replaced_by
                                                                    ? ` · por ${row.replaced_by}`
                                                                    : ''}
                                                            </p>
                                                        </>
                                                    )}
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        )}
                        {history.last_page > 1 ? (
                            <InertiaPaginatorFooter paginator={history} />
                        ) : null}
                    </CardContent>
                </Card>
            </div>

            <ConfirmActionModal
                open={confirmOpen}
                onOpenChange={setConfirmOpen}
                title="¿Publicar esta imagen?"
                description="Reemplazará la imagen que ven los inversionistas. La actual quedará en el historial."
                confirmLabel="Sí, publicar"
                processing={form.processing}
                onConfirm={executeUpload}
            />

            <Dialog
                open={viewing !== null}
                onOpenChange={(open) => !open && setViewing(null)}
            >
                <DialogContent className="max-h-[95vh] overflow-y-auto sm:max-w-3xl">
                    <DialogHeader>
                        <DialogTitle>
                            Cierre del{' '}
                            {formatClosingDate(viewing?.closing_date ?? null)}
                        </DialogTitle>
                        <DialogDescription>
                            {viewing?.original_name} · subida por{' '}
                            {viewing?.uploaded_by ?? '—'} el{' '}
                            {formatDateTime(viewing?.uploaded_at ?? null)}
                        </DialogDescription>
                    </DialogHeader>
                    {viewing ? (
                        <img
                            alt={`Operativa VT Markets Ultima Markets #${viewing.id}`}
                            className="mx-auto w-auto max-w-full rounded-lg"
                            src={viewing.image_url}
                        />
                    ) : null}
                </DialogContent>
            </Dialog>
        </>
    );
}

ProviderClosing.layout = {
    breadcrumbs: [
        { title: 'Administración', href: '/admin' },
        {
            title: 'Operativa VT Markets Ultima Markets',
            href: '/admin/cierre-proveedor',
        },
    ],
};
