import React from 'react';
import { ShoppingCart } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { EventAddonCatalogItem } from '../../api';

type Props = {
  addons: EventAddonCatalogItem[];
  scope: 'photos' | 'guests' | 'gallery';
  onCheckout: (addonKey: string) => void;
  busy?: boolean;
  t: (key: string, fallback: string) => string;
};

const scopeDefaults: Record<Props['scope'], string[]> = {
  photos: ['extra_photos_500', 'extra_photos_2000'],
  guests: ['extra_guests_50', 'extra_guests_100'],
  gallery: ['extend_gallery_30d', 'extend_gallery_90d'],
};

export function AddonsPicker({ addons, scope, onCheckout, busy, t }: Props) {
  const options = React.useMemo(() => {
    const whitelist = scopeDefaults[scope];
    const filtered = addons.filter((addon) => whitelist.includes(addon.key));
    return filtered.length ? filtered : addons;
  }, [addons, scope]);

  const [selected, setSelected] = React.useState<string | undefined>(() => options[0]?.key);

  React.useEffect(() => {
    setSelected(options[0]?.key);
  }, [options]);

  if (!options.length) {
    return null;
  }

  return (
    <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
      <Select value={selected} onValueChange={(value) => setSelected(value)}>
        <SelectTrigger className="w-full sm:w-64">
          <SelectValue placeholder={t('addons.selectPlaceholder', 'Add-on auswählen')} />
        </SelectTrigger>
        <SelectContent>
          {options.map((addon) => (
            <SelectItem key={addon.key} value={addon.key} disabled={!addon.price_id}>
              {addon.label}
              {!addon.price_id ? ' (kein Preis verknüpft)' : ''}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      <Button
        variant="outline"
        size="sm"
        disabled={!selected || busy || !options.find((a) => a.key === selected)?.price_id}
        onClick={() => selected && onCheckout(selected)}
      >
        <ShoppingCart className="mr-2 h-4 w-4" />
        {t('addons.buyNow', 'Jetzt freischalten')}
      </Button>
    </div>
  );
}
