import { DateRangePicker } from '@/components/date-range';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Select, SelectContent, SelectItem, SelectTrigger } from '@/components/ui/select';
import { useTranslation } from '@/hooks/use-translation';
import { cn } from '@/lib/utils';
import type {
    CompareMode,
    DateBasis,
    FilterOption,
    PaymentStatus,
    RevenueFilterState,
    RevenueOptions,
    ServiceFeeFilter,
} from '@/types/revenu';
import {
    addMonths,
    differenceInCalendarDays,
    differenceInCalendarMonths,
    endOfMonth,
    endOfYear,
    format,
    isSameDay,
    parseISO,
    startOfMonth,
    startOfYear,
    subDays,
    subMonths,
    subYears,
} from 'date-fns';
import { ChevronDown, RotateCcw, SlidersHorizontal, X } from 'lucide-react';
import * as React from 'react';

const ISO = 'yyyy-MM-dd';

/** Valeur « aucun choix » des Select Radix : la chaîne vide y est interdite. */
const ANY = '__any__';

/**
 * Sélection active : blanc sur le vert foncé de la marque.
 *
 * Le thème global apparie `--secondary` (vert menthe #31b08f) à un
 * `--secondary-foreground` quasi noir : tout `variant="secondary"` rend du noir
 * sur vert, terne. Mais poser du blanc sur ce même menthe ne vaut pas mieux —
 * 2,6:1, sous le seuil AA. On prend donc `--primary` (#1b4e4d), le vert foncé du
 * menu : blanc dessus, c'est ~12:1, et les deux jetons existent aussi en thème
 * sombre. Aucun jeton partagé par le reste de l'ERP n'est modifié.
 */
const ON_BRAND = 'bg-primary text-primary-foreground';

/** État « ce filtre porte une valeur » : teinte légère, texte foncé, lisible. */
const TRIGGER_ACTIVE = 'border-secondary bg-secondary/10';

const TRIGGER_BASE = 'h-9 gap-1.5 rounded-full border-input bg-background px-3 font-normal shadow-none hover:bg-muted';

export const EMPTY_FILTERS: Omit<RevenueFilterState, 'dateRange'> = {
    dateBasis: 'check_in',
    coHost: '',
    properties: [],
    channels: [],
    locations: [],
    types: [],
    owners: [],
    statuses: [],
    paymentStatus: '',
    serviceFee: '',
    guestCountries: [],
    guestsMin: '',
    guestsMax: '',
    compareMode: '',
    compareFrom: '',
    compareTo: '',
    // Deux cartes par défaut : celles que l'écran affichait avant d'être
    // configurable, pour que rien ne change tant qu'on n'y touche pas.
    charts: [
        { metric: 'commission', type: 'line' },
        { metric: 'nights', type: 'line' },
    ],
};

interface QuickRange {
    key: string;
    from: string;
    to: string;
}

function buildQuickRanges(now: Date): QuickRange[] {
    return [
        { key: 'this_month', from: format(startOfMonth(now), ISO), to: format(endOfMonth(now), ISO) },
        { key: 'last_month', from: format(startOfMonth(subMonths(now, 1)), ISO), to: format(endOfMonth(subMonths(now, 1)), ISO) },
        { key: 'last_30_days', from: format(subDays(now, 29), ISO), to: format(now, ISO) },
        // L'année en cours s'arrête AUJOURD'HUI : prolonger jusqu'au 31/12 ferait
        // traîner des mois vides à droite de chaque courbe et diluerait la
        // comparaison (8 mois de réel face à 12 mois de référence).
        { key: 'this_year', from: format(startOfYear(now), ISO), to: format(now, ISO) },
        { key: 'last_year', from: format(startOfYear(subYears(now, 1)), ISO), to: format(endOfYear(subYears(now, 1)), ISO) },
    ];
}

/** Pastille de comptage : blanc sur vert, jamais le noir-sur-vert du thème. */
function CountBadge({ count }: { count: number }) {
    return <span className={cn('inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1 text-xs tabular-nums', ON_BRAND)}>{count}</span>;
}

/**
 * Sélecteur multi-valeurs compact, indexé sur les identifiants et non sur les
 * libellés : deux logements peuvent porter le même nom commercial, seul l'uid
 * les distingue.
 */
function FacetSelect({
    label,
    options,
    selected,
    onChange,
    className,
}: {
    label: string;
    options: FilterOption[];
    selected: string[];
    onChange: (next: string[]) => void;
    className?: string;
}) {
    const { t } = useTranslation();

    const toggle = (id: string) => {
        onChange(selected.includes(id) ? selected.filter((value) => value !== id) : [...selected, id]);
    };

    return (
        <Popover>
            <PopoverTrigger asChild>
                <Button
                    variant="outline"
                    disabled={options.length === 0}
                    className={cn(TRIGGER_BASE, selected.length > 0 && TRIGGER_ACTIVE, className)}
                >
                    <span className="truncate">{label}</span>
                    {selected.length > 0 && <CountBadge count={selected.length} />}
                    <ChevronDown className="size-3.5 shrink-0 opacity-50" />
                </Button>
            </PopoverTrigger>
            <PopoverContent align="start" className="w-72 p-0">
                <Command>
                    <CommandInput placeholder={label} />
                    <CommandList>
                        <CommandEmpty>{t('revenu', 'no_results')}</CommandEmpty>
                        <CommandGroup>
                            {options.map((option) => (
                                <CommandItem key={option.id} value={option.name} onSelect={() => toggle(option.id)} className="gap-2">
                                    <Checkbox checked={selected.includes(option.id)} className="pointer-events-none" />
                                    <span className="min-w-0 flex-1 truncate">{option.name}</span>
                                    {option.count !== undefined && (
                                        <span className="text-muted-foreground shrink-0 text-xs tabular-nums">{option.count}</span>
                                    )}
                                </CommandItem>
                            ))}
                        </CommandGroup>
                    </CommandList>
                </Command>
            </PopoverContent>
        </Popover>
    );
}

/**
 * Select à valeur unique. Le libellé du filtre reste visible une fois une valeur
 * choisie : un déclencheur qui n'affiche que « Partiel » ne dit pas de quoi il
 * parle.
 */
function SingleSelect({
    label,
    value,
    onChange,
    anyLabel,
    options,
    className,
}: {
    label: string;
    value: string;
    onChange: (next: string) => void;
    anyLabel: string;
    options: FilterOption[];
    className?: string;
}) {
    const selected = options.find((option) => option.id === value);

    return (
        <Select value={value === '' ? ANY : value} onValueChange={(next) => onChange(next === ANY ? '' : next)}>
            <SelectTrigger className={cn(TRIGGER_BASE, 'w-auto', value !== '' && TRIGGER_ACTIVE, className)}>
                {selected ? (
                    <span className="truncate">
                        <span className="text-muted-foreground">{label} · </span>
                        {selected.name}
                    </span>
                ) : (
                    <span className="text-muted-foreground truncate">{label}</span>
                )}
            </SelectTrigger>
            <SelectContent>
                <SelectItem value={ANY}>{anyLabel}</SelectItem>
                {options.map((option) => (
                    <SelectItem key={option.id} value={option.id}>
                        {option.name}
                    </SelectItem>
                ))}
            </SelectContent>
        </Select>
    );
}

interface FilterBarProps {
    value: RevenueFilterState;
    onChange: (next: RevenueFilterState) => void;
    onReset: () => void;
    options: RevenueOptions;
    isAdmin: boolean;
}

export function RevenueFilterBar({ value, onChange, onReset, options, isAdmin }: FilterBarProps) {
    const { t } = useTranslation();
    const quickRanges = React.useMemo(() => buildQuickRanges(new Date()), []);

    const patch = <K extends keyof RevenueFilterState>(key: K, next: RevenueFilterState[K]) => {
        onChange({ ...value, [key]: next });
    };

    const statusOptions: FilterOption[] = [
        { id: '1', name: t('revenu', 'status_confirmed') },
        { id: '2', name: t('revenu', 'status_cancelled') },
        { id: '3', name: t('revenu', 'status_pending') },
    ];

    const paymentOptions: FilterOption[] = [
        { id: 'paid', name: t('revenu', 'payment_paid') },
        { id: 'partial', name: t('revenu', 'payment_partial') },
        { id: 'unpaid', name: t('revenu', 'payment_unpaid') },
    ];

    const serviceFeeOptions: FilterOption[] = [
        { id: 'oui', name: t('revenu', 'service_fee_yes') },
        { id: 'non', name: t('revenu', 'service_fee_no') },
    ];

    const dateBasisOptions: FilterOption[] = [
        { id: 'check_in', name: t('revenu', 'date_basis_check_in') },
        { id: 'check_out', name: t('revenu', 'date_basis_check_out') },
        { id: 'created_date', name: t('revenu', 'date_basis_booked') },
    ];

    const nameOf = (list: FilterOption[], id: string) => list.find((option) => option.id === id)?.name ?? id;

    /**
     * Les puces rendent le périmètre lisible d'un coup d'œil : sans elles, un
     * filtre replié dans « Plus de filtres » rétrécit les chiffres en silence.
     */
    const chips: { key: string; label: string; onRemove: () => void }[] = [];

    const pushFacet = (facet: keyof RevenueFilterState, list: FilterOption[]) => {
        (value[facet] as string[]).forEach((id) => {
            chips.push({
                key: `${facet}-${id}`,
                label: nameOf(list, id),
                onRemove: () =>
                    patch(
                        facet,
                        (value[facet] as string[]).filter((current) => current !== id) as RevenueFilterState[typeof facet],
                    ),
            });
        });
    };

    pushFacet('properties', options.properties);
    pushFacet('channels', options.channels);
    pushFacet('locations', options.locations);
    pushFacet('types', options.types);
    pushFacet('owners', options.owners);
    pushFacet('guestCountries', options.guestCountries);
    pushFacet('statuses', statusOptions);

    if (value.paymentStatus !== '') {
        chips.push({
            key: 'paymentStatus',
            label: nameOf(paymentOptions, value.paymentStatus),
            onRemove: () => patch('paymentStatus', '' as PaymentStatus),
        });
    }

    if (value.serviceFee !== '') {
        chips.push({
            key: 'serviceFee',
            label: nameOf(serviceFeeOptions, value.serviceFee),
            onRemove: () => patch('serviceFee', '' as ServiceFeeFilter),
        });
    }

    if (value.dateBasis !== 'check_in') {
        chips.push({
            key: 'dateBasis',
            label: nameOf(dateBasisOptions, value.dateBasis),
            onRemove: () => patch('dateBasis', 'check_in'),
        });
    }

    if (value.guestsMin !== '' || value.guestsMax !== '') {
        chips.push({
            key: 'guests',
            label: `${t('revenu', 'guests')} ${value.guestsMin || '0'} – ${value.guestsMax || '∞'}`,
            onRemove: () => onChange({ ...value, guestsMin: '', guestsMax: '' }),
        });
    }

    if (value.coHost === 'all') {
        chips.push({ key: 'coHost', label: t('revenu', 'all_franchises'), onRemove: () => patch('coHost', '') });
    } else if (value.coHost !== '') {
        chips.push({ key: 'coHost', label: nameOf(options.coHosts, value.coHost), onRemove: () => patch('coHost', '') });
    }

    const activeQuickRange = quickRanges.find((range) => range.from === value.dateRange.from && range.to === value.dateRange.to);

    return (
        <div className="bg-background/95 supports-[backdrop-filter]:bg-background/85 sticky top-0 z-20 border-b shadow-sm backdrop-blur">
            <div className="flex flex-wrap items-center gap-x-2 gap-y-2 px-3 py-2.5 sm:px-4 lg:px-6">
                {/* Raccourcis de période : contrôle segmenté, pastille verte pour l'actif. */}
                <div className="bg-muted/70 flex flex-wrap items-center gap-0.5 rounded-full p-0.5">
                    {quickRanges.map((range) => (
                        <button
                            key={range.key}
                            type="button"
                            onClick={() => patch('dateRange', { from: range.from, to: range.to })}
                            className={cn(
                                'rounded-full px-3 py-1.5 text-sm whitespace-nowrap transition-colors',
                                activeQuickRange?.key === range.key
                                    ? cn(ON_BRAND, 'shadow-sm')
                                    : 'text-muted-foreground hover:text-foreground hover:bg-background/70',
                            )}
                        >
                            {t('revenu', range.key)}
                        </button>
                    ))}
                </div>

                <DateRangePicker date={value.dateRange} setDate={(next: RevenueFilterState['dateRange']) => patch('dateRange', next)} />

                <span className="bg-border mx-1 hidden h-6 w-px lg:block" />

                <FacetSelect
                    label={t('revenu', 'properties')}
                    options={options.properties}
                    selected={value.properties}
                    onChange={(next) => patch('properties', next)}
                />

                <FacetSelect
                    label={t('revenu', 'channel')}
                    options={options.channels}
                    selected={value.channels}
                    onChange={(next) => patch('channels', next)}
                />

                <SingleSelect
                    label={t('revenu', 'payment_status')}
                    value={value.paymentStatus}
                    onChange={(next) => patch('paymentStatus', next as PaymentStatus)}
                    anyLabel={t('revenu', 'any')}
                    options={paymentOptions}
                />

                <MoreFiltersPopover
                    value={value}
                    onChange={onChange}
                    options={options}
                    statusOptions={statusOptions}
                    serviceFeeOptions={serviceFeeOptions}
                    dateBasisOptions={dateBasisOptions}
                />

                <div className="ml-auto flex items-center gap-2">
                    <ComparePopover value={value} onChange={onChange} />

                    {isAdmin && (
                        <SingleSelect
                            label={t('revenu', 'franchise')}
                            value={value.coHost}
                            onChange={(next) => patch('coHost', next)}
                            anyLabel={t('revenu', 'headquarters')}
                            options={[{ id: 'all', name: t('revenu', 'all_franchises') }, ...options.coHosts]}
                            className="max-w-[220px]"
                        />
                    )}
                </div>
            </div>

            {chips.length > 0 && (
                <div className="flex flex-wrap items-center gap-1.5 border-t px-3 py-2 sm:px-4 lg:px-6">
                    {chips.map((chip) => (
                        <span
                            key={chip.key}
                            className={cn('inline-flex items-center gap-1 rounded-full py-1 pr-1 pl-2.5 text-xs', ON_BRAND)}
                        >
                            <span className="max-w-[240px] truncate">{chip.label}</span>
                            <button
                                type="button"
                                aria-label={`${t('revenu', 'remove_filter')} : ${chip.label}`}
                                onClick={chip.onRemove}
                                className="rounded-full p-0.5 opacity-70 transition-colors hover:bg-white/25 hover:opacity-100"
                            >
                                <X className="size-3" />
                            </button>
                        </span>
                    ))}
                    <Button variant="ghost" onClick={onReset} className="text-muted-foreground hover:text-foreground h-7 gap-1.5 rounded-full px-2.5 text-xs">
                        <RotateCcw className="size-3" />
                        {t('revenu', 'reset')}
                    </Button>
                </div>
            )}
        </div>
    );
}


/**
 * Choix de la période de référence.
 *
 * « Période précédente » seule ne suffit pas en location saisonnière : août ne
 * se compare pas à juillet mais à août de l'an dernier. Les trois lectures sont
 * offertes, dates exactes affichées, plus une plage libre.
 */
function ComparePopover({ value, onChange }: { value: RevenueFilterState; onChange: (next: RevenueFilterState) => void }) {
    const { t, locale } = useTranslation();
    const active = value.compareMode !== '';
    const dateFormat = locale === 'fr' ? 'dd/MM/yyyy' : 'MM/dd/yyyy';

    // Aperçu des bornes AVANT de choisir : on refait côté client le calcul du
    // serveur, sinon l'utilisateur choisit à l'aveugle.
    const from = value.dateRange.from ? parseISO(value.dateRange.from) : null;
    const to = value.dateRange.to ? parseISO(value.dateRange.to) : null;

    const preview = (mode: CompareMode): string => {
        if (!from || !to) {
            return '';
        }

        if (mode === 'year') {
            return `${format(subYears(from, 1), dateFormat)} – ${format(subYears(to, 1), dateFormat)}`;
        }

        // Mois civils entiers ⇒ recul en mois ; sinon décalage en jours.
        const wholeMonths = isSameDay(from, startOfMonth(from)) && isSameDay(to, endOfMonth(to));

        if (wholeMonths) {
            const months = differenceInCalendarMonths(to, from) + 1;
            const previousFrom = startOfMonth(subMonths(from, months));

            return `${format(previousFrom, dateFormat)} – ${format(endOfMonth(addMonths(previousFrom, months - 1)), dateFormat)}`;
        }

        const days = differenceInCalendarDays(to, from) + 1;
        const previousTo = subDays(from, 1);

        return `${format(subDays(previousTo, days - 1), dateFormat)} – ${format(previousTo, dateFormat)}`;
    };

    const choose = (mode: CompareMode) => onChange({ ...value, compareMode: mode });

    const modes: { id: Exclude<CompareMode, ''>; label: string }[] = [
        { id: 'previous', label: t('revenu', 'compare_previous_period') },
        { id: 'year', label: t('revenu', 'compare_last_year') },
        { id: 'custom', label: t('revenu', 'compare_custom') },
    ];

    return (
        <Popover>
            <PopoverTrigger asChild>
                <Button
                    variant="outline"
                    className={cn(TRIGGER_BASE, active && cn(ON_BRAND, 'border-primary hover:bg-primary/90 hover:text-primary-foreground'))}
                >
                    {t('revenu', 'compare_short')}
                    <ChevronDown className="size-3.5 shrink-0 opacity-50" />
                </Button>
            </PopoverTrigger>
            <PopoverContent align="end" className="w-80 space-y-1 p-2">
                <button
                    type="button"
                    onClick={() => choose('')}
                    className={cn(
                        'flex w-full items-center justify-between rounded-md px-2 py-1.5 text-left text-sm transition-colors',
                        value.compareMode === '' ? 'bg-muted font-medium' : 'hover:bg-muted',
                    )}
                >
                    {t('revenu', 'compare_off')}
                </button>

                {modes.map((mode) => (
                    <button
                        key={mode.id}
                        type="button"
                        onClick={() => choose(mode.id)}
                        className={cn(
                            'w-full rounded-md px-2 py-1.5 text-left text-sm transition-colors',
                            value.compareMode === mode.id ? 'bg-muted font-medium' : 'hover:bg-muted',
                        )}
                    >
                        <span className="block">{mode.label}</span>
                        {mode.id !== 'custom' && <span className="text-muted-foreground block text-xs tabular-nums">{preview(mode.id)}</span>}
                    </button>
                ))}

                {value.compareMode === 'custom' && (
                    <div className="space-y-1.5 border-t pt-2">
                        <Label className="text-muted-foreground text-xs">{t('revenu', 'compare_custom')}</Label>
                        <div className="flex items-center gap-2">
                            <Input
                                type="date"
                                value={value.compareFrom}
                                onChange={(event) => onChange({ ...value, compareFrom: event.target.value })}
                            />
                            <span className="text-muted-foreground text-sm">–</span>
                            <Input
                                type="date"
                                value={value.compareTo}
                                onChange={(event) => onChange({ ...value, compareTo: event.target.value })}
                            />
                        </div>
                        {/* Sans les deux bornes, le serveur retombe sur la période précédente. */}
                        {(value.compareFrom === '' || value.compareTo === '') && (
                            <p className="text-muted-foreground text-xs">{t('revenu', 'compare_custom_hint')}</p>
                        )}
                    </div>
                )}
            </PopoverContent>
        </Popover>
    );
}
function MoreFiltersPopover({
    value,
    onChange,
    options,
    statusOptions,
    serviceFeeOptions,
    dateBasisOptions,
}: {
    value: RevenueFilterState;
    onChange: (next: RevenueFilterState) => void;
    options: RevenueOptions;
    statusOptions: FilterOption[];
    serviceFeeOptions: FilterOption[];
    dateBasisOptions: FilterOption[];
}) {
    const { t } = useTranslation();

    const patch = <K extends keyof RevenueFilterState>(key: K, next: RevenueFilterState[K]) => {
        onChange({ ...value, [key]: next });
    };

    const advancedCount =
        value.locations.length +
        value.types.length +
        value.owners.length +
        value.guestCountries.length +
        value.statuses.length +
        (value.serviceFee !== '' ? 1 : 0) +
        (value.dateBasis !== 'check_in' ? 1 : 0) +
        (value.guestsMin !== '' || value.guestsMax !== '' ? 1 : 0);

    return (
        <Popover>
            <PopoverTrigger asChild>
                <Button variant="outline" className={cn(TRIGGER_BASE, advancedCount > 0 && TRIGGER_ACTIVE)}>
                    <SlidersHorizontal className="size-3.5 opacity-70" />
                    {t('revenu', 'more_filters')}
                    {advancedCount > 0 && <CountBadge count={advancedCount} />}
                </Button>
            </PopoverTrigger>
            <PopoverContent align="end" className="max-h-[70vh] w-[min(34rem,calc(100vw-2rem))] overflow-y-auto">
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                    <div className="space-y-1.5">
                        <Label className="text-muted-foreground text-xs">{t('revenu', 'date_basis')}</Label>
                        <SingleSelect
                            label={t('revenu', 'date_basis')}
                            value={value.dateBasis === 'check_in' ? '' : value.dateBasis}
                            onChange={(next) => patch('dateBasis', (next === '' ? 'check_in' : next) as DateBasis)}
                            anyLabel={t('revenu', 'date_basis_check_in')}
                            options={dateBasisOptions.filter((option) => option.id !== 'check_in')}
                            className="w-full"
                        />
                    </div>

                    <div className="space-y-1.5">
                        <Label className="text-muted-foreground text-xs">{t('revenu', 'service_fee')}</Label>
                        <SingleSelect
                            label={t('revenu', 'service_fee')}
                            value={value.serviceFee}
                            onChange={(next) => patch('serviceFee', next as ServiceFeeFilter)}
                            anyLabel={t('revenu', 'any')}
                            options={serviceFeeOptions}
                            className="w-full"
                        />
                    </div>

                    <div className="space-y-1.5">
                        <Label className="text-muted-foreground text-xs">{t('revenu', 'location')}</Label>
                        <FacetSelect
                            label={t('revenu', 'location')}
                            options={options.locations}
                            selected={value.locations}
                            onChange={(next) => patch('locations', next)}
                            className="w-full justify-between"
                        />
                    </div>

                    <div className="space-y-1.5">
                        <Label className="text-muted-foreground text-xs">{t('revenu', 'property_type')}</Label>
                        <FacetSelect
                            label={t('revenu', 'property_type')}
                            options={options.types}
                            selected={value.types}
                            onChange={(next) => patch('types', next)}
                            className="w-full justify-between"
                        />
                    </div>

                    <div className="space-y-1.5">
                        <Label className="text-muted-foreground text-xs">{t('revenu', 'owner')}</Label>
                        <FacetSelect
                            label={t('revenu', 'owner')}
                            options={options.owners}
                            selected={value.owners}
                            onChange={(next) => patch('owners', next)}
                            className="w-full justify-between"
                        />
                    </div>

                    <div className="space-y-1.5">
                        <Label className="text-muted-foreground text-xs">{t('revenu', 'reservation_status')}</Label>
                        <FacetSelect
                            label={t('revenu', 'reservation_status')}
                            options={statusOptions}
                            selected={value.statuses}
                            onChange={(next) => patch('statuses', next)}
                            className="w-full justify-between"
                        />
                    </div>

                    <div className="space-y-1.5">
                        <Label className="text-muted-foreground text-xs">{t('revenu', 'guest_country')}</Label>
                        <FacetSelect
                            label={t('revenu', 'guest_country')}
                            options={options.guestCountries}
                            selected={value.guestCountries}
                            onChange={(next) => patch('guestCountries', next)}
                            className="w-full justify-between"
                        />
                    </div>

                    <div className="space-y-1.5">
                        <Label className="text-muted-foreground text-xs">{t('revenu', 'guests')}</Label>
                        <div className="flex items-center gap-2">
                            <Input
                                type="number"
                                min={0}
                                placeholder={t('revenu', 'guests_min')}
                                value={value.guestsMin}
                                onChange={(event) => onChange({ ...value, guestsMin: event.target.value })}
                            />
                            <span className="text-muted-foreground text-sm">–</span>
                            <Input
                                type="number"
                                min={0}
                                placeholder={t('revenu', 'guests_max')}
                                value={value.guestsMax}
                                onChange={(event) => onChange({ ...value, guestsMax: event.target.value })}
                            />
                        </div>
                    </div>
                </div>
            </PopoverContent>
        </Popover>
    );
}
