import { CalendarDays, ChevronDown, X } from 'lucide-react';
import { useState } from 'react';
import { es } from 'react-day-picker/locale';
import type { DateRange } from 'react-day-picker';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { cn } from '@/lib/utils';

const iso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
const desdeIso = (s: string) => {
    const [y, m, d] = s.split('-').map(Number);
    return new Date(y!, m! - 1, d!);
};
const MESES = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'];
const corta = (s: string) => {
    const d = desdeIso(s);
    return `${d.getDate()} ${MESES[d.getMonth()]} ${d.getFullYear()}`;
};

function atajos(): { id: string; label: string; desde: string; hasta: string }[] {
    const hoy = new Date();
    const y = hoy.getFullYear();
    const m = hoy.getMonth();
    const hace30 = new Date(hoy);
    hace30.setDate(hoy.getDate() - 29);
    return [
        { id: 'mes', label: 'Este mes', desde: iso(new Date(y, m, 1)), hasta: iso(hoy) },
        { id: 'anterior', label: 'Mes anterior', desde: iso(new Date(y, m - 1, 1)), hasta: iso(new Date(y, m, 0)) },
        { id: '30', label: 'Últimos 30 días', desde: iso(hace30), hasta: iso(hoy) },
        { id: 'trimestre', label: 'Este trimestre', desde: iso(new Date(y, Math.floor(m / 3) * 3, 1)), hasta: iso(hoy) },
        { id: 'ytd', label: 'Año a la fecha', desde: iso(new Date(y, 0, 1)), hasta: iso(hoy) },
        { id: 'anio-ant', label: 'Año anterior', desde: iso(new Date(y - 1, 0, 1)), hasta: iso(new Date(y - 1, 11, 31)) },
    ];
}

/** Selector de periodo: atajos frecuentes + calendario de rango. */
export function PeriodoPicker({ desde, hasta, onChange }: { desde: string; hasta: string; onChange: (p: { desde: string; hasta: string }) => void }) {
    const [abierto, setAbierto] = useState(false);
    const [rango, setRango] = useState<DateRange | undefined>({ from: desdeIso(desde), to: desdeIso(hasta) });
    const lista = atajos();
    const actual = lista.find((a) => a.desde === desde && a.hasta === hasta);

    return (
        <Popover open={abierto} onOpenChange={(o) => (setAbierto(o), o && setRango({ from: desdeIso(desde), to: desdeIso(hasta) }))}>
            <PopoverTrigger asChild>
                <Button variant="outline" className="h-10 justify-start gap-2 bg-white font-normal">
                    <CalendarDays className="size-4 text-primary" />
                    <span className="font-medium">{actual ? actual.label : 'Personalizado'}</span>
                    <span className="hidden text-muted-foreground md:inline">
                        · {corta(desde)} – {corta(hasta)}
                    </span>
                    <ChevronDown className="ml-1 size-4 text-muted-foreground" />
                </Button>
            </PopoverTrigger>
            <PopoverContent align="start" className="flex w-auto gap-0 p-0">
                <div className="flex w-40 flex-col gap-1 border-r p-2">
                    {lista.map((a) => (
                        <button
                            key={a.id}
                            type="button"
                            onClick={() => (onChange({ desde: a.desde, hasta: a.hasta }), setAbierto(false))}
                            className={cn('rounded-md px-3 py-2 text-left text-sm hover:bg-accent', actual?.id === a.id && 'bg-accent font-semibold text-accent-foreground')}
                        >
                            {a.label}
                        </button>
                    ))}
                </div>
                <div className="p-2">
                    <Calendar mode="range" locale={es} numberOfMonths={2} defaultMonth={rango?.from} selected={rango} onSelect={setRango} />
                    <div className="flex items-center justify-between border-t px-2 pt-2">
                        <span className="text-xs text-muted-foreground">{rango?.from && rango?.to ? `${corta(iso(rango.from))} – ${corta(iso(rango.to))}` : 'Elige inicio y fin'}</span>
                        <Button size="sm" disabled={!rango?.from || !rango?.to} onClick={() => (onChange({ desde: iso(rango!.from!), hasta: iso(rango!.to!) }), setAbierto(false))}>
                            Aplicar
                        </Button>
                    </div>
                </div>
            </PopoverContent>
        </Popover>
    );
}

/** Filtro de una dimensión con opción "todas". */
export function Filtro({ label, value, todos, options, onChange }: { label: string; value: string; todos: string; options: string[]; onChange: (v: string) => void }) {
    const activo = value !== todos;
    return (
        <Select value={value} onValueChange={onChange}>
            <SelectTrigger className={cn('h-10 min-w-40 bg-white', activo && 'border-primary/40 bg-accent text-accent-foreground')}>
                <span className="text-xs text-muted-foreground">{label}:</span>
                <SelectValue />
            </SelectTrigger>
            <SelectContent>
                <SelectItem value={todos}>{todos === 'TODOS' ? 'Todos' : 'Todas'}</SelectItem>
                {options.map((o) => (
                    <SelectItem key={o} value={o}>
                        {o}
                    </SelectItem>
                ))}
            </SelectContent>
        </Select>
    );
}

/**
 * Filtro de selección múltiple (como la app anterior). El valor viaja como texto:
 * "TODAS"/"TODOS" = sin filtro, o los valores elegidos unidos con "|".
 */
export function FiltroMultiple({ label, value, todos, options, onChange }: { label: string; value: string; todos: string; options: string[]; onChange: (v: string) => void }) {
    const seleccion = value === todos || !value ? [] : value.split('|').filter(Boolean);
    const [abierto, setAbierto] = useState(false);
    const [borrador, setBorrador] = useState<string[]>(seleccion);
    const [buscar, setBuscar] = useState('');
    const visibles = options.filter((o) => !buscar || o.toLowerCase().includes(buscar.toLowerCase()));
    const todasLabel = todos === 'TODOS' ? 'Todos' : 'Todas';
    const resumen = seleccion.length === 0 ? todasLabel : seleccion.length === 1 ? seleccion[0] : `${seleccion.length} seleccionadas`;
    const alternar = (o: string) => setBorrador((b) => (b.includes(o) ? b.filter((x) => x !== o) : [...b, o]));
    const aplicar = (v: string[]) => {
        onChange(v.length === 0 || v.length === options.length ? todos : v.join('|'));
        setAbierto(false);
    };

    return (
        <Popover open={abierto} onOpenChange={(o) => (setAbierto(o), o && (setBorrador(seleccion), setBuscar('')))}>
            <PopoverTrigger asChild>
                <Button variant="outline" className={cn('h-10 min-w-40 justify-between gap-2 bg-white font-normal', seleccion.length > 0 && 'border-primary/40 bg-accent text-accent-foreground')}>
                    <span className="flex min-w-0 items-center gap-1.5">
                        <span className="text-xs text-muted-foreground">{label}:</span>
                        <span className="max-w-40 truncate font-medium">{resumen}</span>
                    </span>
                    <ChevronDown className="size-4 text-muted-foreground" />
                </Button>
            </PopoverTrigger>
            <PopoverContent align="start" className="w-72 p-0">
                <div className="flex items-center justify-between border-b px-3 py-2">
                    <span className="text-xs font-semibold tracking-wide text-muted-foreground uppercase">{label}</span>
                    {borrador.length > 0 && (
                        <button type="button" onClick={() => setBorrador([])} className="text-xs font-semibold text-primary hover:underline">
                            Limpiar
                        </button>
                    )}
                </div>
                {options.length > 8 && (
                    <div className="border-b p-2">
                        <Input autoFocus value={buscar} onChange={(e) => setBuscar(e.target.value)} placeholder={`Buscar ${label.toLowerCase()}…`} className="h-8" />
                    </div>
                )}
                <div className="max-h-64 overflow-y-auto p-1">
                    {!buscar && (
                        <label className="flex cursor-pointer items-center gap-2.5 rounded-md px-2 py-2 text-sm hover:bg-accent">
                            <Checkbox checked={borrador.length === 0} onCheckedChange={() => setBorrador([])} />
                            <span className="font-medium">{todasLabel}</span>
                        </label>
                    )}
                    {visibles.map((o) => (
                        <label key={o} className="flex cursor-pointer items-center gap-2.5 rounded-md px-2 py-2 text-sm hover:bg-accent">
                            <Checkbox checked={borrador.includes(o)} onCheckedChange={() => alternar(o)} />
                            <span className="truncate">{o}</span>
                        </label>
                    ))}
                    {visibles.length === 0 && <p className="px-2 py-3 text-sm text-muted-foreground">Sin resultados.</p>}
                </div>
                <div className="flex items-center justify-between gap-2 border-t p-2">
                    <span className="pl-1 text-xs text-muted-foreground">{borrador.length ? `${borrador.length} de ${options.length}` : todasLabel}</span>
                    <span className="flex gap-2">
                        <Button variant="ghost" size="sm" onClick={() => setAbierto(false)}>
                            Cancelar
                        </Button>
                        <Button size="sm" onClick={() => aplicar(borrador)}>
                            Aplicar
                        </Button>
                    </span>
                </div>
            </PopoverContent>
        </Popover>
    );
}

export function LimpiarFiltros({ visible, onClick }: { visible: boolean; onClick: () => void }) {
    if (!visible) return null;
    return (
        <Button variant="ghost" className="h-10 text-muted-foreground" onClick={onClick}>
            <X className="size-4" /> Limpiar filtros
        </Button>
    );
}
