/**
 * 添加柜子弹窗组件
 * - 选择组织 -> 项目
 * - 批量输入 IMEI
 */
import { useState } from 'react';
import {
  Modal,
  Form,
  Input,
  Select,
  Message,
} from '@arco-design/web-react';
import {
  projectApi,
  cabinetApi,
  type Organization,
} from '@/api/devices';

interface AddCabinetModalProps {
  visible: boolean;
  orgList: Organization[];
  onCancel: () => void;
  onSuccess: () => void;
}

export default function AddCabinetModal({
  visible,
  orgList,
  onCancel,
  onSuccess,
}: AddCabinetModalProps) {
  const [imeis, setImeis] = useState('');
  const [orgId, setOrgId] = useState<number | undefined>();
  const [projectId, setProjectId] = useState<number | undefined>();
  const [projList, setProjList] = useState<{ id: number; name: string }[]>([]);

  /** 组织变更时加载项目列表 */
  const handleOrgChange = async (newOrgId: number) => {
    setOrgId(newOrgId);
    setProjectId(undefined);
    try {
      const res = await projectApi.list(newOrgId);
      setProjList((res as unknown as { id: number; name: string }[]) || []);
    } catch {
      setProjList([]);
    }
  };

  /** 提交添加柜子 */
  const handleOk = async () => {
    if (!projectId) {
      Message.warning('请选择项目');
      return;
    }
    const imeiList = imeis
      .split('\n')
      .map((s) => s.trim())
      .filter(Boolean);
    if (imeiList.length === 0) {
      Message.warning('请输入至少一个 IMEI');
      return;
    }
    try {
      await cabinetApi.create({ imeis: imeiList, project_id: projectId });
      Message.success(`成功添加 ${imeiList.length} 个柜子`);
      setImeis('');
      setOrgId(undefined);
      setProjectId(undefined);
      setProjList([]);
      onSuccess();
    } catch (e: unknown) {
      const msg = e instanceof Error ? e.message : '添加柜子失败';
      Message.error(msg);
    }
  };

  /** 关闭弹窗时重置状态 */
  const handleCancel = () => {
    setImeis('');
    setOrgId(undefined);
    setProjectId(undefined);
    setProjList([]);
    onCancel();
  };

  return (
    <Modal
      title="添加柜子"
      visible={visible}
      onCancel={handleCancel}
      onOk={handleOk}
      okText="提交"
      cancelText="取消"
      style={{ width: 520 }}
    >
      <Form layout="vertical">
        <Form.Item label="所属组织" required>
          <Select
            placeholder="请选择组织"
            value={orgId}
            onChange={handleOrgChange}
            style={{ width: '100%' }}
          >
            {orgList.map((o) => (
              <Select.Option key={o.id} value={o.id}>{o.name}</Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="所属项目" required>
          <Select
            placeholder="请选择项目"
            value={projectId}
            onChange={(v: number) => setProjectId(v)}
            style={{ width: '100%' }}
            disabled={!orgId}
          >
            {projList.map((p) => (
              <Select.Option key={p.id} value={p.id}>{p.name}</Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="IMEI（一行一个，支持批量）" required>
          <Input.TextArea
            placeholder="每行输入一个15位IMEI"
            value={imeis}
            onChange={setImeis}
            rows={5}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
}
