import React from 'react';
import { useQuery } from '@tanstack/react-query';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/client/components/ui/select';
import { goodsCategoryClient } from '@/client/api';

interface GoodsCategorySelectorProps {
  value?: number;
  onChange?: (value: number) => void;
  placeholder?: string;
  disabled?: boolean;
  level?: 1 | 2 | 3;
  parentId?: number;
}

const GoodsCategorySelector: React.FC<GoodsCategorySelectorProps> = ({
  value,
  onChange,
  placeholder = "请选择商品分类",
  disabled = false,
  level = 1,
  parentId,
}) => {
  const { data: categories, isLoading } = useQuery({
    queryKey: ['goods-categories', level, parentId],
    queryFn: async () => {
      const res = await goodsCategoryClient.$get({
        query: {
          page: 1,
          pageSize: 100,
          filters: JSON.stringify({
            level,
            parentId: parentId || undefined,
          })
        }
      });
      if (res.status !== 200) throw new Error('获取商品分类失败');
      const data = await res.json();
      return data.data;
    },
    enabled: !disabled,
  });

  return (
    <Select
      value={value?.toString()}
      onValueChange={(v) => onChange?.(parseInt(v))}
      disabled={disabled || isLoading}
    >
      <SelectTrigger>
        <SelectValue placeholder={isLoading ? "加载中..." : placeholder} />
      </SelectTrigger>
      <SelectContent>
        {categories?.map((category) => (
          <SelectItem key={category.id} value={category.id.toString()}>
            {category.name}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
};

export default GoodsCategorySelector;