import { MyResponseType } from '@/common';
import { Form, Input, Modal, message } from 'antd';
import { useEffect, useState } from 'react';
import PermissionTree from './PermissionTree';

interface RoleFormModalProps {
  open: boolean;
  onCancel: () => void;
  onSuccess: () => void;
  item?: Record<string, any>;
  title: string;
  storeApi: (data: any) => Promise<MyResponseType>;
  updateApi: (data: any) => Promise<MyResponseType>;
  setPermissionsApi: (data: any) => Promise<MyResponseType>;
  getPermissionsApi: (data: any) => Promise<MyResponseType>;
  permissionTreeApi: () => Promise<MyResponseType>;
}

export default function RoleFormModal({
  open,
  onCancel,
  onSuccess,
  item,
  title,
  storeApi,
  updateApi,
  setPermissionsApi,
  getPermissionsApi,
  permissionTreeApi,
}: RoleFormModalProps) {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const isEdit = !!item?.id;

  useEffect(() => {
    if (!open) return;

    if (isEdit && item) {
      form.setFieldsValue({ name: item.name });
      let cancelled = false;
      getPermissionsApi({ id: item.id }).then((res: any) => {
        if (cancelled) return;
        const ids = res.data?.permissions_ids || [];
        form.setFieldsValue({ permissions_ids: ids });
      });
      return () => {
        cancelled = true;
      };
    }

    form.resetFields();
  }, [open, item]);

  const extractId = (res: MyResponseType): number | undefined => {
    const data = (res as any).data;
    if (typeof data === 'number') return data;
    if (data && typeof data === 'object') {
      return data.id ?? data.data?.id;
    }
    return undefined;
  };

  const handleOk = async () => {
    const values = await form.validateFields();
    setLoading(true);
    try {
      let roleId = item?.id;
      if (!isEdit) {
        const res = await storeApi({ name: values.name });
        roleId = extractId(res);
        if (!roleId) {
          throw new Error('创建角色失败，未返回角色ID');
        }
      } else {
        await updateApi({ id: roleId, name: values.name });
      }

      await setPermissionsApi({
        id: roleId,
        permissions_ids: values.permissions_ids || [],
      });

      message.success('保存成功');
      onSuccess();
    } catch (err: any) {
      message.error(err?.message || '保存失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      open={open}
      destroyOnClose
      title={`${isEdit ? '编辑' : '新增'}${title}`}
      onCancel={onCancel}
      onOk={handleOk}
      confirmLoading={loading}
      width={600}
      maskClosable={false}
    >
      <Form form={form} layout="vertical" preserve={false}>
        <Form.Item
          name="name"
          label="角色名称"
          rules={[{ required: true, message: '请输入角色名称' }]}
        >
          <Input placeholder="请输入角色名称" />
        </Form.Item>
        <Form.Item name="permissions_ids" label="权限配置">
          <PermissionTree api={permissionTreeApi} />
        </Form.Item>
      </Form>
    </Modal>
  );
}
