import { useState } from 'react';

import { StoreProduct } from '@medusajs/types';
import { ChevronDown } from 'lucide-react';

import { Card } from '@kit/ui/shadcn/card';
import { Label } from '@kit/ui/shadcn/label';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@kit/ui/shadcn/popover';
import { RadioGroup, RadioGroupItem } from '@kit/ui/shadcn/radio-group';
import { Trans } from '@kit/ui/trans';

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

const ServiceSelector = ({ products }: { products: StoreProduct[] }) => {
  const { selectedService, setSelectedService } = useBooking();
  const [collapsed, setCollapsed] = useState(false);
  const [firstFourProducts] = useState<StoreProduct[]>(products?.slice(0, 4));

  const onServiceSelect = async (productId: StoreProduct['id']) => {
    const product = products.find((p) => p.id === productId);
    setSelectedService(product ?? null);
    setCollapsed(false);
  };

  return (
    <Card className="mb-4 p-4">
      <h5 className="text-semibold mb-2">
        <Trans i18nKey="booking:services" />
      </h5>
      <Popover open={collapsed} onOpenChange={setCollapsed}>
        <div className="flex flex-col">
          <RadioGroup
            defaultValue={selectedService?.id || ''}
            className="mb-2 flex flex-col"
            onValueChange={onServiceSelect}
          >
            {firstFourProducts?.map((product) => (
              <div key={product.id} className="flex items-center gap-2">
                <RadioGroupItem
                  value={product.id}
                  id={product.id}
                  checked={selectedService?.id === product.id}
                />
                <Label htmlFor={product.id}>{product.title}</Label>
              </div>
            ))}
          </RadioGroup>
          {products.length > 4 && (
            <PopoverTrigger asChild>
              <div
                onClick={() => setCollapsed((_) => !_)}
                className="flex cursor-pointer items-center justify-between border-t py-1"
              >
                <span>
                  <Trans i18nKey="booking:showAll" />
                </span>
                <ChevronDown />
              </div>
            </PopoverTrigger>
          )}
        </div>
        <PopoverContent sideOffset={10}>
          <RadioGroup onValueChange={onServiceSelect}>
            {products?.map((product) => (
              <div key={product.id + '-2'} className="flex items-center gap-2">
                <RadioGroupItem
                  value={product.id}
                  id={product.id + '-2'}
                  checked={selectedService?.id === product.id}
                />
                <Label htmlFor={product.id + '-2'}>{product.title}</Label>
              </div>
            ))}
          </RadioGroup>
        </PopoverContent>
      </Popover>
    </Card>
  );
};

export default ServiceSelector;
