/**
 * KRA - Auto Code Admin Page
 * 自动化代码管理页面 - 查看历史记录、回滚、复用
 */
import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Checkbox,
  Drawer,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  PlusOutlined,
  DeleteOutlined,
  RollbackOutlined,
  CopyOutlined,
  AppstoreAddOutlined,
  RobotOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import {
  getSysHistory,
  rollback,
  delSysHistory,
  getMeta,
  addFunc,
} from '@/services/kratos/autoCode';
import { formatDate } from '@/utils/date';
import styles from './index.less';

interface AutoCodeHistory {
  ID: number;
  CreatedAt: string;
  structName: string;
  description: string;
  tableName: string;
  flag: number;
  package?: string;
  packageName?: string;
  abbreviation?: string;
}

interface RollbackForm {
  deleteApi: boolean;
  deleteMenu: boolean;
  deleteTable: boolean;
}

interface AddFuncForm {
  package: string;
  structName: string;
  packageName: string;
  humpPackageName: string;
  description: string;
  abbreviation: string;
  isAi: boolean;
  prompt: string;
  funcDesc: string;
  funcName: string;
  method: string;
  isAuth: boolean;
  router: string;
  apiFunc?: string;
  serverFunc?: string;
  jsFunc?: string;
}

const AutoCodeAdminPage: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<AutoCodeHistory[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  
  // Rollback dialog
  const [rollbackVisible, setRollbackVisible] = useState(false);
  const [rollbackRow, setRollbackRow] = useState<AutoCodeHistory | null>(null);
  const [rollbackForm, setRollbackForm] = useState<RollbackForm>({
    deleteApi: false,
    deleteMenu: false,
    deleteTable: false,
  });
  
  // Add function drawer
  const [funcVisible, setFuncVisible] = useState(false);
  const [funcLoading, setFuncLoading] = useState(false);
  const [funcForm, setFuncForm] = useState<AddFuncForm>({
    package: '',
    structName: '',
    packageName: '',
    humpPackageName: '',
    description: '',
    abbreviation: '',
    isAi: false,
    prompt: '',
    funcDesc: '',
    funcName: '',
    method: 'GET',
    isAuth: true,
    router: '',
  });

  // Fetch table data
  const fetchData = async () => {
    setLoading(true);
    try {
      const res = await getSysHistory({ page: current, pageSize });
      if (res.code === 0) {
        setDataSource(res.data?.list || []);
        setTotal(res.data?.total || 0);
      }
    } catch (error) {
      console.error('获取历史记录失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [current, pageSize]);

  // Navigate to auto code page
  const handleGoAutoCode = (row: AutoCodeHistory | null, mode?: number) => {
    if (row) {
      // Reuse or add field mode
      navigate('/systemTools/autoCode', {
        state: { id: row.ID, mode },
      });
    } else {
      // New
      navigate('/systemTools/autoCode');
    }
  };

  // Open rollback dialog
  const handleOpenRollback = (row: AutoCodeHistory) => {
    setRollbackRow(row);
    setRollbackForm({
      deleteApi: false,
      deleteMenu: false,
      deleteTable: false,
    });
    setRollbackVisible(true);
  };

  // Execute rollback
  const handleRollback = async () => {
    if (!rollbackRow) return;
    try {
      const res = await rollback({
        id: rollbackRow.ID,
        ...rollbackForm,
      });
      if (res.code === 0) {
        message.success('回滚成功');
        setRollbackVisible(false);
        fetchData();
      } else {
        message.error(res.msg || '回滚失败');
      }
    } catch (error) {
      message.error('回滚失败');
    }
  };

  // Delete row
  const handleDelete = async (row: AutoCodeHistory) => {
    try {
      const res = await delSysHistory({ id: row.ID });
      if (res.code === 0) {
        message.success('删除成功');
        fetchData();
      } else {
        message.error(res.msg || '删除失败');
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // Open add function drawer
  const handleOpenAddFunc = async (row: AutoCodeHistory) => {
    try {
      const res = await getMeta({ id: row.ID });
      if (res.code === 0) {
        const meta = res.data;
        setFuncForm({
          package: meta.package || '',
          structName: meta.structName || '',
          packageName: meta.packageName || '',
          humpPackageName: meta.humpPackageName || '',
          description: meta.description || '',
          abbreviation: meta.abbreviation || '',
          isAi: false,
          prompt: '',
          funcDesc: '',
          funcName: '',
          method: 'GET',
          isAuth: true,
          router: '',
        });
        setFuncVisible(true);
      }
    } catch (error) {
      message.error('获取元数据失败');
    }
  };

  // Execute add function
  const handleAddFunc = async () => {
    if (!funcForm.funcName || !funcForm.router) {
      message.warning('请填写方法名和路由');
      return;
    }
    setFuncLoading(true);
    try {
      const res = await addFunc(funcForm);
      if (res.code === 0) {
        message.success('添加成功');
        setFuncVisible(false);
      } else {
        message.error(res.msg || '添加失败');
      }
    } catch (error) {
      message.error('添加失败');
    } finally {
      setFuncLoading(false);
    }
  };

  const columns: ColumnsType<AutoCodeHistory> = [
    { title: 'ID', dataIndex: 'ID', width: 60 },
    {
      title: '日期',
      dataIndex: 'CreatedAt',
      width: 180,
      render: (text) => formatDate(text),
    },
    { title: '结构体名', dataIndex: 'structName', width: 150 },
    { title: '结构体描述', dataIndex: 'description', width: 150 },
    { title: '表名称', dataIndex: 'tableName', width: 150 },
    {
      title: '回滚标记',
      dataIndex: 'flag',
      width: 100,
      render: (flag) =>
        flag ? (
          <Tag color="error">已回滚</Tag>
        ) : (
          <Tag color="success">未回滚</Tag>
        ),
    },
    {
      title: '操作',
      key: 'action',
      width: 320,
      render: (_, record) => (
        <Space wrap>
          <Button
            type="link"
            size="small"
            icon={<AppstoreAddOutlined />}
            disabled={record.flag === 1}
            onClick={() => handleOpenAddFunc(record)}
          >
            增加方法
          </Button>
          <Button
            type="link"
            size="small"
            icon={<PlusOutlined />}
            onClick={() => handleGoAutoCode(record, 1)}
          >
            增加字段
          </Button>
          <Button
            type="link"
            size="small"
            icon={<RollbackOutlined />}
            disabled={record.flag === 1}
            onClick={() => handleOpenRollback(record)}
          >
            回滚
          </Button>
          <Button
            type="link"
            size="small"
            icon={<CopyOutlined />}
            onClick={() => handleGoAutoCode(record)}
          >
            复用
          </Button>
          <Popconfirm
            title="确定要删除吗?"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" size="small" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <Card>
        <div className={styles.toolbar}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => handleGoAutoCode(null)}
          >
            新增
          </Button>
        </div>
        <Table
          rowKey="ID"
          columns={columns}
          dataSource={dataSource}
          loading={loading}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (t) => `共 ${t} 条`,
            onChange: (page, size) => {
              setCurrent(page);
              setPageSize(size);
            },
          }}
        />
      </Card>

      {/* Rollback Dialog */}
      <Modal
        title="回滚确认"
        open={rollbackVisible}
        onCancel={() => setRollbackVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setRollbackVisible(false)}>
            取消
          </Button>,
          <Popconfirm
            key="confirm"
            title="此操作将回滚生成文件和勾选项目，是否继续?"
            onConfirm={handleRollback}
            okText="确定"
            cancelText="取消"
          >
            <Button type="primary">确定</Button>
          </Popconfirm>,
        ]}
      >
        <Form layout="inline">
          <Form.Item label="选项">
            <Space>
              <Checkbox
                checked={rollbackForm.deleteApi}
                onChange={(e) =>
                  setRollbackForm((prev) => ({ ...prev, deleteApi: e.target.checked }))
                }
              >
                删除接口
              </Checkbox>
              <Checkbox
                checked={rollbackForm.deleteMenu}
                onChange={(e) =>
                  setRollbackForm((prev) => ({ ...prev, deleteMenu: e.target.checked }))
                }
              >
                删除菜单
              </Checkbox>
              <Checkbox
                checked={rollbackForm.deleteTable}
                onChange={(e) =>
                  setRollbackForm((prev) => ({ ...prev, deleteTable: e.target.checked }))
                }
              >
                删除表
              </Checkbox>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* Add Function Drawer */}
      <Drawer
        title="增加方法"
        open={funcVisible}
        onClose={() => setFuncVisible(false)}
        width={600}
        extra={
          <Space>
            <Button onClick={() => setFuncVisible(false)}>取消</Button>
            <Button type="primary" loading={funcLoading} onClick={handleAddFunc}>
              生成
            </Button>
          </Space>
        }
      >
        <Form layout="vertical">
          <Form.Item label="包名">
            <Input value={funcForm.package} disabled />
          </Form.Item>
          <Form.Item label="结构体名">
            <Input value={funcForm.structName} disabled />
          </Form.Item>
          <Form.Item label="描述">
            <Input value={funcForm.description} disabled />
          </Form.Item>
          <Form.Item label="是否AI填充">
            <Checkbox
              checked={funcForm.isAi}
              onChange={(e) =>
                setFuncForm((prev) => ({ ...prev, isAi: e.target.checked }))
              }
            />
            <span className={styles.aiWarning}>
              当前AI帮写存在不稳定因素，生成代码后请注意手动调整部分内容
            </span>
          </Form.Item>
          {funcForm.isAi && (
            <Form.Item label="AI帮写">
              <Input.TextArea
                value={funcForm.prompt}
                onChange={(e) =>
                  setFuncForm((prev) => ({ ...prev, prompt: e.target.value }))
                }
                rows={4}
                placeholder="AI帮写功能，输入提示信息，自动生成代码"
              />
            </Form.Item>
          )}
          <Form.Item label="方法介绍">
            <Space.Compact style={{ width: '100%' }}>
              <Input
                value={funcForm.funcDesc}
                onChange={(e) =>
                  setFuncForm((prev) => ({ ...prev, funcDesc: e.target.value }))
                }
                placeholder="请输入方法介绍"
              />
              <Button type="primary" icon={<RobotOutlined />}>
                补全
              </Button>
            </Space.Compact>
          </Form.Item>
          <Form.Item label="方法名" required>
            <Input
              value={funcForm.funcName}
              onChange={(e) =>
                setFuncForm((prev) => ({ ...prev, funcName: e.target.value }))
              }
              placeholder="请输入方法名"
            />
          </Form.Item>
          <Form.Item label="方法">
            <Select
              value={funcForm.method}
              onChange={(val) => setFuncForm((prev) => ({ ...prev, method: val }))}
              options={[
                { label: 'GET', value: 'GET' },
                { label: 'POST', value: 'POST' },
                { label: 'PUT', value: 'PUT' },
                { label: 'DELETE', value: 'DELETE' },
              ]}
            />
          </Form.Item>
          <Form.Item label="是否鉴权">
            <Checkbox
              checked={funcForm.isAuth}
              onChange={(e) =>
                setFuncForm((prev) => ({ ...prev, isAuth: e.target.checked }))
              }
            />
          </Form.Item>
          <Form.Item label="路由path" required>
            <Input
              value={funcForm.router}
              onChange={(e) =>
                setFuncForm((prev) => ({
                  ...prev,
                  router: e.target.value.replace(/\//g, ''),
                }))
              }
              placeholder="路由path"
            />
          </Form.Item>
        </Form>
      </Drawer>
    </PageContainer>
  );
};

export default AutoCodeAdminPage;
