import { Label } from '@medusajs/ui';
import { useTranslation } from 'react-i18next';

import { RadioGroup, RadioGroupItem } from '@kit/ui/radio-group';
import { Card } from '@kit/ui/shadcn/card';
import { Trans } from '@kit/ui/trans';

import { useBooking } from './booking.provider';

const LocationSelector = () => {
  const { t } = useTranslation();
  const { selectedLocationId, setSelectedLocationId, locations } = useBooking();

  const onLocationSelect = (locationId: number | string | null) => {
    if (locationId === 'all') return setSelectedLocationId(null);
    setSelectedLocationId(Number(locationId));
  };

  return (
    <Card className="mb-4 p-4">
      <h5 className="text-semibold mb-2">
        <Trans i18nKey="booking:locations" />
      </h5>
      <div className="flex flex-col">
        <RadioGroup
          className="mb-2 flex flex-col"
          onValueChange={(val) => onLocationSelect(val)}
        >
          <div className="flex items-center gap-2">
            <RadioGroupItem
              value={'all'}
              id={'all'}
              checked={selectedLocationId === null}
            />
            <Label htmlFor={'all'}>{t('booking:showAllLocations')}</Label>
          </div>
          {locations?.map((location) => (
            <div key={location.sync_id} className="flex items-center gap-2">
              <RadioGroupItem
                value={location.sync_id.toString()}
                id={location.sync_id.toString()}
                checked={selectedLocationId === location.sync_id}
              />
              <Label htmlFor={location.sync_id.toString()}>
                {location.name}
              </Label>
            </div>
          ))}
        </RadioGroup>
      </div>
    </Card>
  );
};

export default LocationSelector;
