import clsx from 'clsx';
import { useEffect, useState, type ReactNode } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';

/* Piezas compartidas de Administración → Presupuesto, con el patrón visual de Administración → Usuarios. */

export function Msg({ msg }: { msg: { t: 'ok' | 'err'; m: string } | null }) {
    if (!msg) return null;
    return <p className={clsx('mb-4 rounded-lg border px-4 py-2.5 text-sm whitespace-pre-line', msg.t === 'ok' ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : 'border-red-200 bg-red-50 text-red-800')}>{msg.m}</p>;
}

/** Tarjeta con encabezado (título, ayuda y acción a la derecha) y cuerpo. */
export function Caja({ titulo, sub, derecha, children, className }: { titulo: string; sub?: string; derecha?: ReactNode; children: ReactNode; className?: string }) {
    return (
        <section className={clsx('rounded-xl border border-border bg-white', className)}>
            <div className="flex flex-wrap items-start justify-between gap-3 border-b border-border px-5 py-4">
                <div className="min-w-0">
                    <h2 className="text-sm font-semibold">{titulo}</h2>
                    {sub && <p className="mt-0.5 text-sm text-muted-foreground">{sub}</p>}
                </div>
                {derecha}
            </div>
            <div className="p-5">{children}</div>
        </section>
    );
}

/** Cifra destacada (reemplaza a las KpiCard en esta pantalla). */
export function Dato({ titulo, valor, detalle }: { titulo: string; valor: ReactNode; detalle?: ReactNode }) {
    return (
        <div className="rounded-xl border border-border bg-white p-4">
            <p className="text-sm text-muted-foreground">{titulo}</p>
            <p className="mt-1 text-2xl font-bold tracking-tight tabular-nums">{valor}</p>
            {detalle && <p className="mt-0.5 text-xs text-muted-foreground">{detalle}</p>}
        </div>
    );
}

/** Botón del módulo sobre el Button del sistema: primario/oscuro = principal, neutro = contorno, peligro = contorno rojo. */
export function Btn({ children, onClick, disabled, tono = 'primario', type = 'button' }: { children: ReactNode; onClick?: () => void; disabled?: boolean; tono?: 'primario' | 'oscuro' | 'neutro' | 'peligro'; type?: 'button' | 'submit' }) {
    return (
        <Button
            type={type}
            size="sm"
            disabled={disabled}
            onClick={onClick}
            variant={tono === 'neutro' || tono === 'peligro' ? 'outline' : 'default'}
            className={clsx(tono === 'peligro' && 'border-red-200 text-red-600 hover:bg-red-50 hover:text-red-700')}
        >
            {children}
        </Button>
    );
}

/** Clase de campos de formulario (input / select nativos) con el estilo del Input del sistema. */
export const input = 'h-9 rounded-md border border-input bg-white px-3 text-sm font-normal text-foreground shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:opacity-50';

export function Estado({ cargando, error }: { cargando: boolean; error: string | null }) {
    if (error) return <p className="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-2.5 text-sm text-red-800">{error}</p>;
    if (cargando)
        return (
            <div className="mb-4 space-y-2" aria-busy="true" aria-label="Cargando">
                <Skeleton className="h-9 w-full" />
                <Skeleton className="h-9 w-full" />
                <Skeleton className="h-9 w-2/3" />
            </div>
        );
    return null;
}

/** Tabla con cabecera clara fija; el relleno de las celdas lo pone la tabla (las filas solo marcan alineación). */
export function Tabla({ cols, children, min = 'min-w-[700px]' }: { cols: (string | [string, 'r' | 'c'])[]; children: ReactNode; min?: string }) {
    return (
        <div className="max-h-[60vh] overflow-auto rounded-lg border border-border">
            <table className={clsx('w-full text-sm tabular-nums [&_td]:px-3 [&_td]:py-2.5 [&_tbody_tr:first-child]:border-t-0', min)}>
                <thead className="sticky top-0 z-10 bg-slate-50 text-xs text-muted-foreground">
                    <tr className="border-b border-border">
                        {cols.map((c) => {
                            const [l, a] = Array.isArray(c) ? c : [c, 'l'];
                            return (
                                <th key={l} className={clsx('px-3 py-2.5 font-medium whitespace-nowrap', a === 'r' ? 'text-right' : a === 'c' ? 'text-center' : 'text-left')}>
                                    {l}
                                </th>
                            );
                        })}
                    </tr>
                </thead>
                <tbody>{children}</tbody>
            </table>
        </div>
    );
}

/* ---------- Diálogos (reemplazan confirm() y prompt() del navegador) ---------- */

type Opcion = { valor: string; label: string; variante?: 'default' | 'outline' | 'destructive' };
type Pedido = { titulo: string; descripcion?: ReactNode; opciones: Opcion[]; campo?: { tipo: 'text' | 'date'; valor: string; etiqueta?: string }; resolver: (r: { valor: string; texto: string } | null) => void };

let mostrar: ((p: Pedido) => void) | null = null;

function pedir(p: Omit<Pedido, 'resolver'>): Promise<{ valor: string; texto: string } | null> {
    return new Promise((resolver) => {
        if (!mostrar) return resolver(null);
        mostrar({ ...p, resolver });
    });
}

/** Pregunta Sí / Cancelar. */
export async function confirmar(titulo: string, opts: { descripcion?: ReactNode; accion?: string; peligro?: boolean } = {}) {
    const r = await pedir({ titulo, descripcion: opts.descripcion, opciones: [{ valor: 'si', label: opts.accion ?? 'Sí, continuar', variante: opts.peligro ? 'destructive' : 'default' }] });
    return r !== null;
}

/** Varias opciones además de Cancelar; devuelve el valor elegido o null. */
export async function elegir(titulo: string, descripcion: ReactNode, opciones: Opcion[]) {
    return (await pedir({ titulo, descripcion, opciones }))?.valor ?? null;
}

/** Pide un texto o una fecha; devuelve null si se cancela o queda vacío. */
export async function pedirTexto(titulo: string, valor: string, opts: { descripcion?: ReactNode; tipo?: 'text' | 'date'; etiqueta?: string; accion?: string } = {}) {
    const r = await pedir({ titulo, descripcion: opts.descripcion, campo: { tipo: opts.tipo ?? 'text', valor, etiqueta: opts.etiqueta }, opciones: [{ valor: 'ok', label: opts.accion ?? 'Guardar' }] });
    const t = r?.texto.trim() ?? '';
    return t === '' ? null : t;
}

/** Monta una vez en la página: muestra los diálogos pedidos con confirmar / elegir / pedirTexto. */
export function DialogosPresupuesto() {
    const [p, setP] = useState<Pedido | null>(null);
    const [texto, setTexto] = useState('');

    useEffect(() => {
        mostrar = (nuevo) => {
            setTexto(nuevo.campo?.valor ?? '');
            setP(nuevo);
        };
        return () => {
            mostrar = null;
        };
    }, []);

    const cerrar = (r: { valor: string; texto: string } | null) => {
        p?.resolver(r);
        setP(null);
    };

    return (
        <Dialog open={p !== null} onOpenChange={(o) => !o && cerrar(null)}>
            <DialogContent>
                {p && (
                    <form
                        className="grid gap-4"
                        onSubmit={(e) => {
                            e.preventDefault();
                            const principal = p.opciones[p.opciones.length - 1]!;
                            if (!p.campo || texto.trim()) cerrar({ valor: principal.valor, texto });
                        }}
                    >
                        <DialogHeader>
                            <DialogTitle>{p.titulo}</DialogTitle>
                            {p.descripcion ? <DialogDescription>{p.descripcion}</DialogDescription> : <DialogDescription className="sr-only">Confirmación</DialogDescription>}
                        </DialogHeader>
                        {p.campo && (
                            <label className="block">
                                {p.campo.etiqueta && <span className="mb-1.5 block text-sm font-medium">{p.campo.etiqueta}</span>}
                                <Input autoFocus type={p.campo.tipo} value={texto} onChange={(e) => setTexto(e.target.value)} />
                            </label>
                        )}
                        <DialogFooter>
                            <Button type="button" variant="outline" onClick={() => cerrar(null)}>
                                Cancelar
                            </Button>
                            {p.opciones.map((o, i) => (
                                <Button key={o.valor} type={i === p.opciones.length - 1 ? 'submit' : 'button'} variant={o.variante ?? 'default'} disabled={!!p.campo && !texto.trim()} onClick={i === p.opciones.length - 1 ? undefined : () => cerrar({ valor: o.valor, texto })}>
                                    {o.label}
                                </Button>
                            ))}
                        </DialogFooter>
                    </form>
                )}
            </DialogContent>
        </Dialog>
    );
}
