import { RiCloseLine } from '@remixicon/react';
import { useMemo } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxList,
    ComboboxTrigger,
} from '@/components/ui/combobox';

export type LocationOption = {
    id: number;
    name: string;
    type: 'fixed' | 'mobile_zone';
};

type LocationMultiSelectProps = {
    locations: LocationOption[];
    selectedIds: number[];
    onChange: (ids: number[]) => void;
};

function locationLabel(location: LocationOption): string {
    const typeLabel = location.type === 'fixed' ? 'Fixed' : 'Mobile';

    return `${location.name} (${typeLabel})`;
}

function isSameLocation(
    a: LocationOption | null,
    b: LocationOption | null,
): boolean {
    return a?.id === b?.id;
}

export function LocationMultiSelect({
    locations,
    selectedIds,
    onChange,
}: LocationMultiSelectProps) {
    const selectedLocations = useMemo(
        () => locations.filter((location) => selectedIds.includes(location.id)),
        [locations, selectedIds],
    );

    const removeLocation = (locationId: number) => {
        onChange(selectedIds.filter((id) => id !== locationId));
    };

    if (locations.length === 0) {
        return (
            <p className="text-sm text-muted-foreground">
                No active locations yet.
            </p>
        );
    }

    const triggerLabel =
        selectedLocations.length === 0
            ? 'All locations (no restriction)'
            : `${selectedLocations.length} location${selectedLocations.length === 1 ? '' : 's'} selected`;

    return (
        <div className="flex flex-col gap-2">
            <Combobox
                items={locations}
                itemToStringLabel={locationLabel}
                itemToStringValue={(loc) => String(loc.id)}
                isItemEqualToValue={isSameLocation}
                multiple
                value={selectedLocations}
                onValueChange={(value) =>
                    onChange(value.map((location) => location.id))
                }
            >
                <ComboboxTrigger
                    render={
                        <Button
                            type="button"
                            variant="outline"
                            className="h-auto min-h-9 w-full justify-between px-3 py-2 font-normal"
                        >
                            <span className="truncate text-left">
                                {triggerLabel}
                            </span>
                        </Button>
                    }
                />
                <ComboboxContent>
                    <ComboboxInput
                        showTrigger={false}
                        placeholder="Search locations..."
                    />
                    <ComboboxEmpty>No locations found.</ComboboxEmpty>
                    <ComboboxList>
                        {(location: LocationOption) => (
                            <ComboboxItem key={location.id} value={location}>
                                <span className="flex min-w-0 flex-1 flex-col">
                                    <span className="truncate">
                                        {location.name}
                                    </span>
                                    <span className="text-xs text-muted-foreground">
                                        {location.type === 'fixed'
                                            ? 'Fixed location'
                                            : 'Mobile zone'}
                                    </span>
                                </span>
                            </ComboboxItem>
                        )}
                    </ComboboxList>
                </ComboboxContent>
            </Combobox>

            {selectedLocations.length > 0 ? (
                <div className="flex flex-wrap gap-1.5">
                    {selectedLocations.map((location) => (
                        <Badge
                            key={location.id}
                            variant="secondary"
                            className="gap-1 pr-1"
                        >
                            {location.name}
                            <button
                                type="button"
                                className="rounded-sm opacity-70 transition-opacity hover:opacity-100"
                                aria-label={`Remove ${location.name}`}
                                onClick={() => removeLocation(location.id)}
                            >
                                <RiCloseLine className="size-3.5" />
                            </button>
                        </Badge>
                    ))}
                </div>
            ) : null}
        </div>
    );
}
