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 { channelClientManager } from '../api/channelClient';

interface ChannelSelectorProps {
  value?: number;
  onChange?: (value: number) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  'data-testid'?: string;
}

export const ChannelSelector: React.FC<ChannelSelectorProps> = ({
  value,
  onChange,
  placeholder = "请选择渠道",
  disabled = false,
  className,
  'data-testid': testId,
}) => {
  const {
    data: channels,
    isLoading,
    isError,
  } = useQuery({
    queryKey: ['channels'],
    queryFn: async () => {
      const client = channelClientManager.get()
      const res = await client.getAllChannels.$get({
        query: {
          skip: 0,
          take: 100
        }
      });
      if (res.status !== 200) throw new Error('获取渠道列表失败');
      return await res.json();
    },
  });

  if (isError) {
    return (
      <div className="text-sm text-destructive">
        加载渠道列表失败
      </div>
    );
  }

  const channelList = channels?.data || [];

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

export default ChannelSelector;