import { useState } from 'react';
import { DayPicker } from 'react-day-picker';
import type { DateRange } from 'react-day-picker';
import { fr } from 'date-fns/locale';
import {
    format,
    startOfWeek, endOfWeek,
    startOfMonth, endOfMonth,
    startOfYear, endOfYear,
    subWeeks, subMonths, subYears,
} from 'date-fns';
import * as Popover from '@radix-ui/react-popover';
import { Calendar as CalIcon } from 'lucide-react';
import 'react-day-picker/style.css';

export interface DateRangeValue {
    from: Date;
    to: Date;
}

interface Props {
    value: DateRangeValue;
    onChange: (range: DateRangeValue) => void;
}

function makeShortcuts(now: Date) {
    return [
        { label: "Aujourd'hui",      from: now,                                             to: now },
        { label: 'Cette semaine',    from: startOfWeek(now, { weekStartsOn: 1 }),           to: endOfWeek(now,             { weekStartsOn: 1 }) },
        { label: 'Semaine dernière', from: startOfWeek(subWeeks(now, 1), { weekStartsOn: 1 }), to: endOfWeek(subWeeks(now, 1), { weekStartsOn: 1 }) },
        { label: 'Ce mois-ci',       from: startOfMonth(now),                               to: endOfMonth(now) },
        { label: 'Mois dernier',     from: startOfMonth(subMonths(now, 1)),                 to: endOfMonth(subMonths(now, 1)) },
        { label: 'Cette année',      from: startOfYear(now),                                to: endOfYear(now) },
        { label: 'Année dernière',   from: startOfYear(subYears(now, 1)),                   to: endOfYear(subYears(now, 1)) },
        { label: 'Depuis le début',  from: new Date(2000, 0, 1),                            to: now },
    ];
}

const FMT = 'd MMM yyyy';
const PRIMARY   = '#117176';
const PRIMARY_H = '#0c4f54';

export default function DateRangePicker({ value, onChange }: Props) {
    const [open,    setOpen]    = useState(false);
    const [pending, setPending] = useState<DateRange>({ from: value.from, to: value.to });

    const handleOpenChange = (o: boolean) => {
        if (o) setPending({ from: value.from, to: value.to });
        setOpen(o);
    };

    const shortcuts = makeShortcuts(new Date());

    const isActive = (s: { from: Date; to: Date }) =>
        pending?.from && pending?.to &&
        format(pending.from, 'yyyy-MM-dd') === format(s.from, 'yyyy-MM-dd') &&
        format(pending.to,   'yyyy-MM-dd') === format(s.to,   'yyyy-MM-dd');

    const apply = () => {
        if (pending?.from && pending?.to) {
            onChange({ from: pending.from, to: pending.to });
        }
        setOpen(false);
    };

    const triggerLabel = `${format(value.from, FMT, { locale: fr })} – ${format(value.to, FMT, { locale: fr })}`;

    return (
        <Popover.Root open={open} onOpenChange={handleOpenChange}>
            <Popover.Trigger asChild>
                <button className="flex items-center gap-2 w-full min-h-[38px] bg-white/[0.06] border border-white/15 rounded-lg text-sm text-white/80 px-3 py-2 hover:border-white/30 focus:outline-none focus:border-white/40 focus:ring-2 focus:ring-white/10 transition-colors text-left">
                    <CalIcon size={14} className="text-white/40 flex-shrink-0" />
                    <span className="flex-1 truncate">{triggerLabel}</span>
                </button>
            </Popover.Trigger>

            <Popover.Portal>
                <Popover.Content
                    side="left"
                    align="start"
                    sideOffset={8}
                    className="z-50 bg-white rounded-2xl shadow-2xl border border-gray-200 overflow-hidden"
                >
                    <div className="flex divide-x divide-gray-100">

                        {/* ── Raccourcis ──────────────────────────────── */}
                        <div className="flex flex-col gap-0.5 py-3 px-2 min-w-[156px]">
                            {shortcuts.map(s => (
                                <button
                                    key={s.label}
                                    onClick={() => setPending({ from: s.from, to: s.to })}
                                    className={`text-left px-3 py-1.5 rounded-lg text-sm transition-colors ${
                                        isActive(s)
                                            ? 'bg-gray-100 text-gray-900 font-semibold'
                                            : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'
                                    }`}
                                >
                                    {s.label}
                                </button>
                            ))}
                        </div>

                        {/* ── Calendrier ──────────────────────────────── */}
                        <div className="flex flex-col">
                            <div className="rdp-aqua">
                                <style>{`
                                    .rdp-aqua .rdp-root {
                                        --rdp-accent-color:                    #117176;
                                        --rdp-accent-background-color:         #f0f0f0;
                                        --rdp-today-color:                     #117176;
                                        --rdp-range_middle-background-color:   #f0f0f0;
                                        --rdp-range_start-date-background-color: #117176;
                                        --rdp-range_end-date-background-color:   #117176;
                                        --rdp-range_start-color:               white;
                                        --rdp-range_end-color:                 white;
                                    }
                                    .rdp-aqua .rdp-day_button { font-size: 0.8125rem; font-weight: 300; }
                                    .rdp-aqua .rdp-selected   { font-size: inherit; font-weight: 400; }
                                    .rdp-aqua .rdp-range_middle .rdp-day_button { color: #374151; }
                                    .rdp-aqua .rdp-today:not(.rdp-outside) { color: #117176; }
                                `}</style>
                                <DayPicker
                                    mode="range"
                                    selected={pending}
                                    onSelect={r => r && setPending(r)}
                                    locale={fr}
                                    numberOfMonths={1}
                                    showOutsideDays
                                />
                            </div>

                            {/* Footer */}
                            <div className="flex items-center gap-2 px-4 pb-4 pt-2 border-t border-gray-100">
                                <span className="flex-1 text-xs text-gray-400 tabular-nums">
                                    {pending?.from ? format(pending.from, FMT, { locale: fr }) : '—'}
                                    {' – '}
                                    {pending?.to ? format(pending.to, FMT, { locale: fr }) : '—'}
                                </span>
                                <button
                                    onClick={() => setOpen(false)}
                                    className="px-3.5 py-1.5 rounded-full text-xs font-medium border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors"
                                >
                                    Annuler
                                </button>
                                <button
                                    onClick={apply}
                                    disabled={!pending?.from || !pending?.to}
                                    style={{ background: PRIMARY }}
                                    className="px-3.5 py-1.5 rounded-full text-xs font-medium text-white transition-colors disabled:opacity-40"
                                    onMouseEnter={e => { (e.currentTarget as HTMLButtonElement).style.background = PRIMARY_H; }}
                                    onMouseLeave={e => { (e.currentTarget as HTMLButtonElement).style.background = PRIMARY; }}
                                >
                                    Appliquer
                                </button>
                            </div>
                        </div>
                    </div>
                </Popover.Content>
            </Popover.Portal>
        </Popover.Root>
    );
}
