import { useEffect, useState } from 'react';
import { X, Loader2, ArrowDownRight, ArrowUpRight } from 'lucide-react';

type Row = { date: string; location: string; unit: string; tenant: string; phone: string | null; email: string | null };
type Detail = {
    period: { start: string; end: string };
    move_ins: Row[]; move_outs: Row[];
    counts: { move_ins: number; move_outs: number; net: number };
};

export function MovementModal({ title, location, onClose }: {
    title: string; location?: string | null; onClose: () => void;
}) {
    const [days, setDays] = useState(30);
    const [data, setData] = useState<Detail | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        let cancelled = false;
        setLoading(true);
        fetch(`/portfolio/movement?days=${days}&location=${encodeURIComponent(location ?? '')}`,
            { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then((r) => r.json())
            .then((d) => { if (!cancelled) { setData(d); setLoading(false); } })
            .catch(() => { if (!cancelled) setLoading(false); });
        return () => { cancelled = true; };
    }, [days, location]);

    // Close on Escape — expected behaviour for a modal.
    useEffect(() => {
        const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
        window.addEventListener('keydown', onKey);
        return () => window.removeEventListener('keydown', onKey);
    }, [onClose]);

    return (
        <div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/40 p-4 sm:p-8"
            onClick={onClose}>
            <div className="w-full max-w-4xl rounded-2xl border border-border bg-card shadow-xl"
                onClick={(e) => e.stopPropagation()}>

                <header className="flex items-center justify-between gap-4 border-b border-border px-6 py-4">
                    <h2 className="text-lg font-semibold text-foreground">{title} — Move-Ins / Move-Outs</h2>
                    <div className="flex items-center gap-3">
                        <label className="text-[11px] uppercase tracking-wide text-muted-foreground">Window</label>
                        <select value={days} onChange={(e) => setDays(Number(e.target.value))}
                            className="rounded-md border border-border bg-background px-2.5 py-1.5 text-sm">
                            <option value={7}>Last 7 days</option>
                            <option value={30}>Last 30 days</option>
                            <option value={60}>Last 60 days</option>
                            <option value={90}>Last 90 days</option>
                        </select>
                        <button onClick={onClose} className="rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground">
                            <X className="size-5" />
                        </button>
                    </div>
                </header>

                {loading ? (
                    <div className="flex items-center justify-center gap-2 py-20 text-sm text-muted-foreground">
                        <Loader2 className="size-4 animate-spin" /> Loading movement…
                    </div>
                ) : ! data ? (
                    <p className="py-20 text-center text-sm text-muted-foreground">Couldn't load movement.</p>
                ) : (
                    <div className="max-h-[70vh] overflow-y-auto px-6 py-5">
                        <div className="mb-5 flex flex-wrap items-center gap-2">
                            <Chip tone="emerald">{data.counts.move_ins} Move-Ins</Chip>
                            <Chip tone="rose">{data.counts.move_outs} Move-Outs</Chip>
                            <Chip tone={data.counts.net >= 0 ? 'emerald' : 'rose'}>
                                Net {data.counts.net > 0 ? '+' : ''}{data.counts.net}
                            </Chip>
                            <span className="ml-auto text-sm text-muted-foreground">
                                {data.period.start} → {data.period.end}
                            </span>
                        </div>

                        <Section title="Move-Ins" icon={<ArrowDownRight className="size-4 text-emerald-600" />} rows={data.move_ins} dateLabel="Moved In" />
                        <Section title="Move-Outs" icon={<ArrowUpRight className="size-4 text-destructive" />} rows={data.move_outs} dateLabel="Moved Out" />
                    </div>
                )}
            </div>
        </div>
    );
}

function Chip({ children, tone }: { children: React.ReactNode; tone: 'emerald' | 'rose' }) {
    const tones = {
        emerald: 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-500/30 dark:bg-emerald-500/10 dark:text-emerald-300',
        rose: 'border-rose-200 bg-rose-50 text-rose-700 dark:border-rose-500/30 dark:bg-rose-500/10 dark:text-rose-300',
    };
    return <span className={`rounded-full border px-3 py-1 text-sm font-medium ${tones[tone]}`}>{children}</span>;
}

function Section({ title, icon, rows, dateLabel }: {
    title: string; icon: React.ReactNode; rows: Row[]; dateLabel: string;
}) {
    return (
        <section className="mb-6 last:mb-0">
            <h3 className="mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                {icon} {title}
            </h3>
            {rows.length === 0 ? (
                <p className="rounded-lg border border-dashed border-border px-4 py-6 text-center text-sm text-muted-foreground">
                    None in this window.
                </p>
            ) : (
                <div className="overflow-hidden rounded-lg border border-border">
                    <table className="w-full text-sm">
                        <thead className="bg-muted/50 text-left text-xs uppercase tracking-wide text-muted-foreground">
                            <tr>
                                <th className="px-3 py-2 font-medium">{dateLabel}</th>
                                <th className="px-3 py-2 font-medium">Location</th>
                                <th className="px-3 py-2 font-medium">Suite</th>
                                <th className="px-3 py-2 font-medium">Tenant</th>
                                <th className="px-3 py-2 font-medium">Phone</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-border">
                            {rows.map((r, i) => (
                                <tr key={i}>
                                    <td className="px-3 py-2 text-muted-foreground">{r.date}</td>
                                    <td className="px-3 py-2 text-foreground">{r.location}</td>
                                    <td className="px-3 py-2 text-foreground">{r.unit}</td>
                                    <td className="px-3 py-2 font-medium text-foreground">{r.tenant}</td>
                                    <td className="px-3 py-2 text-muted-foreground">{r.phone ?? '—'}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}
        </section>
    );
}
