import React from 'react';
import { useQuery } from '@tanstack/react-query';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@d8d/shared-ui-components/components/ui/select';
import { advertisementTypeClientManager } from '../api/advertisementTypeClient';

interface AdvertisementTypeSelectorProps {
  value?: number;
  onChange?: (value: number) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  testId?: string;
}

export const AdvertisementTypeSelector: React.FC<AdvertisementTypeSelectorProps> = ({
  value,
  onChange,
  placeholder = "请选择广告类型",
  disabled = false,
  className,
  testId,
}) => {
  const {
    data: advertisementTypes,
    isLoading,
    isError,
  } = useQuery({
    queryKey: ['advertisement-types'],
    queryFn: async () => {
      const client = advertisementTypeClientManager.get()
      const res = await client.index.$get({
        query: {
          page: 1,
          pageSize: 100
        }
      });
      if (res.status !== 200) throw new Error('获取广告类型失败');
      return await res.json();
    },
  });

  if (isError) {
    return (
      <div className="text-sm text-destructive">
        加载广告类型失败
      </div>
    );
  }

  const types = advertisementTypes?.data || [];

  return (
    <Select
      value={value?.toString()}
      onValueChange={(val) => onChange?.(parseInt(val))}
      disabled={disabled || isLoading || types.length === 0}
    >
      <SelectTrigger className={className} data-testid={testId}>
        <SelectValue placeholder={isLoading ? '加载中...' : placeholder} />
      </SelectTrigger>
      <SelectContent>
        {types.map((type) => (
          <SelectItem key={type.id} value={type.id.toString()}>
            {type.name}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
};

export default AdvertisementTypeSelector;