import { useState, useEffect } from 'react';
import { useIntl } from '@umijs/max';
import { PageContainer, ProCard, ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { Button, Row, Col, Typography, Alert, Space, Tag, Tooltip } from 'antd';
import { ReloadOutlined, TeamOutlined } from '@ant-design/icons';
import { formatUnits } from 'viem';
import { useChainId } from 'wagmi';
import { getDecimals, getBlockExplorer } from '@/config/contracts';

const { Text, Link } = Typography;

interface Holder {
  id: number;
  holder_address: string;
  token_type: string;
  token_address: string;
  balance: string;
  first_seen: number;
  last_updated: number;
}

interface Stats {
  token_type: string;
  holder_count: number;
  total_balance: number;
}

const API_BASE_URL = '/api';

export default function HoldersPage() {
  const intl = useIntl();
  const chainId = useChainId();
  const TOKEN_DECIMALS = getDecimals(chainId);
  const blockExplorer = getBlockExplorer(chainId);

  const [selectedType, setSelectedType] = useState<string>('YT-A');
  const [holders, setHolders] = useState<Holder[]>([]);
  const [stats, setStats] = useState<Stats[]>([]);
  const [loading, setLoading] = useState(false);
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null);
  const [error, setError] = useState<string | null>(null);

  const tokenTypes = ['YT-A', 'YT-B', 'YT-C', 'ytLP', 'Lending'];

  // 获取统计数据
  const fetchStats = async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/holders/stats`);
      if (!response.ok) {
        console.warn('Stats API returned non-OK status:', response.status);
        setStats([]);
        return;
      }

      const data = await response.json();
      console.log('📊 [Holders] Stats API 原始返回:', data);

      if (data.success && data.data !== null && Array.isArray(data.data)) {
        setStats(data.data);
      } else if (data.success && data.data === null) {
        console.warn('⚠️ [Holders] Stats 返回 null，设置为空数组');
        setStats([]);
      } else {
        console.warn('❌ [Holders] Invalid stats data format:', data);
        setStats([]);
      }
    } catch (err) {
      console.error('Failed to fetch stats:', err);
      setStats([]); // 出错时返回空数组
    }
  };

  // 获取持有者数据
  const fetchHolders = async (type: string) => {
    console.log(`🔍 [Holders] 开始获取持有者数据 - Token类型: ${type}`);
    setLoading(true);
    setError(null);

    try {
      const url = `${API_BASE_URL}/holders/${type}`;
      console.log(`📡 [Holders] 请求 URL: ${url}`);

      const response = await fetch(url);
      console.log(`📥 [Holders] API 响应状态: ${response.status}`);

      if (!response.ok) {
        console.warn(`⚠️ [Holders] API 返回非 OK 状态 ${response.status} for ${type}`);
        setHolders([]);
        setError(`Failed to load ${type} holders (Status: ${response.status})`);
        setLastUpdate(new Date());
        return;
      }

      const data = await response.json();
      console.log(`📊 [Holders] API 返回数据:`, {
        success: data.success,
        dataLength: data.data?.length || 0,
        sampleData: data.data?.slice(0, 2)
      });

      if (data.success && Array.isArray(data.data)) {
        console.log(`✅ [Holders] 成功加载 ${data.data.length} 个持有者`);
        setHolders(data.data);
        setLastUpdate(new Date());
        // 清除之前的错误信息
        if (error) setError(null);
      } else {
        console.error(`❌ [Holders] 数据格式无效:`, data);
        setError(data.error || 'Invalid data format');
        setHolders([]);
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      console.error('❌ [Holders] 获取持有者失败:', err);
      setError(`Network error: ${errorMessage}`);
      setHolders([]);
    } finally {
      setLoading(false);
    }
  };

  // 手动触发更新
  const triggerUpdate = async () => {
    setLoading(true);
    setError(null);

    try {
      const response = await fetch(`${API_BASE_URL}/holders/update`, {
        method: 'POST'
      });

      if (!response.ok) {
        setError(`Update failed (Status: ${response.status})`);
        setLoading(false);
        return;
      }

      const data = await response.json();
      if (data.success) {
        // 等待后端更新完成（5秒）
        setTimeout(async () => {
          try {
            await Promise.all([
              fetchHolders(selectedType),
              fetchStats()
            ]);
          } catch (err) {
            const errorMessage = err instanceof Error ? err.message : 'Unknown error';
            setError(`Failed to refresh data: ${errorMessage}`);
          } finally {
            setLoading(false);
          }
        }, 5000);
      } else {
        setError(data.error || 'Update request failed');
        setLoading(false);
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      setError(`Failed to trigger update: ${errorMessage}`);
      setLoading(false);
    }
  };

  // 初始加载和类型切换时获取数据
  useEffect(() => {
    fetchHolders(selectedType);
  }, [selectedType]);

  // 初始加载统计数据
  useEffect(() => {
    fetchStats();
    // 每30秒刷新一次统计
    const interval = setInterval(fetchStats, 30000);
    return () => clearInterval(interval);
  }, []);

  // 格式化地址（显示前6位和后4位）
  const formatAddress = (address: string) => {
    return `${address.slice(0, 6)}...${address.slice(-4)}`;
  };

  // 格式化余额
  const formatBalance = (balance: string) => {
    try {
      const formatted = formatUnits(BigInt(balance), TOKEN_DECIMALS.YT);
      return parseFloat(formatted).toLocaleString(undefined, {
        minimumFractionDigits: 2,
        maximumFractionDigits: 6
      });
    } catch {
      return balance;
    }
  };

  // 计算持有时长
  const formatHoldingTime = (firstSeen: number) => {
    const now = Math.floor(Date.now() / 1000);
    const duration = now - firstSeen;

    const days = Math.floor(duration / 86400);
    const hours = Math.floor((duration % 86400) / 3600);
    const minutes = Math.floor((duration % 3600) / 60);

    if (days > 0) return `${days}${intl.formatMessage({ id: 'pages.holders.days' })} ${hours}${intl.formatMessage({ id: 'pages.holders.hours' })}`;
    if (hours > 0) return `${hours}${intl.formatMessage({ id: 'pages.holders.hours' })} ${minutes}${intl.formatMessage({ id: 'pages.holders.minutes' })}`;
    return `${minutes}${intl.formatMessage({ id: 'pages.holders.minutes' })}`;
  };

  // 获取某类型的统计数据
  const getStatForType = (type: string) => {
    return stats?.find(s => s.token_type === type) || null;
  };

  // ProTable 列定义
  const columns: ProColumns<Holder>[] = [
    {
      title: intl.formatMessage({ id: 'pages.holders.rank' }),
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 80,
      search: false,
      fixed: 'left',
    },
    {
      title: intl.formatMessage({ id: 'pages.holders.address' }),
      dataIndex: 'holder_address',
      width: 220,
      ellipsis: true,
      fieldProps: {
        placeholder: '搜索地址 (0x...)',
      },
      render: (_, record) => (
        <Tooltip title={record.holder_address}>
          <Text copyable={{ text: record.holder_address }}>
            <Link
              href={`${blockExplorer}/address/${record.holder_address}`}
              target="_blank"
            >
              {formatAddress(record.holder_address)}
            </Link>
          </Text>
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'pages.holders.balance' }),
      dataIndex: 'balance',
      width: 200,
      search: false,
      render: (_, record) => (
        <Text strong style={{ fontFamily: 'monospace' }}>
          {formatBalance(record.balance)}
        </Text>
      ),
      sorter: (a, b) => {
        try {
          return BigInt(a.balance) > BigInt(b.balance) ? 1 : -1;
        } catch {
          return 0;
        }
      },
      defaultSortOrder: 'descend',
    },
    {
      title: intl.formatMessage({ id: 'pages.holders.holdingTime' }),
      dataIndex: 'first_seen',
      width: 150,
      search: false,
      render: (_, record) => formatHoldingTime(record.first_seen),
      sorter: (a, b) => a.first_seen - b.first_seen,
    },
    {
      title: intl.formatMessage({ id: 'pages.holders.lastUpdated' }),
      dataIndex: 'last_updated',
      width: 200,
      valueType: 'dateTime',
      search: false,
      render: (_, record) => new Date(record.last_updated * 1000).toLocaleString(),
      sorter: (a, b) => a.last_updated - b.last_updated,
    },
  ];

  return (
    <PageContainer
      title={intl.formatMessage({ id: 'pages.holders.title' })}
      extra={[
        <Space key="actions">
          {lastUpdate && (
            <Text type="secondary">
              {intl.formatMessage({ id: 'pages.holders.lastUpdate' })}: {lastUpdate.toLocaleTimeString()}
            </Text>
          )}
          <Button
            type="primary"
            icon={<ReloadOutlined />}
            onClick={triggerUpdate}
            loading={loading}
          >
            {intl.formatMessage({ id: 'pages.holders.updateNow' })}
          </Button>
        </Space>
      ]}
    >
      <Space direction="vertical" size="large" style={{ width: '100%' }}>

        {/* 错误提示 */}
        {error && (
          <Alert
            message={error}
            type="error"
            closable
            onClose={() => setError(null)}
          />
        )}

        {/* 统计卡片 */}
        <Row gutter={[16, 16]}>
          {tokenTypes.map(type => {
            const stat = getStatForType(type);
            const isActive = selectedType === type;
            return (
              <Col xs={24} sm={12} md={8} lg={4} key={type}>
                <ProCard
                  hoverable
                  bordered
                  style={{
                    cursor: 'pointer',
                    borderColor: isActive ? '#1890ff' : undefined,
                    background: isActive ? '#e6f7ff' : undefined,
                  }}
                  onClick={() => setSelectedType(type)}
                >
                  <Space direction="vertical" size="small" style={{ width: '100%' }}>
                    <Text strong style={{ fontSize: 16 }}>{type}</Text>
                    <Space>
                      <TeamOutlined style={{ color: '#1890ff' }} />
                      <Text type="secondary">
                        {stat?.holder_count || 0} {intl.formatMessage({ id: 'pages.holders.holders' })}
                      </Text>
                    </Space>
                    {isActive && <Tag color="blue">{intl.formatMessage({ id: 'pages.common.balance' })}</Tag>}
                  </Space>
                </ProCard>
              </Col>
            );
          })}
        </Row>

        {/* 持有者列表 */}
        <ProCard
          title={
            <Space>
              <Text strong>{selectedType} {intl.formatMessage({ id: 'pages.holders.holdersList' })}</Text>
              <Tag color="blue">
                {intl.formatMessage({ id: 'pages.holders.total' })}: {holders.length}
              </Tag>
            </Space>
          }
        >
          <ProTable<Holder>
            columns={columns}
            dataSource={holders}
            rowKey="id"
            search={{
              labelWidth: 'auto',
              defaultCollapsed: false,
              optionRender: (searchConfig, formProps, dom) => [
                ...dom.reverse(),
              ],
            }}
            loading={loading}
            options={{
              reload: () => {
                console.log('🔄 [Holders] 用户点击刷新按钮');
                fetchHolders(selectedType);
              },
              density: true,
              fullScreen: true,
              setting: true,
            }}
            pagination={{
              pageSize: 20,
              showSizeChanger: true,
              showQuickJumper: true,
              pageSizeOptions: ['10', '20', '50', '100'],
              onChange: (page, pageSize) => {
                console.log(`📄 [Holders] 分页变化 - 页码: ${page}, 每页: ${pageSize}`);
              },
            }}
            locale={{
              emptyText: intl.formatMessage({ id: 'pages.holders.noHolders' }),
            }}
            toolbar={{
              title: (
                <Space>
                  <span>共 {holders.length} 个持有者</span>
                </Space>
              ),
            }}
            onSubmit={(params) => {
              console.log('🔎 [Holders] ProTable 搜索提交:', params);
            }}
            onReset={() => {
              console.log('🔄 [Holders] ProTable 重置搜索');
            }}
          />
        </ProCard>
      </Space>
    </PageContainer>
  );
}
