import {
  siteapicontrollerCreatewebhook,
  siteapicontrollerDeletewebhook,
  siteapicontrollerGetwebhooks,
  siteapicontrollerUpdatewebhook,
} from '@/servers/api/siteApi';
import {
  ActionType,
  ProCard,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { useParams } from '@umijs/max';
import {
  Button,
  Form,
  Input,
  message,
  Modal,
  Popconfirm,
  Select,
  Space,
} from 'antd';
import React, { useRef, useState } from 'react';

const WebhooksPage: React.FC = () => {
  const params = useParams();
  const siteId = Number(params.siteId);
  const actionRef = useRef<ActionType>();

  // 模态框状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const [currentWebhook, setCurrentWebhook] =
    useState<API.UnifiedWebhookDTO | null>(null);

  // 表单实例
  const [form] = Form.useForm();

  // webhook主题选项
  const webhookTopics = [
    { label: '订单创建', value: 'order.created' },
    { label: '订单更新', value: 'order.updated' },
    { label: '订单删除', value: 'order.deleted' },
    { label: '产品创建', value: 'product.created' },
    { label: '产品更新', value: 'product.updated' },
    { label: '产品删除', value: 'product.deleted' },
    { label: '客户创建', value: 'customer.created' },
    { label: '客户更新', value: 'customer.updated' },
    { label: '客户删除', value: 'customer.deleted' },
  ];

  // webhook状态选项
  const webhookStatuses = [
    { label: '活跃', value: 'active' },
    { label: '非活跃', value: 'inactive' },
  ];

  // 打开新建模态框
  const showCreateModal = () => {
    setIsEditMode(false);
    setCurrentWebhook(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  // 打开编辑模态框
  const showEditModal = async (record: API.UnifiedWebhookDTO) => {
    setIsEditMode(true);
    setCurrentWebhook(record);
    try {
      // 如果需要获取最新的webhook数据，可以取消下面的注释
      // const response = await siteapicontrollerGetwebhook({ siteId, id: String(record.id) });
      // if (response.success && response.data) {
      //   form.setFieldsValue(response.data);
      // } else {
      //   form.setFieldsValue(record);
      // }
      form.setFieldsValue(record);
      setIsModalVisible(true);
    } catch (error) {
      message.error('加载webhook数据失败');
    }
  };

  // 关闭模态框
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

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

      // 准备提交数据
      const webhookData = {
        ...values,
        siteId,
      };

      let response;
      if (isEditMode && currentWebhook?.id) {
        // 更新webhook
        response = await siteapicontrollerUpdatewebhook({
          ...webhookData,
          id: String(currentWebhook.id),
        });
      } else {
        // 创建新webhook
        response = await siteapicontrollerCreatewebhook(webhookData);
      }

      if (response.success) {
        message.success(isEditMode ? '更新成功' : '创建成功');
        setIsModalVisible(false);
        form.resetFields();
        actionRef.current?.reload();
      } else {
        message.error(isEditMode ? '更新失败' : '创建失败');
      }
    } catch (error: any) {
      message.error('表单验证失败:' + error.message);
    }
  };

  const columns: ProColumns<API.UnifiedWebhookDTO>[] = [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 50 },
    { title: '名称', dataIndex: 'name', key: 'name' },
    { title: '主题', dataIndex: 'topic', key: 'topic' },
    {
      title: '回调URL',
      dataIndex: 'delivery_url',
      key: 'delivery_url',
      ellipsis: true,
    },
    { title: '状态', dataIndex: 'status', key: 'status', width: 80 },
    {
      title: '创建时间',
      dataIndex: 'date_created',
      key: 'date_created',
      valueType: 'dateTime',
    },
    {
      title: '更新时间',
      dataIndex: 'date_modified',
      key: 'date_modified',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            style={{ padding: 0 }}
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除吗？"
            onConfirm={async () => {
              if (record.id) {
                try {
                  const response = await siteapicontrollerDeletewebhook({
                    siteId,
                    id: String(record.id),
                  });
                  if (response.success) {
                    message.success('删除成功');
                    actionRef.current?.reload();
                  } else {
                    message.error('删除失败');
                  }
                } catch (error) {
                  message.error('删除失败');
                }
              }
            }}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <>
      <ProCard>
        <ProTable<API.UnifiedWebhookDTO>
          columns={columns}
          actionRef={actionRef}
          request={async (params) => {
            try {
              const response = await siteapicontrollerGetwebhooks({
                ...params,
                siteId,
                page: params.current,
                per_page: params.pageSize,
              });
              // 确保 response.data 存在
              if (!response || !response.data) {
                return {
                  data: [],
                  success: true,
                  total: 0,
                };
              }
              // 确保 response.data.items 是数组
              const items = Array.isArray(response.data.items)
                ? response.data.items
                : [];
              // 确保每个 item 有有效的 id
              const processedItems = items.map((item, index) => ({
                ...item,
                // 如果 id 是对象，转换为字符串，否则使用索引作为后备
                id:
                  typeof item.id === 'object'
                    ? JSON.stringify(item.id)
                    : item.id || index,
              }));
              return {
                data: processedItems,
                success: true,
                total: Number(response.data.total) || 0,
              };
            } catch (error) {
              console.error('获取webhooks失败:', error);
              return {
                data: [],
                success: true,
                total: 0,
              };
            }
          }}
          rowKey="id"
          search={{
            labelWidth: 'auto',
          }}
          headerTitle="Webhooks列表"
          toolBarRender={() => [
            <Button type="primary" onClick={showCreateModal}>
              新建Webhook
            </Button>,
          ]}
        />
      </ProCard>

      {/* Webhook编辑/新建模态框 */}
      <Modal
        title={isEditMode ? '编辑Webhook' : '新建Webhook'}
        open={isModalVisible}
        onCancel={handleCancel}
        footer={[
          <Button key="back" onClick={handleCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleSubmit}>
            {isEditMode ? '更新' : '创建'}
          </Button>,
        ]}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            status: 'active',
          }}
        >
          <Form.Item
            name="name"
            label="名称"
            rules={[
              { required: true, message: '请输入webhook名称' },
              { max: 100, message: '名称不能超过100个字符' },
            ]}
          >
            <Input placeholder="请输入webhook名称" />
          </Form.Item>

          <Form.Item
            name="topic"
            label="主题"
            rules={[{ required: true, message: '请选择webhook主题' }]}
          >
            <Select
              placeholder="请选择webhook主题"
              options={webhookTopics}
              allowClear
            />
          </Form.Item>

          <Form.Item
            name="delivery_url"
            label="回调URL"
            rules={[
              { required: true, message: '请输入回调URL' },
              { type: 'url', message: '请输入有效的URL' },
            ]}
          >
            <Input placeholder="请输入回调URL，如:https://example.com/webhook" />
          </Form.Item>

          <Form.Item
            name="secret"
            label="密钥(可选)"
            rules={[{ max: 255, message: '密钥不能超过255个字符' }]}
          >
            <Input placeholder="请输入密钥，用于验证webhook请求" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择webhook状态' }]}
          >
            <Select placeholder="请选择webhook状态" options={webhookStatuses} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default WebhooksPage;
