import React, { useEffect, useState } from 'react';
import { Button, Table, Tag, message } from 'antd';
import { PlusOutlined, CheckCircleOutlined, ClockCircleOutlined, CiCircleOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

// 授权数据类型
interface AuthorizationData {
  id: string;
  status: string;
  description: string;
}

// 状态配置
const statusConfig = {
  active: { label: '已授权', color: 'green', icon: CheckCircleOutlined },
  pending: { label: '待授权', color: 'gold', icon: ClockCircleOutlined },
  expired: { label: '已过期', color: 'red', icon: CiCircleOutlined },
  revoked: { label: '已撤销', color: 'gray', icon: CiCircleOutlined },
};

interface ApiResponse {
  code: number;
  message: string;
  data: AuthorizationData[];
}

// 模拟授权列表接口
const mockApiResponse: ApiResponse = {
  code: 200,
  message: 'success',
  data: [
    { id: '1867060028363785', status: 'active', description: '用户张三的API授权' },
    { id: '1867059757929740', status: 'pending', description: '用户李四的API授权' },
    { id: '1867059808785418', status: 'active', description: '用户王五的API授权' },
    { id: '1867060028363786', status: 'expired', description: '用户赵六的API授权' },
    { id: '1867060028363787', status: 'revoked', description: '用户钱七的API授权' },
  ],
};

// 模拟调用接口 /api/admin/user-oauth-apps/list
const fetchAuthorizationList = async (): Promise<ApiResponse> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(mockApiResponse);
    }, 800);
  });
};

const AuthorizationPage: React.FC = () => {
  const navigate = useNavigate();
  const [authorizations, setAuthorizations] = useState<AuthorizationData[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [listLoading, setListLoading] = useState(false);

  // 页面初始化时获取授权列表
  useEffect(() => {
    const loadData = async () => {
      setListLoading(true);
      try {
        const response = await fetchAuthorizationList();
        if (response.code === 200) {
          setAuthorizations(response.data);
        } else {
          message.error(response.message);
        }
      } catch (error) {
        message.error('获取授权列表失败');
      } finally {
        setListLoading(false);
      }
    };
    loadData();
  }, []);

  // 状态标签渲染
  const renderStatus = (status: string) => {
    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.expired;
    const Icon = config.icon;
    return (
      <Tag color={config.color} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
        <Icon size={14} />
        {config.label}
      </Tag>
    );
  };

  // 跳转到消耗记录页面
  const handleGoToConsume = () => {
    navigate('/consume');
  };

  // 处理点击授权按钮
  const handleAuthorize = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择需要授权的记录');
      return;
    }
    setLoading(true);
    // 模拟授权操作
    setTimeout(() => {
      setAuthorizations(prev =>
        prev.map(item =>
          selectedRowKeys.includes(item.id) ? { ...item, status: 'active' } : item
        )
      );
      setSelectedRowKeys([]);
      setLoading(false);
      message.success(`成功授权 ${selectedRowKeys.length} 条记录`);
    }, 800);
  };

  // 表格列配置
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (text: number) => <span style={{ color: '#94a3b8' }}>{text}</span>,
    },
    {
      title: '授权ID',
      dataIndex: 'id',
      key: 'id',
      ellipsis: true,
      render: (text: string) => (
        <span style={{ fontWeight: 500, color: '#1e293b' }}>{text}</span>
      ),
    },
    {
      title: '授权状态',
      dataIndex: 'status',
      key: 'status',
      width: 140,
      render: (text: string) => renderStatus(text),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: 120,
      render: (_: any, record: AuthorizationData) => (
        <Button
          type="primary"
          size="small"
          style={{
            borderRadius: 8,
            border: 'none',
          }}
          onClick={handleGoToConsume}
        >
          查看消耗
        </Button>
      ),
    }
  ];

  const tableData = authorizations.map((item, index) => ({
    ...item,
    index: index + 1,
    key: item.id,
  }));

  return (
    <div style={{ padding: 24, minHeight: '94vh', background: '#f8fafc' }}>
      {/* 页面标题 */}
      <div style={{ marginBottom: 20 }}>
        <h1 style={{ fontSize: 24, fontWeight: 600, color: '#1e293b', marginBottom: 8 }}>
          授权管理
        </h1>
      </div>

      {/* 操作栏 */}
      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12, marginBottom: 16 }}>
        <Button
          type="primary"
          size="large"
          icon={<PlusOutlined />}
          onClick={handleAuthorize}
          loading={loading}
          style={{
            height: 40,
            padding: '0 24px',
            borderRadius: 8,
            fontSize: 14,
            fontWeight: 500,
          }}
        >
          点击授权
        </Button>
      </div>

      {/* 表格 */}
      <div style={{ background: '#fff', borderRadius: 12, boxShadow: '0 1px 3px rgba(0,0,0,0.05)' }}>
        <Table
          dataSource={tableData}
          columns={columns}
          loading={listLoading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          rowKey="id"
          bordered={false}
          style={{ padding: 16 }}
          scroll={{ x: 'max-content' }}
        />
      </div>
    </div>
  );
};

export default AuthorizationPage;
