import React, { useState, useImperativeHandle, forwardRef } from 'react';
import { Modal, Form, Input, Select, Spin } from 'antd';
import { deptApi, DeptVO } from '../../api/dept';
import { userApi } from '../../api/user';
import { UserVO } from '../../types';
import { toast } from 'sonner';
import { DICT_TYPE, getIntDictOptions } from '../../utils/dict';
import { handleTree, TreeNode } from '../../utils/tree';
import { useTranslation } from 'react-i18next';

interface DeptFormProps {
  onSuccess?: () => void;
}

export interface DeptFormRef {
  open: (type: string, id?: number, parentId?: number) => void;
}

const DeptForm = forwardRef<DeptFormRef, DeptFormProps>(({ onSuccess }, ref) => {
  const { t } = useTranslation();
  const [dialogVisible, setDialogVisible] = useState(false);
  const [dialogTitle, setDialogTitle] = useState('');
  const [formLoading, setFormLoading] = useState(false);
  const [formType, setFormType] = useState<'create' | 'update'>('create');
  const [currentId, setCurrentId] = useState<number | undefined>();
  const [form] = Form.useForm();
  const [deptTree, setDeptTree] = useState<TreeNode[]>([]);
  const [userList, setUserList] = useState<UserVO[]>([]);
  // 获取最新的字典选项（每次调用都从缓存中获取最新数据）
  const getStatusOptions = () => getIntDictOptions(DICT_TYPE.COMMON_STATUS);

  // 打开弹窗
  const open = async (type: string, id?: number, parentId?: number) => {
    setDialogVisible(true);
    setDialogTitle(type === 'create' ? t('common.addNew') : t('common.edit'));
    setFormType(type as 'create' | 'update');
    setCurrentId(id);
    form.resetFields();

    // 加载用户列表
    try {
      const users = await userApi.getSimpleUserList();
      setUserList(users);
    } catch (error) {
      console.error('加载用户列表失败:', error);
    }

    // 加载部门树
    try {
      const deptList = await deptApi.getSimpleDeptList();
      // 过滤掉没有 id 的项，并确保 id 存在
      const validDeptList = deptList.filter((dept): dept is DeptVO & { id: number } => !!dept.id);
      const treeData = handleTree(validDeptList);
      // 添加顶级部门选项
      const rootDept: TreeNode = { id: 0, name: t('form.topDept'), children: treeData };
      setDeptTree([rootDept]);
    } catch (error) {
      console.error('加载部门树失败:', error);
    }

    // 修改时，设置数据
    if (id) {
      setFormLoading(true);
      try {
        const deptData = await deptApi.getDept(id);
        form.setFieldsValue({
          name: deptData.name,
          parentId: deptData.parentId ?? 0,
          sort: deptData.sort ?? 0,
          leaderUserId: deptData.leaderUserId,
          phone: deptData.phone || '',
          email: deptData.email || '',
          status: deptData.status ?? (getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1),
        });
      } catch (error) {
        toast.error(error.message || t('common.error'));
      } finally {
        setFormLoading(false);
      }
    } else {
      // 新增时，设置默认父级部门
      form.setFieldsValue({
        name: '',
        parentId: parentId ?? 0,
        sort: 0,
        leaderUserId: undefined,
        phone: '',
        email: '',
        status: getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1,
      });
    }
  };

  useImperativeHandle(ref, () => ({
    open,
  }));

  // 提交表单
  const submitForm = async () => {
    try {
      const values = await form.validateFields();
      setFormLoading(true);
      
      const data: DeptVO = {
        ...values,
        parentId: values.parentId ?? 0,
        sort: values.sort ?? 0,
        status: values.status ?? (getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1),
      };

      if (formType === 'create') {
        await deptApi.createDept(data);
        toast.success(t('common.addSuccess'));
      } else {
        if (currentId) {
          data.id = currentId;
        }
        await deptApi.updateDept(data);
        toast.success(t('common.updateSuccess'));
      }
      setDialogVisible(false);
      onSuccess?.();
    } catch (error: any) {
      if (error.errorFields) {
        // 表单验证错误
        return;
      }
      toast.error(error.message || t('common.saveFailed'));
    } finally {
      setFormLoading(false);
    }
  };

  // 递归构建部门树选项
  const buildDeptOptions = (nodes: TreeNode[], level: number = 0): { label: string; value: number }[] => {
    const options: { label: string; value: number }[] = [];
    nodes.forEach((node) => {
      options.push({
        label: '　'.repeat(level) + node.name,
        value: node.id,
      });
      if (node.children && node.children.length > 0) {
        options.push(...buildDeptOptions(node.children, level + 1));
      }
    });
    return options;
  };

  return (
    <Modal
      title={dialogTitle}
      open={dialogVisible}
      onCancel={() => setDialogVisible(false)}
      onOk={submitForm}
      confirmLoading={formLoading}
      okText={t('common.confirm')}
      cancelText={t('common.cancel')}
      width={840}
      destroyOnClose
    >
      <Spin spinning={formLoading}>
        <Form
          form={form}
          layout="horizontal"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 19 }}
          initialValues={{
            parentId: 0,
            sort: 0,
            status: getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1,
          }}
        >
          <Form.Item
            label={t('form.parentDept')}
            name="parentId"
            rules={[{ required: true, message: t('form.parentDeptPlaceholder') }]}
          >
            <Select
              placeholder={t('form.parentDeptPlaceholder')}
              options={buildDeptOptions(deptTree)}
            />
          </Form.Item>

          <Form.Item
            label={t('form.departmentName')}
            name="name"
            rules={[
              { required: true, message: t('form.departmentNamePlaceholder') },
              { max: 50, message: t('common.error') },
            ]}
          >
            <Input placeholder={t('form.departmentNamePlaceholder')} />
          </Form.Item>

          <Form.Item
            label={t('form.displayOrder')}
            name="sort"
            rules={[{ required: true, message: t('form.displayOrderPlaceholder') }]}
          >
            <Input type="number" placeholder={t('form.displayOrderPlaceholder')} min={0} />
          </Form.Item>

          <Form.Item
            label={t('form.deptLeader')}
            name="leaderUserId"
          >
            <Select
              placeholder={t('form.deptLeaderPlaceholder')}
              allowClear
              options={[
                ...userList.map((user) => ({
                  label: user.nickname,
                  value: user.id,
                })),
              ]}
            />
          </Form.Item>

          <Form.Item
            label={t('form.deptPhone')}
            name="phone"
            rules={[
              {
                pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                message: t('form.deptPhoneRule'),
              },
            ]}
          >
            <Input placeholder={t('form.deptPhonePlaceholder')} maxLength={11} />
          </Form.Item>

          <Form.Item
            label={t('form.deptEmail')}
            name="email"
            rules={[
              {
                type: 'email',
                message: t('form.deptEmailRule'),
              },
              { max: 50, message: t('form.deptEmailMaxRule') },
            ]}
          >
            <Input type="email" placeholder={t('form.deptEmailPlaceholder')} maxLength={50} />
          </Form.Item>

          <Form.Item
            label={t('form.deptStatus')}
            name="status"
            rules={[{ required: true, message: t('form.deptStatusPlaceholder') }]}
          >
            <Select
              placeholder={t('form.deptStatusPlaceholder')}
              options={getStatusOptions().map((dict) => ({
                label: dict.label,
                value: dict.value,
              }))}
            />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
});

DeptForm.displayName = 'DeptForm';

export default DeptForm;

