import React, { useState, useRef } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  Button,
  Space,
  Popconfirm,
  message,
  Drawer,
  Form,
  Input,
  Descriptions,
  Alert,
} from 'antd';
import { PlusOutlined, DeleteOutlined, InfoCircleOutlined } from '@ant-design/icons';
import {
  getParamsList,
  createParams,
  updateParams,
  deleteParams,
  deleteParamsByIds,
  findParams,
} from '@/services/kratos/params';
import { formatDate } from '@/utils/date';
import styles from './index.less';

interface ParamsItem {
  ID: number;
  CreatedAt: string;
  name: string;
  key: string;
  value: string;
  desc: string;
}

const ParamsPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [editType, setEditType] = useState<'create' | 'update'>('create');
  const [currentRecord, setCurrentRecord] = useState<ParamsItem | null>(null);
  const [detailRecord, setDetailRecord] = useState<ParamsItem | null>(null);
  const [form] = Form.useForm();

  // 打开新增抽屉
  const handleAdd = () => {
    setEditType('create');
    setCurrentRecord(null);
    form.resetFields();
    setDrawerVisible(true);
  };

  // 打开编辑抽屉
  const handleEdit = async (record: ParamsItem) => {
    setEditType('update');
    try {
      const res = await findParams({ ID: record.ID });
      if (res.code === 0) {
        setCurrentRecord(res.data);
        form.setFieldsValue(res.data);
        setDrawerVisible(true);
      }
    } catch (error) {
      message.error('获取详情失败');
    }
  };

  // 查看详情
  const handleViewDetail = async (record: ParamsItem) => {
    try {
      const res = await findParams({ ID: record.ID });
      if (res.code === 0) {
        setDetailRecord(res.data);
        setDetailVisible(true);
      }
    } catch (error) {
      message.error('获取详情失败');
    }
  };

  // 删除单条
  const handleDelete = async (record: ParamsItem) => {
    try {
      const res = await deleteParams({ ID: record.ID });
      if (res.code === 0) {
        message.success('删除成功');
        actionRef.current?.reload();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的数据');
      return;
    }
    try {
      const res = await deleteParamsByIds({ IDs: selectedRowKeys as number[] });
      if (res.code === 0) {
        message.success('删除成功');
        setSelectedRowKeys([]);
        actionRef.current?.reload();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 关闭抽屉
  const handleCloseDrawer = () => {
    setDrawerVisible(false);
    form.resetFields();
    setCurrentRecord(null);
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      let res;
      if (editType === 'create') {
        res = await createParams(values);
      } else {
        res = await updateParams({ ...currentRecord, ...values });
      }
      if (res.code === 0) {
        message.success(editType === 'create' ? '创建成功' : '更新成功');
        handleCloseDrawer();
        actionRef.current?.reload();
      }
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const columns: ProColumns<ParamsItem>[] = [
    {
      title: '日期',
      dataIndex: 'CreatedAt',
      valueType: 'dateTime',
      width: 180,
      search: false,
      render: (_, record) => formatDate(record.CreatedAt),
    },
    {
      title: '参数名称',
      dataIndex: 'name',
      width: 150,
    },
    {
      title: '参数键',
      dataIndex: 'key',
      width: 150,
    },
    {
      title: '参数值',
      dataIndex: 'value',
      width: 200,
      search: false,
      ellipsis: true,
    },
    {
      title: '参数说明',
      dataIndex: 'desc',
      width: 200,
      search: false,
      ellipsis: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="detail"
          type="link"
          size="small"
          icon={<InfoCircleOutlined />}
          onClick={() => handleViewDetail(record)}
        >
          查看详情
        </Button>,
        <Button key="edit" type="link" size="small" onClick={() => handleEdit(record)}>
          变更
        </Button>,
        <Popconfirm
          key="delete"
          title="确定要删除吗？"
          onConfirm={() => handleDelete(record)}
        >
          <Button type="link" size="small" danger>
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <Alert
        message="获取参数且缓存方法已在前端 utils/params 已经封装完成，不必自己书写，使用方法查看文件内注释"
        type="warning"
        showIcon
        style={{ marginBottom: 16 }}
      />
      <ProTable<ParamsItem>
        actionRef={actionRef}
        columns={columns}
        rowKey="ID"
        scroll={{ x: 1000 }}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        request={async (params) => {
          const res = await getParamsList({
            page: params.current,
            pageSize: params.pageSize,
            name: params.name,
            key: params.key,
          });
          return {
            data: res.data?.list || [],
            total: res.data?.total || 0,
            success: res.code === 0,
          };
        }}
        toolBarRender={() => [
          <Button key="add" type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增
          </Button>,
          <Popconfirm
            key="batchDelete"
            title="确定要删除选中的数据吗？"
            onConfirm={handleBatchDelete}
            disabled={selectedRowKeys.length === 0}
          >
            <Button
              icon={<DeleteOutlined />}
              disabled={selectedRowKeys.length === 0}
            >
              删除
            </Button>
          </Popconfirm>,
        ]}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      <Drawer
        title={editType === 'create' ? '添加' : '修改'}
        open={drawerVisible}
        onClose={handleCloseDrawer}
        width={800}
        extra={
          <Space>
            <Button onClick={handleCloseDrawer}>取消</Button>
            <Button type="primary" onClick={handleSubmit}>
              确定
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="参数名称"
            name="name"
            rules={[
              { required: true, message: '请输入参数名称' },
              { whitespace: true, message: '不能只输入空格' },
            ]}
          >
            <Input placeholder="请输入参数名称" />
          </Form.Item>
          <Form.Item
            label="参数键"
            name="key"
            rules={[
              { required: true, message: '请输入参数键' },
              { whitespace: true, message: '不能只输入空格' },
            ]}
          >
            <Input placeholder="请输入参数键" />
          </Form.Item>
          <Form.Item
            label="参数值"
            name="value"
            rules={[
              { required: true, message: '请输入参数值' },
              { whitespace: true, message: '不能只输入空格' },
            ]}
          >
            <Input.TextArea rows={5} placeholder="请输入参数值" />
          </Form.Item>
          <Form.Item label="参数说明" name="desc">
            <Input placeholder="请输入参数说明" />
          </Form.Item>
        </Form>

        <div className={styles.usageInstructions}>
          <h3>使用说明</h3>
          <p>
            前端可以通过引入{' '}
            <code>{"import { getParams } from '@/utils/params'"}</code> 然后通过{' '}
            <code>{`await getParams("${form.getFieldValue('key') || 'your_key'}")`}</code>{' '}
            来获取对应的参数。
          </p>
          <p>
            后端需要提前{' '}
            <code>
              {'import "github.com/go-kratos/kratos-admin/server/service/system"'}
            </code>
          </p>
          <p>
            然后调用{' '}
            <code>
              {`new(system.SysParamsService).GetSysParam("${
                form.getFieldValue('key') || 'your_key'
              }")`}
            </code>{' '}
            来获取对应的 value 值。
          </p>
        </div>
      </Drawer>

      <Drawer
        title="参数详情"
        open={detailVisible}
        onClose={() => {
          setDetailVisible(false);
          setDetailRecord(null);
        }}
        width={800}
      >
        {detailRecord && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="参数名称">{detailRecord.name}</Descriptions.Item>
            <Descriptions.Item label="参数键">{detailRecord.key}</Descriptions.Item>
            <Descriptions.Item label="参数值">{detailRecord.value}</Descriptions.Item>
            <Descriptions.Item label="参数说明">{detailRecord.desc}</Descriptions.Item>
          </Descriptions>
        )}
      </Drawer>
    </PageContainer>
  );
};

export default ParamsPage;
