/**
 * KRA - Authority Form Component
 * Create/Edit/Copy authority form in drawer
 */
import React, { useState, useEffect } from 'react';
import { Drawer, Form, Input, Button, Space, Cascader, message } from 'antd';
import {
  createAuthority,
  updateAuthority,
  copyAuthority,
} from '@/services/kratos/authority';

interface Authority {
  authorityId: string;
  authorityName: string;
  parentId: string;
  children?: Authority[];
  dataAuthorityId?: Authority[];
}

interface AuthorityFormProps {
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
  dialogType: 'add' | 'edit' | 'copy';
  initialValues: Authority | null;
  parentId: string;
  authorityOptions: Authority[];
}

const AuthorityForm: React.FC<AuthorityFormProps> = ({
  visible,
  onClose,
  onSuccess,
  dialogType,
  initialValues,
  parentId,
  authorityOptions,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (visible) {
      if (dialogType === 'add') {
        form.resetFields();
        form.setFieldsValue({ parentId: parentId || '0' });
      } else if (initialValues) {
        form.setFieldsValue({
          authorityId: initialValues.authorityId,
          authorityName: initialValues.authorityName,
          parentId: initialValues.parentId || '0',
        });
      }
    }
  }, [visible, dialogType, initialValues, parentId, form]);

  // 构建级联选项
  const buildCascaderOptions = (data: Authority[], currentId?: string): any[] => {
    const rootOption = {
      value: '0',
      label: '根角色(严格模式下为当前用户角色)',
      disabled: false,
    };

    const buildOptions = (items: Authority[], disabled: boolean = false): any[] => {
      return items.map((item) => ({
        value: item.authorityId,
        label: item.authorityName,
        disabled: disabled || item.authorityId === currentId,
        children: item.children
          ? buildOptions(item.children, disabled || item.authorityId === currentId)
          : undefined,
      }));
    };

    return [rootOption, ...buildOptions(data)];
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const submitData = {
        authorityId: values.authorityId,
        authorityName: values.authorityName,
        parentId: values.parentId || '0',
      };

      let res;
      switch (dialogType) {
        case 'add':
          res = await createAuthority(submitData);
          break;
        case 'edit':
          res = await updateAuthority(submitData);
          break;
        case 'copy':
          res = await copyAuthority({
            authority: {
              ...submitData,
              dataAuthorityId: initialValues?.dataAuthorityId || [],
            },
            oldAuthorityId: initialValues?.authorityId || '',
          });
          break;
      }

      if (res?.code === 0) {
        message.success(
          dialogType === 'add' ? '添加成功' : dialogType === 'edit' ? '编辑成功' : '复制成功'
        );
        onSuccess();
      } else {
        message.error(res?.msg || '操作失败');
      }
    } catch (error) {
      console.error('Form validation failed:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    form.resetFields();
    onClose();
  };

  const getTitle = () => {
    switch (dialogType) {
      case 'add':
        return '新增角色';
      case 'edit':
        return '编辑角色';
      case 'copy':
        return '拷贝角色';
      default:
        return '角色';
    }
  };

  return (
    <Drawer
      title={getTitle()}
      width={500}
      open={visible}
      onClose={handleClose}
      extra={
        <Space>
          <Button onClick={handleClose}>取消</Button>
          <Button type="primary" loading={loading} onClick={handleSubmit}>
            确定
          </Button>
        </Space>
      }
    >
      <Form
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        <Form.Item
          name="parentId"
          label="父级角色"
          rules={[{ required: true, message: '请选择父角色' }]}
        >
          <Cascader
            options={buildCascaderOptions(authorityOptions, dialogType === 'edit' ? initialValues?.authorityId : undefined)}
            disabled={dialogType === 'add'}
            showSearch
            changeOnSelect
            style={{ width: '100%' }}
            placeholder="请选择父级角色"
          />
        </Form.Item>
        <Form.Item
          name="authorityId"
          label="角色ID"
          rules={[
            { required: true, message: '请输入角色ID' },
            { pattern: /^[0-9]*[1-9][0-9]*$/, message: '必须为正整数' },
          ]}
        >
          <Input
            placeholder="请输入角色ID"
            disabled={dialogType === 'edit'}
            maxLength={15}
          />
        </Form.Item>
        <Form.Item
          name="authorityName"
          label="角色名称"
          rules={[{ required: true, message: '请输入角色名' }]}
        >
          <Input placeholder="请输入角色名称" />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default AuthorityForm;
