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

interface CompanySelectorProps {
  value?: number;
  onChange?: (value: number) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  'data-testid'?: string;
  platformId?: number; // 可选：按平台ID过滤公司
}

export const CompanySelector: React.FC<CompanySelectorProps> = ({
  value,
  onChange,
  placeholder = "请选择公司",
  disabled = false,
  className,
  'data-testid': testId,
  platformId,
}) => {
  const {
    data: companies,
    isLoading,
    isError,
  } = useQuery({
    queryKey: ['companies', platformId],
    queryFn: async () => {
      const client = companyClientManager.get();

      let res;
      if (platformId) {
        // 按平台过滤公司
        res = await client.getCompaniesByPlatform[':platformId'].$get({
          param: { platformId }
        });
      } else {
        // 获取所有公司（分页，取前100条）
        res = await client.getAllCompanies.$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>
    );
  }

  // 处理响应数据格式
  let companyList: Array<{ id: number; companyName: string; platformId?: number }> = [];

  if (companies) {
    if (platformId) {
      // getCompaniesByPlatform 返回的是数组
      companyList = companies as Array<{ id: number; companyName: string; platformId?: number }>;
    } else {
      // getAllCompanies 返回的是 { data: [], total: number }
      companyList = (companies as { data: Array<{ id: number; companyName: string; platformId?: number }> }).data || [];
    }
  }

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

export default CompanySelector;