import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Printer } from 'lucide-react';
import React from 'react';

type UserLite = { id: number | string; name: string };

type ReportLabel = 'checkin' | 'checkout' | 'cleaning';

type Props = {
    open: boolean;
    onClose: () => void;
    label: ReportLabel;
    events: any[];
    menageUsers: UserLite[];
    verifUsers: UserLite[];
};

function normalizeUserPlaned(raw: any): string[] {
    if (raw == null || raw === '') return [];
    if (Array.isArray(raw)) return raw.map((v) => String(v));
    if (typeof raw === 'string') {
        const trimmed = raw.trim();
        if (trimmed.startsWith('[')) {
            try {
                const parsed = JSON.parse(trimmed);
                return Array.isArray(parsed) ? parsed.map((v: any) => String(v)) : [];
            } catch {
                return [];
            }
        }
        return [String(raw)];
    }
    return [String(raw)];
}

function todayISO(): string {
    const d = new Date();
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

function eventDateISO(ev: any): string {
    return ev?.start ? String(ev.start).slice(0, 10) : '';
}

function formatDateHeading(iso: string): string {
    if (!iso) return '';
    const [y, m, d] = iso.split('-');
    return `${d}/${m}/${y}`;
}

function escapeHtml(s: string): string {
    return s
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

const LABEL_TITLES: Record<ReportLabel, string> = {
    checkin: 'Check-in',
    checkout: 'Check-out',
    cleaning: 'Ménage (mi-séjour)',
};

export default function DayReportDialog({ open, onClose, label, events, menageUsers, verifUsers }: Props) {
    const [date, setDate] = React.useState<string>(todayISO());

    const menageById = React.useMemo(() => {
        const m = new Map<string, string>();
        menageUsers.forEach((u) => m.set(String(u.id), u.name));
        return m;
    }, [menageUsers]);

    const verifById = React.useMemo(() => {
        const m = new Map<string, string>();
        verifUsers.forEach((u) => m.set(String(u.id), u.name));
        return m;
    }, [verifUsers]);

    const dayEvents = React.useMemo(() => events.filter((ev) => eventDateISO(ev) === date), [events, date]);

    const grouped = React.useMemo(() => {
        const map = new Map<string, any[]>();
        dayEvents.forEach((ev) => {
            const key = ev?.extendedProps?.property_name || ev?.title || '—';
            if (!map.has(key)) map.set(key, []);
            map.get(key)!.push(ev);
        });
        return Array.from(map.entries()).sort((a, b) => a[0].localeCompare(b[0]));
    }, [dayEvents]);

    const showHousekeepers = label === 'checkout' || label === 'cleaning';
    const showVerifier = label === 'checkin' || label === 'cleaning';

    const housekeeperText = (planning: any) => {
        const ids = normalizeUserPlaned(planning?.userPlaned);
        if (ids.length === 0) return { text: 'Non assignée', missing: true };
        return { text: ids.map((id) => menageById.get(id) ?? `#${id}`).join(', '), missing: false };
    };

    const verifierInfo = (planning: any) => {
        const isVerif = planning?.isVerif === 'Oui';
        if (!isVerif) return { text: 'Non vérifiée', state: 'warn' as const };
        const verifId = planning?.userVerif ? String(planning.userVerif) : '';
        const name = verifId ? verifById.get(verifId) ?? `#${verifId}` : '—';
        return { text: `Vérifiée · ${name}`, state: 'ok' as const };
    };

    const buildPrintHtml = () => {
        const title = `Rapport du jour · ${LABEL_TITLES[label]} · ${formatDateHeading(date)}`;
        const sections = grouped
            .map(([propertyName, evs]) => {
                const rows = evs
                    .map((ev) => {
                        const ext = ev.extendedProps ?? {};
                        const planning = ext.planning;
                        const parts: string[] = [];
                        if (showHousekeepers) {
                            const hk = housekeeperText(planning);
                            parts.push(
                                `<div><span class="lbl">Femme de ménage:</span> <span class="${hk.missing ? 'missing' : ''}">${escapeHtml(hk.text)}</span></div>`,
                            );
                        }
                        if (showVerifier) {
                            const v = verifierInfo(planning);
                            parts.push(
                                `<div><span class="lbl">Vérification:</span> <span class="${v.state}">${escapeHtml(v.text)}</span></div>`,
                            );
                        }
                        if (planning?.arrival_time) {
                            parts.push(`<div><span class="lbl">Arrivée:</span> ${escapeHtml(planning.arrival_time)}</div>`);
                        }
                        if (planning?.exit_time) {
                            parts.push(`<div><span class="lbl">Départ:</span> ${escapeHtml(planning.exit_time)}</div>`);
                        }
                        const comment = planning?.comment
                            ? `<div class="comment"><span class="lbl">Commentaire:</span> ${escapeHtml(planning.comment)}</div>`
                            : '';
                        const phone = ext.phone ? `<div class="phone">📞 ${escapeHtml(ext.phone)}</div>` : '';
                        return `
              <li class="res">
                <div class="row1">
                  <span class="name">${escapeHtml(ext.guest || '—')}</span>
                  <span class="meta">${escapeHtml(ext.platform || '')} · #${escapeHtml(String(ev.id))}</span>
                </div>
                ${phone}
                <div class="grid">${parts.join('')}</div>
                ${comment}
              </li>`;
                    })
                    .join('');
                return `<section><h3>${escapeHtml(propertyName)}</h3><ul>${rows}</ul></section>`;
            })
            .join('');

        const empty = grouped.length === 0 ? `<p style="font-style:italic;color:#6b7280;">Aucune réservation pour cette date.</p>` : '';

        return `<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8" />
<title>${escapeHtml(title)}</title>
<style>
  * { box-sizing: border-box; }
  body { font-family: -apple-system, Segoe UI, Roboto, sans-serif; margin: 24px; color: #111; }
  h1 { font-size: 20px; margin: 0 0 16px; }
  h3 { font-size: 13px; text-transform: uppercase; letter-spacing: 0.04em; color: #374151; margin: 20px 0 8px; border-bottom: 1px solid #d1d5db; padding-bottom: 4px; }
  ul { list-style: none; padding: 0; margin: 0; }
  .res { border: 1px solid #d1d5db; border-radius: 6px; padding: 10px 12px; margin-bottom: 8px; font-size: 12px; page-break-inside: avoid; }
  .res .row1 { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; }
  .res .name { font-weight: 600; font-size: 13px; }
  .res .meta { color: #6b7280; font-size: 11px; }
  .res .phone { color: #374151; font-size: 11px; margin-top: 2px; }
  .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 4px 24px; margin-top: 8px; font-size: 11px; }
  .lbl { color: #6b7280; }
  .missing { color: #b91c1c; font-weight: 500; }
  .warn { color: #b45309; }
  .ok { color: #15803d; }
  .comment { background: #f3f4f6; padding: 6px 8px; border-radius: 4px; margin-top: 8px; font-size: 11px; }
  @media print { body { margin: 12mm; } }
</style>
</head>
<body>
<h1>${escapeHtml(title)}</h1>
${empty}
${sections}
</body>
</html>`;
    };

    const handlePrint = () => {
        const w = window.open('', '_blank', 'width=900,height=700');
        if (!w) return;
        w.document.open();
        w.document.write(buildPrintHtml());
        w.document.close();
        w.focus();
        setTimeout(() => {
            w.print();
        }, 150);
    };

    return (
        <Dialog open={open} onOpenChange={onClose}>
            <DialogContent className="max-w-3xl">
                <DialogHeader>
                    <DialogTitle>Rapport du jour · {LABEL_TITLES[label]}</DialogTitle>
                    <DialogDescription>
                        {dayEvents.length} réservation{dayEvents.length > 1 ? 's' : ''} le {formatDateHeading(date)}
                    </DialogDescription>
                </DialogHeader>

                <div className="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
                    <div>
                        <Label>Date</Label>
                        <Input type="date" value={date} onChange={(e) => setDate(e.target.value)} className="mt-1 w-full sm:w-48" />
                    </div>
                    <Button type="button" variant="outline" onClick={handlePrint} className="gap-2">
                        <Printer className="h-4 w-4" /> Imprimer
                    </Button>
                </div>

                <div className="mt-2 max-h-[60vh] overflow-y-auto pr-1">
                    {grouped.length === 0 && (
                        <p className="text-muted-foreground text-sm italic">Aucune réservation pour cette date.</p>
                    )}

                    <ul className="divide-border divide-y">
                        {grouped.map(([propertyName, evs]) => (
                            <li key={propertyName} className="py-3">
                                <h3 className="text-sm font-semibold uppercase tracking-wide text-gray-700">{propertyName}</h3>
                                <ul className="mt-2 space-y-2">
                                    {evs.map((ev) => {
                                        const ext = ev.extendedProps ?? {};
                                        const planning = ext.planning;
                                        const hk = showHousekeepers ? housekeeperText(planning) : null;
                                        const vf = showVerifier ? verifierInfo(planning) : null;
                                        return (
                                            <li key={ev.id} className="rounded-md border bg-gray-50 p-3 text-sm">
                                                <div className="flex flex-wrap items-baseline justify-between gap-x-3">
                                                    <span className="font-medium">{ext.guest || '—'}</span>
                                                    <span className="text-xs text-gray-500">
                                                        {ext.platform || ''} · #{ev.id}
                                                    </span>
                                                </div>
                                                {ext.phone && <div className="text-xs text-gray-600">📞 {ext.phone}</div>}
                                                <div className="mt-2 grid grid-cols-1 gap-x-6 gap-y-1 text-xs sm:grid-cols-2">
                                                    {hk && (
                                                        <div>
                                                            <span className="text-gray-500">Femme de ménage: </span>
                                                            <span className={hk.missing ? 'font-medium text-red-600' : ''}>{hk.text}</span>
                                                        </div>
                                                    )}
                                                    {vf && (
                                                        <div>
                                                            <span className="text-gray-500">Vérification: </span>
                                                            <span className={vf.state === 'ok' ? 'text-green-700' : 'text-amber-600'}>{vf.text}</span>
                                                        </div>
                                                    )}
                                                    {planning?.arrival_time && (
                                                        <div>
                                                            <span className="text-gray-500">Arrivée: </span>
                                                            {planning.arrival_time}
                                                        </div>
                                                    )}
                                                    {planning?.exit_time && (
                                                        <div>
                                                            <span className="text-gray-500">Départ: </span>
                                                            {planning.exit_time}
                                                        </div>
                                                    )}
                                                </div>
                                                {planning?.comment && (
                                                    <div className="mt-2 rounded bg-white p-2 text-xs text-gray-700">
                                                        <span className="text-gray-500">Commentaire: </span>
                                                        {planning.comment}
                                                    </div>
                                                )}
                                            </li>
                                        );
                                    })}
                                </ul>
                            </li>
                        ))}
                    </ul>
                </div>

                <DialogFooter>
                    <Button type="button" variant="outline" onClick={onClose}>
                        Fermer
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
