import * as React from 'react';
import { Table, TableColumnsType, Button, Space, Modal, Form, Input, message } from 'antd';
import { DownloadOutlined, PlusOutlined, FileTextOutlined } from '@ant-design/icons';
import Search from './components/Search';
import ApiDoc from './components/ApiDoc';
import dayjs from 'dayjs';
import './style.scss';
import { apis } from '@/apis';

interface Record {
    id: string;
    name: string;
    apiKey: string;
    createTime: string;
    [key: string]: any;
}

const ApiKeyList: React.FC = () => {
    const [listLoading, setListLoading] = React.useState(false);
    const [list, setList] = React.useState<Record[]>([]);
    const [page, setPage] = React.useState({
        pageNum: 1,
        pageSize: 10,
        total: 0,
    });

    // API 文档弹窗
    const [apiDocOpen, setApiDocOpen] = React.useState(false);

    // 创建弹窗相关
    const [createModalOpen, setCreateModalOpen] = React.useState(false);
    const [createLoading, setCreateLoading] = React.useState(false);
    const [createForm] = Form.useForm();

    const fetchApiKeyList = React.useCallback(async () => {
        setListLoading(true);
        try {
            // TODO: 调用 API 获取数据
            setList([]);
        } catch (error) {
            console.error('获取 API Key 列表失败:', error);
        } finally {
            setListLoading(false);
        }
    }, []);

    React.useEffect(() => {
        fetchApiKeyList();
    }, [fetchApiKeyList]);

    // 处理创建 API Key
    const handleCreateApiKey = async () => {
        try {
            const values = await createForm.validateFields();
            setCreateLoading(true);
            const res = await apis.createApiKey({
                name: values.name,
                remark: values.remark,
            });

            if (res.code === 200) {
                message.success('创建成功');
                setCreateModalOpen(false);
                createForm.resetFields();
                fetchApiKeyList();

                // 如果有返回 apiKey，提示用户保存
                if (res.data?.apiKey) {
                    Modal.success({
                        title: 'API Key 创建成功',
                        content: (
                            <div>
                                <p style={{ marginBottom: 8 }}>请妥善保存此密钥，关闭后将无法查看：</p>
                                <Input
                                    value={res.data.apiKey}
                                    readOnly
                                    style={{ marginBottom: 8 }}
                                />
                                <p style={{ color: '#ff4d4f', fontSize: 12 }}>
                                    ⚠️ 此密钥仅显示一次，请务必备份保存！
                                </p>
                            </div>
                        ),
                        width: 500,
                    });
                }
            }
        } catch (error: any) {
            console.error('创建 API Key 失败:', error);
            if (error?.msg) {
                message.error(error.msg);
            }
        } finally {
            setCreateLoading(false);
        }
    };

    // 打开创建弹窗
    const handleOpenCreateModal = () => {
        createForm.resetFields();
        setCreateModalOpen(true);
    };

    const columns: TableColumnsType<Record> = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: 'API Key',
            dataIndex: 'apiKey',
            key: 'apiKey',
            ellipsis: true,
            render: (text) => (
                <span style={{ fontFamily: 'monospace', fontSize: 12 }}>{text}</span>
            ),
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            render: (_text, record) => (
                <Space>
                    <Button
                        type="link"
                        size="small"
                        danger
                        onClick={() => handleDeleteApiKey(record)}
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    // 删除 API Key
    const handleDeleteApiKey = async (record: Record) => {
        Modal.confirm({
            title: '确认删除',
            content: `确定要删除 API Key "${record.name}" 吗？`,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                try {
                    const res = await apis.deleteApiKey(record.id);
                    if (res.code === 200) {
                        message.success('删除成功');
                        fetchApiKeyList();
                    }
                } catch (error: any) {
                    message.error(error?.msg || '删除失败');
                }
            },
        });
    };

    return (
        <div className="page-container">
            {/* 标题区域 */}
            <div className="list-header">
                <div className='list-header-title'>
                    <h1>API Key 管理</h1>
                    <p>管理和使用 API Key</p>
                </div>
                <div className='list-header-actions'>
                    <Button
                        icon={<FileTextOutlined />}
                        onClick={() => setApiDocOpen(true)}
                        style={{ marginRight: 8 }}
                    >
                        API 文档
                    </Button>
                    <Button
                        type='primary'
                        icon={<PlusOutlined />}
                        onClick={handleOpenCreateModal}
                    >
                        创建
                    </Button>
                </div>
            </div>

            {/* 搜索 + 表格区域 - 共用一个 content-section */}
            <div className="content-section">
                {/* 搜索区域 */}
                <div style={{ marginBottom: 16 }}>
                    <Search />
                </div>

                {/* 表格区域 */}
                <Table
                    rowKey="id"
                    columns={columns}
                    dataSource={list}
                    loading={listLoading}
                    pagination={{
                        current: page.pageNum,
                        pageSize: page.pageSize,
                        total: page.total,
                        onChange: (pageNum, pageSize) => {
                            setPage({ ...page, pageNum, pageSize });
                            fetchApiKeyList();
                        },
                    }}
                />
            </div>

            {/* 创建 API Key 弹窗 */}
            <Modal
                title="创建 API Key"
                open={createModalOpen}
                onOk={handleCreateApiKey}
                onCancel={() => setCreateModalOpen(false)}
                confirmLoading={createLoading}
                okText="创建"
                cancelText="取消"
                width={500}
            >
                <Form form={createForm} layout="vertical">
                    <Form.Item
                        label="名称"
                        name="name"
                        rules={[{ required: true, message: '请输入名称' }]}
                    >
                        <Input placeholder="请输入 API Key 名称" />
                    </Form.Item>
                    <Form.Item
                        label="备注"
                        name="remark"
                    >
                        <Input.TextArea
                            rows={3}
                            placeholder="请输入备注（可选）"
                        />
                    </Form.Item>
                </Form>
            </Modal>

            {/* API 文档抽屉 */}
            <ApiDoc open={apiDocOpen} onClose={() => setApiDocOpen(false)} />
        </div>
    );
};

export default ApiKeyList;
