import { Select, Spin } from "antd";
import { api } from "@nice/client";
import { useEffect, useState } from "react";
import React from "react";

interface DeviceTypeSelectProps {
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  style?: React.CSSProperties;
  systemTypeId?: string; // 添加系统类型ID参数用于筛选
}

export default function DeviceTypeSelect({
  value,
  onChange,
  placeholder = "选择故障类型",
  disabled = false,
  className,
  style,
  systemTypeId, // 接收系统类型ID
}: DeviceTypeSelectProps) {
  const [options, setOptions] = useState<{ label: string; value: string }[]>(
    []
  );
  const [loading, setLoading] = useState(false);

  // 动态构建查询条件
  const whereCondition = {
    taxonomy: { slug: "device_type" },
    deletedAt: null,
    ...(systemTypeId && { parentId: systemTypeId }), // 只有当systemTypeId存在时才添加parentId条件
  };

  // 获取故障类型，根据选中的系统类型进行筛选
  const { data: deviceTypes } = api.term.findMany.useQuery({
    where: whereCondition,
    orderBy: { order: "asc" },
  });

  // 处理选项数据
  useEffect(() => {
    if (deviceTypes) {
      const options = deviceTypes.map(term => ({
        label: term.name,
        value: term.id,
      }));
      setOptions(options);
    }
  }, [deviceTypes]);

  return (
    <Select
      loading={loading}
      value={value}
      onChange={onChange}
      options={options}
      placeholder={placeholder}
      disabled={disabled}
      className={className}
      style={style}
      showSearch
      filterOption={(input, option) =>
        (option?.label?.toString() || "")
          .toLowerCase()
          .includes(input.toLowerCase())
      }
      allowClear
      notFoundContent={loading ? <Spin size="small" /> : null}
    />
  );
}
