/**
 * KRA - Menu Form Drawer Component
 * Create and edit menu with all configurations
 */
import React, { useState, useEffect } from 'react';
import {
  Drawer,
  Form,
  Input,
  Select,
  InputNumber,
  Button,
  Space,
  Row,
  Col,
  Table,
  Cascader,
  Tooltip,
  Divider,
  message,
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  QuestionCircleOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons';
import { addBaseMenu, updateBaseMenu } from '@/services/kratos/menu';
import IconSelector from './IconSelector';
import type { MenuItem } from '../index';

interface MenuFormProps {
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
  initialValues: MenuItem | null;
  dialogFlag: 'add' | 'edit';
  parentId: number;
  menuList: MenuItem[];
}

interface MenuOption {
  value: number;
  label: string;
  disabled?: boolean;
  children?: MenuOption[];
}

const MenuForm: React.FC<MenuFormProps> = ({
  visible,
  onClose,
  onSuccess,
  initialValues,
  dialogFlag,
  parentId,
  menuList,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [checkFlag, setCheckFlag] = useState(false);
  const [parameters, setParameters] = useState<Array<{ type: string; key: string; value: string }>>([]);
  const [menuBtns, setMenuBtns] = useState<Array<{ name: string; desc: string }>>([]);
  const [menuOptions, setMenuOptions] = useState<MenuOption[]>([]);

  // 构建菜单选项树
  const buildMenuOptions = (
    data: MenuItem[],
    disabled: boolean = false,
    currentId?: number
  ): MenuOption[] => {
    return data.map((item) => ({
      value: item.ID,
      label: item.meta?.title || item.name,
      disabled: disabled || item.ID === currentId,
      children: item.children?.length
        ? buildMenuOptions(item.children, disabled || item.ID === currentId, currentId)
        : undefined,
    }));
  };

  // 初始化表单
  useEffect(() => {
    if (visible) {
      // 构建菜单选项
      const options: MenuOption[] = [
        { value: 0, label: '根目录' },
        ...buildMenuOptions(menuList, false, initialValues?.ID),
      ];
      setMenuOptions(options);

      if (dialogFlag === 'edit' && initialValues) {
        form.setFieldsValue({
          ...initialValues,
          'meta.title': initialValues.meta?.title,
          'meta.icon': initialValues.meta?.icon,
          'meta.keepAlive': initialValues.meta?.keepAlive || false,
          'meta.defaultMenu': initialValues.meta?.defaultMenu || false,
          'meta.closeTab': initialValues.meta?.closeTab || false,
          'meta.activeName': initialValues.meta?.activeName,
          'meta.transitionType': initialValues.meta?.transitionType,
        });
        setParameters(initialValues.parameters || []);
        setMenuBtns(initialValues.menuBtn || []);
        setCheckFlag(initialValues.path !== initialValues.name);
      } else {
        form.resetFields();
        form.setFieldsValue({
          parentId: parentId,
          hidden: false,
          sort: 0,
          'meta.keepAlive': false,
          'meta.defaultMenu': false,
          'meta.closeTab': false,
        });
        setParameters([]);
        setMenuBtns([]);
        setCheckFlag(false);
      }
    }
  }, [visible, initialValues, dialogFlag, parentId, menuList, form]);

  // 路由Name变化时同步Path
  const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const name = e.target.value;
    if (!checkFlag) {
      form.setFieldsValue({ path: name });
    }
  };

  // 添加参数
  const handleAddParameter = () => {
    setParameters([...parameters, { type: 'query', key: '', value: '' }]);
  };

  // 删除参数
  const handleDeleteParameter = (index: number) => {
    const newParams = [...parameters];
    newParams.splice(index, 1);
    setParameters(newParams);
  };

  // 更新参数
  const handleUpdateParameter = (index: number, field: string, value: string) => {
    const newParams = [...parameters];
    (newParams[index] as any)[field] = value;
    setParameters(newParams);
  };

  // 添加按钮
  const handleAddBtn = () => {
    setMenuBtns([...menuBtns, { name: '', desc: '' }]);
  };

  // 删除按钮
  const handleDeleteBtn = (index: number) => {
    const newBtns = [...menuBtns];
    newBtns.splice(index, 1);
    setMenuBtns(newBtns);
  };

  // 更新按钮
  const handleUpdateBtn = (index: number, field: string, value: string) => {
    const newBtns = [...menuBtns];
    (newBtns[index] as any)[field] = value;
    setMenuBtns(newBtns);
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const submitData: any = {
        ...initialValues,
        ...values,
        meta: {
          title: values['meta.title'],
          icon: values['meta.icon'],
          keepAlive: values['meta.keepAlive'] || false,
          defaultMenu: values['meta.defaultMenu'] || false,
          closeTab: values['meta.closeTab'] || false,
          activeName: values['meta.activeName'],
          transitionType: values['meta.transitionType'],
        },
        parameters: parameters.filter((p) => p.key),
        menuBtn: menuBtns.filter((b) => b.name),
      };

      // 删除扁平化的meta字段
      delete submitData['meta.title'];
      delete submitData['meta.icon'];
      delete submitData['meta.keepAlive'];
      delete submitData['meta.defaultMenu'];
      delete submitData['meta.closeTab'];
      delete submitData['meta.activeName'];
      delete submitData['meta.transitionType'];

      let res;
      if (dialogFlag === 'edit') {
        res = await updateBaseMenu(submitData);
      } else {
        res = await addBaseMenu(submitData);
      }

      if (res.code === 0) {
        message.success(dialogFlag === 'edit' ? '编辑成功' : '添加成功，请到角色管理页面分配权限');
        onSuccess();
      } else {
        message.error(res.msg || '操作失败');
      }
    } catch (error) {
      console.error('Form validation failed:', error);
    } finally {
      setLoading(false);
    }
  };

  // 参数表格列
  const paramColumns = [
    {
      title: '参数类型',
      dataIndex: 'type',
      width: 120,
      render: (_: any, record: any, index: number) => (
        <Select
          value={record.type}
          onChange={(v) => handleUpdateParameter(index, 'type', v)}
          style={{ width: '100%' }}
          size="small"
        >
          <Select.Option value="query">query</Select.Option>
          <Select.Option value="params">params</Select.Option>
        </Select>
      ),
    },
    {
      title: '参数key',
      dataIndex: 'key',
      width: 150,
      render: (_: any, record: any, index: number) => (
        <Input
          value={record.key}
          onChange={(e) => handleUpdateParameter(index, 'key', e.target.value)}
          placeholder="请输入参数key"
          size="small"
        />
      ),
    },
    {
      title: '参数值',
      dataIndex: 'value',
      render: (_: any, record: any, index: number) => (
        <Input
          value={record.value}
          onChange={(e) => handleUpdateParameter(index, 'value', e.target.value)}
          placeholder="请输入参数值"
          size="small"
        />
      ),
    },
    {
      title: '操作',
      width: 80,
      render: (_: any, __: any, index: number) => (
        <Button
          type="text"
          danger
          size="small"
          icon={<DeleteOutlined />}
          onClick={() => handleDeleteParameter(index)}
        />
      ),
    },
  ];

  // 按钮表格列
  const btnColumns = [
    {
      title: '按钮名称',
      dataIndex: 'name',
      width: 150,
      render: (_: any, record: any, index: number) => (
        <Input
          value={record.name}
          onChange={(e) => handleUpdateBtn(index, 'name', e.target.value)}
          placeholder="请输入按钮名称"
          size="small"
        />
      ),
    },
    {
      title: '备注',
      dataIndex: 'desc',
      render: (_: any, record: any, index: number) => (
        <Input
          value={record.desc}
          onChange={(e) => handleUpdateBtn(index, 'desc', e.target.value)}
          placeholder="请输入按钮备注"
          size="small"
        />
      ),
    },
    {
      title: '操作',
      width: 80,
      render: (_: any, __: any, index: number) => (
        <Button
          type="text"
          danger
          size="small"
          icon={<DeleteOutlined />}
          onClick={() => handleDeleteBtn(index)}
        />
      ),
    },
  ];

  return (
    <Drawer
      title={dialogFlag === 'edit' ? '编辑菜单' : '新增菜单'}
      width={720}
      open={visible}
      onClose={onClose}
      destroyOnClose
      extra={
        <Space>
          <Button onClick={onClose}>取消</Button>
          <Button type="primary" loading={loading} onClick={handleSubmit}>
            确定
          </Button>
        </Space>
      }
    >
      <Form form={form} layout="vertical" requiredMark="optional">
        {/* 基础信息 */}
        <Divider orientation="left">基础信息</Divider>
        <Form.Item
          name="component"
          label="文件路径"
          rules={[{ required: true, message: '请输入文件路径' }]}
          extra={
            <Space>
              <InfoCircleOutlined style={{ color: '#1890ff' }} />
              <span>如果菜单包含子菜单，请创建router-view二级路由页面或设置为 view/routerHolder.vue</span>
            </Space>
          }
        >
          <Input placeholder="页面:view/xxx/xx.vue 插件:plugin/xx/xx.vue" />
        </Form.Item>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="meta.title"
              label="展示名称"
              rules={[{ required: true, message: '请输入菜单展示名称' }]}
            >
              <Input placeholder="请输入菜单展示名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="name"
              label="路由Name"
              rules={[{ required: true, message: '请输入路由Name' }]}
            >
              <Input placeholder="唯一英文字符串" onChange={handleNameChange} />
            </Form.Item>
          </Col>
        </Row>

        {/* 路由配置 */}
        <Divider orientation="left">路由配置</Divider>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item name="parentId" label="父节点ID">
              <Cascader
                options={menuOptions}
                disabled={dialogFlag === 'edit'}
                placeholder="请选择父节点"
                changeOnSelect
                showSearch
                fieldNames={{ label: 'label', value: 'value', children: 'children' }}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="path"
              label={
                <Space>
                  <span>路由Path</span>
                  <Button
                    type="link"
                    size="small"
                    onClick={() => setCheckFlag(!checkFlag)}
                  >
                    {checkFlag ? '自动同步' : '添加参数'}
                  </Button>
                </Space>
              }
              rules={[{ required: true, message: '请输入路由Path' }]}
            >
              <Input placeholder="建议只在后方拼接参数" disabled={!checkFlag} />
            </Form.Item>
          </Col>
        </Row>

        {/* 显示设置 */}
        <Divider orientation="left">显示设置</Divider>
        <Row gutter={16}>
          <Col span={8}>
            <Form.Item name="meta.icon" label="图标">
              <IconSelector />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item name="sort" label="排序标记">
              <InputNumber placeholder="请输入排序数字" style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item name="hidden" label="是否隐藏">
              <Select placeholder="是否在列表隐藏">
                <Select.Option value={false}>否</Select.Option>
                <Select.Option value={true}>是</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        {/* 高级配置 */}
        <Divider orientation="left">高级配置</Divider>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="meta.activeName"
              label={
                <Space>
                  <span>高亮菜单</span>
                  <Tooltip title="注：当到达此路由时候，指定左侧菜单指定name会处于活跃状态（亮起），可为空，为空则为本路由Name。">
                    <QuestionCircleOutlined />
                  </Tooltip>
                </Space>
              }
            >
              <Input placeholder="请输入高亮菜单名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item name="meta.keepAlive" label="KeepAlive">
              <Select placeholder="是否keepAlive缓存页面">
                <Select.Option value={false}>否</Select.Option>
                <Select.Option value={true}>是</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item name="meta.closeTab" label="CloseTab">
              <Select placeholder="是否自动关闭tab">
                <Select.Option value={false}>否</Select.Option>
                <Select.Option value={true}>是</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="meta.defaultMenu"
              label={
                <Space>
                  <span>是否为基础页面</span>
                  <Tooltip title="此项选择为是，则不会展示左侧菜单以及顶部信息。">
                    <QuestionCircleOutlined />
                  </Tooltip>
                </Space>
              }
            >
              <Select placeholder="是否为基础页面">
                <Select.Option value={false}>否</Select.Option>
                <Select.Option value={true}>是</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="meta.transitionType"
              label={
                <Space>
                  <span>路由切换动画</span>
                  <Tooltip title="如果设置了路由切换动画，在本路由下的动画优先级高于全局动画切换优先级。">
                    <QuestionCircleOutlined />
                  </Tooltip>
                </Space>
              }
            >
              <Select placeholder="跟随全局" allowClear>
                <Select.Option value="fade">淡入淡出</Select.Option>
                <Select.Option value="slide">滑动</Select.Option>
                <Select.Option value="zoom">缩放</Select.Option>
                <Select.Option value="none">无动画</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        {/* 菜单参数配置 */}
        <Divider orientation="left">
          <Space>
            <span>菜单参数配置</span>
            <Button type="primary" size="small" icon={<PlusOutlined />} onClick={handleAddParameter}>
              新增菜单参数
            </Button>
          </Space>
        </Divider>
        <Table
          dataSource={parameters}
          columns={paramColumns}
          rowKey={(_, index) => `param-${index}`}
          pagination={false}
          size="small"
          bordered
        />

        {/* 可控按钮配置 */}
        <Divider orientation="left" style={{ marginTop: 24 }}>
          <Space>
            <span>可控按钮配置</span>
            <Button type="primary" size="small" icon={<PlusOutlined />} onClick={handleAddBtn}>
              新增可控按钮
            </Button>
            <Tooltip title="点击查看按钮权限配置文档">
              <QuestionCircleOutlined style={{ color: '#1890ff', cursor: 'pointer' }} />
            </Tooltip>
          </Space>
        </Divider>
        <Table
          dataSource={menuBtns}
          columns={btnColumns}
          rowKey={(_, index) => `btn-${index}`}
          pagination={false}
          size="small"
          bordered
        />
      </Form>
    </Drawer>
  );
};

export default MenuForm;
