import {
  CopyOutlined,
  DeleteOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
  KeyOutlined,
  MinusCircleOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import {
  App,
  Button,
  Card,
  Col,
  Empty,
  Form,
  Input,
  Modal,
  Popconfirm,
  Row,
  Space,
  Spin,
  Table,
  Tag,
  Tooltip,
  Typography,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import React, { useEffect, useState } from 'react';
import { createApiKey, getMyApiKeys, revokeApiKey } from '@/services/auth/api';

const { Text, Paragraph } = Typography;

const ApiKeysView: React.FC = () => {
  const intl = useIntl();
  const { message, modal } = App.useApp();

  const [loading, setLoading] = useState(true);
  const [apiKeys, setApiKeys] = useState<AuthAPI.ApiKeyInfo[]>([]);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [createLoading, setCreateLoading] = useState(false);
  const [newKeyInfo, setNewKeyInfo] = useState<AuthAPI.CreateApiKeyData | null>(
    null,
  );
  const [showSecret, setShowSecret] = useState(false);
  const [form] = Form.useForm();

  // 加载 API Key 列表
  const loadApiKeys = async () => {
    setLoading(true);
    try {
      const response = await getMyApiKeys();
      if (response.success && response.data) {
        setApiKeys(response.data.keys || []);
      } else {
        message.error(
          response.message ||
            intl.formatMessage({
              id: 'pages.account.settings.apiKey.loadFailed',
              defaultMessage: '加载失败',
            }),
        );
      }
    } catch (error: any) {
      message.error(
        error?.message ||
          intl.formatMessage({
            id: 'pages.account.settings.apiKey.loadFailed',
            defaultMessage: '加载失败',
          }),
      );
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadApiKeys();
  }, []);

  // 创建 API Key
  const handleCreate = async (values: {
    name: string;
    ipWhitelist?: string[];
  }) => {
    setCreateLoading(true);
    try {
      // 过滤掉空的 IP 地址
      const ipWhitelist =
        values.ipWhitelist?.filter((ip) => ip && ip.trim()) || [];
      const response = await createApiKey({
        name: values.name,
        ipWhitelist: ipWhitelist.length > 0 ? ipWhitelist : undefined,
      });

      if (response.success && response.data) {
        setNewKeyInfo(response.data);
        message.success(
          intl.formatMessage({
            id: 'pages.account.settings.apiKey.createSuccess',
            defaultMessage: '创建成功',
          }),
        );
        loadApiKeys();
      } else {
        message.error(
          response.message ||
            intl.formatMessage({
              id: 'pages.account.settings.apiKey.createFailed',
              defaultMessage: '创建失败',
            }),
        );
      }
    } catch (error: any) {
      message.error(
        error?.message ||
          intl.formatMessage({
            id: 'pages.account.settings.apiKey.createFailed',
            defaultMessage: '创建失败',
          }),
      );
    } finally {
      setCreateLoading(false);
    }
  };

  // 撤销 API Key
  const handleRevoke = async (id: string) => {
    try {
      const response = await revokeApiKey(id);
      if (response.success) {
        message.success(
          intl.formatMessage({
            id: 'pages.account.settings.apiKey.revokeSuccess',
            defaultMessage: '撤销成功',
          }),
        );
        loadApiKeys();
      } else {
        message.error(
          response.message ||
            intl.formatMessage({
              id: 'pages.account.settings.apiKey.revokeFailed',
              defaultMessage: '撤销失败',
            }),
        );
      }
    } catch (error: any) {
      message.error(
        error?.message ||
          intl.formatMessage({
            id: 'pages.account.settings.apiKey.revokeFailed',
            defaultMessage: '撤销失败',
          }),
      );
    }
  };

  // 复制到剪贴板
  const copyToClipboard = async (text: string) => {
    try {
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(text);
      } else {
        // Fallback for non-HTTPS or unsupported browsers
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-9999px';
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
      }
      message.success(
        intl.formatMessage({
          id: 'pages.account.settings.apiKey.copied',
          defaultMessage: '已复制',
        }),
      );
    } catch {
      message.error(
        intl.formatMessage({
          id: 'pages.assets.copyFailed',
          defaultMessage: '复制失败',
        }),
      );
    }
  };

  // 关闭创建弹窗
  const handleCloseCreateModal = () => {
    setCreateModalVisible(false);
    setNewKeyInfo(null);
    setShowSecret(false);
    form.resetFields();
  };

  const columns: ColumnsType<AuthAPI.ApiKeyInfo> = [
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.apiKey.column.name',
        defaultMessage: '名称',
      }),
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: 'API Key',
      dataIndex: 'apiKey',
      key: 'apiKey',
      width: 200,
      render: (text: string) => (
        <Space>
          <Text code>{text}</Text>
          <Tooltip
            title={intl.formatMessage({
              id: 'pages.account.settings.apiKey.copy',
              defaultMessage: '复制',
            })}
          >
            <CopyOutlined
              style={{ cursor: 'pointer' }}
              onClick={() => copyToClipboard(text)}
            />
          </Tooltip>
        </Space>
      ),
    },
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.apiKey.column.ipWhitelist',
        defaultMessage: 'IP 白名单',
      }),
      dataIndex: 'ipWhitelist',
      key: 'ipWhitelist',
      width: 200,
      render: (ipWhitelist: string[]) =>
        ipWhitelist && ipWhitelist.length > 0 ? (
          <Space wrap>
            {ipWhitelist.map((ip) => (
              <Tag key={ip}>{ip}</Tag>
            ))}
          </Space>
        ) : (
          <Text type="secondary">
            {intl.formatMessage({
              id: 'pages.account.settings.apiKey.ipWhitelist.all',
              defaultMessage: '不限制',
            })}
          </Text>
        ),
    },
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.apiKey.column.status',
        defaultMessage: '状态',
      }),
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={status === 'active' ? 'success' : 'error'}>
          {status === 'active'
            ? intl.formatMessage({
                id: 'pages.account.settings.apiKey.status.active',
                defaultMessage: '有效',
              })
            : intl.formatMessage({
                id: 'pages.account.settings.apiKey.status.revoked',
                defaultMessage: '已撤销',
              })}
        </Tag>
      ),
    },
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.apiKey.column.lastUsed',
        defaultMessage: '最后使用',
      }),
      dataIndex: 'lastUsedAt',
      key: 'lastUsedAt',
      width: 180,
      render: (text: string) => (text ? new Date(text).toLocaleString() : '-'),
    },
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.apiKey.column.action',
        defaultMessage: '操作',
      }),
      key: 'action',
      width: 100,
      render: (_, record) =>
        record.status === 'active' ? (
          <Popconfirm
            title={intl.formatMessage({
              id: 'pages.account.settings.apiKey.revokeConfirm',
              defaultMessage: '确定要撤销此 API Key 吗？',
            })}
            onConfirm={() => handleRevoke(record.id)}
            okText={intl.formatMessage({
              id: 'pages.account.settings.apiKey.confirm',
              defaultMessage: '确定',
            })}
            cancelText={intl.formatMessage({
              id: 'pages.account.settings.apiKey.cancel',
              defaultMessage: '取消',
            })}
          >
            <Button type="link" danger size="small" icon={<DeleteOutlined />}>
              {intl.formatMessage({
                id: 'pages.account.settings.apiKey.revoke',
                defaultMessage: '撤销',
              })}
            </Button>
          </Popconfirm>
        ) : (
          <Text type="secondary">-</Text>
        ),
    },
  ];

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: 40 }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <>
      <Card
        title={
          <Space>
            <KeyOutlined />
            <span>
              {intl.formatMessage({
                id: 'pages.account.settings.apiKey.title',
                defaultMessage: 'API Key 管理',
              })}
            </span>
          </Space>
        }
        extra={
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setCreateModalVisible(true)}
          >
            {intl.formatMessage({
              id: 'pages.account.settings.apiKey.create',
              defaultMessage: '创建 API Key',
            })}
          </Button>
        }
      >
        <Paragraph type="secondary" style={{ marginBottom: 16 }}>
          {intl.formatMessage({
            id: 'pages.account.settings.apiKey.description',
            defaultMessage:
              'API Key 用于程序化访问您的账户。每个用户最多创建 5 个有效的 Key。请妥善保管您的 Secret，它只在创建时显示一次。',
          })}
        </Paragraph>

        {apiKeys.length === 0 ? (
          <Empty
            description={intl.formatMessage({
              id: 'pages.account.settings.apiKey.empty',
              defaultMessage: '暂无 API Key',
            })}
          />
        ) : (
          <Table
            columns={columns}
            dataSource={apiKeys}
            rowKey="id"
            pagination={false}
            scroll={{ x: 900 }}
          />
        )}
      </Card>

      {/* 创建 API Key 弹窗 */}
      <Modal
        title={
          newKeyInfo
            ? intl.formatMessage({
                id: 'pages.account.settings.apiKey.createSuccess',
                defaultMessage: '创建成功',
              })
            : intl.formatMessage({
                id: 'pages.account.settings.apiKey.create',
                defaultMessage: '创建 API Key',
              })
        }
        open={createModalVisible}
        onCancel={handleCloseCreateModal}
        footer={
          newKeyInfo
            ? [
                <Button
                  key="close"
                  type="primary"
                  onClick={handleCloseCreateModal}
                >
                  {intl.formatMessage({
                    id: 'pages.account.settings.apiKey.understood',
                    defaultMessage: '我已保存，关闭',
                  })}
                </Button>,
              ]
            : undefined
        }
        onOk={() => form.submit()}
        confirmLoading={createLoading}
        okText={intl.formatMessage({
          id: 'pages.account.settings.apiKey.confirm',
          defaultMessage: '确定',
        })}
        cancelText={intl.formatMessage({
          id: 'pages.account.settings.apiKey.cancel',
          defaultMessage: '取消',
        })}
        width={500}
        destroyOnHidden
      >
        {newKeyInfo ? (
          <div>
            <Paragraph type="warning" style={{ marginBottom: 16 }}>
              <strong>
                {intl.formatMessage({
                  id: 'pages.account.settings.apiKey.secretWarning',
                  defaultMessage: '请立即保存以下信息，Secret 只显示一次！',
                })}
              </strong>
            </Paragraph>

            <Card size="small" style={{ marginBottom: 16 }}>
              <Row gutter={[0, 12]}>
                <Col span={24}>
                  <Text type="secondary">API Key:</Text>
                  <div
                    style={{ display: 'flex', alignItems: 'center', gap: 8 }}
                  >
                    <Text code copyable>
                      {newKeyInfo.apiKey}
                    </Text>
                  </div>
                </Col>
                <Col span={24}>
                  <Text type="secondary">Secret:</Text>
                  <div
                    style={{ display: 'flex', alignItems: 'center', gap: 8 }}
                  >
                    <Text code copyable>
                      {showSecret
                        ? newKeyInfo.secret
                        : '••••••••••••••••••••••••'}
                    </Text>
                    <Button
                      type="text"
                      size="small"
                      icon={
                        showSecret ? <EyeInvisibleOutlined /> : <EyeOutlined />
                      }
                      onClick={() => setShowSecret(!showSecret)}
                    />
                  </div>
                </Col>
              </Row>
            </Card>
          </div>
        ) : (
          <Form form={form} onFinish={handleCreate} layout="vertical">
            <Form.Item
              name="name"
              label={intl.formatMessage({
                id: 'pages.account.settings.apiKey.form.name',
                defaultMessage: '名称',
              })}
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'pages.account.settings.apiKey.form.name.required',
                    defaultMessage: '请输入名称',
                  }),
                },
                {
                  max: 50,
                  message: intl.formatMessage({
                    id: 'pages.account.settings.apiKey.form.name.maxLength',
                    defaultMessage: '名称最多50个字符',
                  }),
                },
              ]}
            >
              <Input
                placeholder={intl.formatMessage({
                  id: 'pages.account.settings.apiKey.form.name.placeholder',
                  defaultMessage: '例如：交易机器人',
                })}
              />
            </Form.Item>

            <Form.Item
              label={intl.formatMessage({
                id: 'pages.account.settings.apiKey.form.ipWhitelist',
                defaultMessage: 'IP 白名单（可选）',
              })}
            >
              <Form.List name="ipWhitelist">
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, ...restField }) => (
                      <Space
                        key={key}
                        style={{ display: 'flex', marginBottom: 8 }}
                        align="baseline"
                      >
                        <Form.Item
                          {...restField}
                          name={name}
                          rules={[
                            {
                              pattern:
                                /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
                              message: intl.formatMessage({
                                id: 'pages.account.settings.apiKey.form.ipWhitelist.invalid',
                                defaultMessage: '请输入有效的 IP 地址',
                              }),
                            },
                          ]}
                          style={{ marginBottom: 0 }}
                        >
                          <Input
                            placeholder="192.168.1.1"
                            style={{ width: 200 }}
                          />
                        </Form.Item>
                        <MinusCircleOutlined
                          onClick={() => remove(name)}
                          style={{ color: '#ff4d4f' }}
                        />
                      </Space>
                    ))}
                    <Form.Item style={{ marginBottom: 0 }}>
                      <Button
                        type="dashed"
                        onClick={() => add()}
                        block
                        icon={<PlusOutlined />}
                      >
                        {intl.formatMessage({
                          id: 'pages.account.settings.apiKey.form.ipWhitelist.add',
                          defaultMessage: '添加 IP 地址',
                        })}
                      </Button>
                    </Form.Item>
                  </>
                )}
              </Form.List>
              <Text type="secondary" style={{ fontSize: 12 }}>
                {intl.formatMessage({
                  id: 'pages.account.settings.apiKey.form.ipWhitelist.hint',
                  defaultMessage:
                    '不填写则不限制 IP，填写后仅允许白名单内的 IP 使用此 Key',
                })}
              </Text>
            </Form.Item>
          </Form>
        )}
      </Modal>
    </>
  );
};

export default ApiKeysView;
