import React, { useState, useEffect } from 'react';
import { Card, Tabs, Table, Tag, Statistic, Row, Col, Spin, message, Select, Button, Tooltip, Badge } from 'antd';
import { TrophyOutlined, RiseOutlined, DollarOutlined, PercentageOutlined, CrownOutlined, FireOutlined, StarOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { leaderboardDataSource, LeaderboardEntry, LeaderboardData, MyRank } from '@/services/leaderboardDataSource';

const { TabPane } = Tabs;
const { Option } = Select;

const LeaderboardPage: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [leaderboardData, setLeaderboardData] = useState<LeaderboardData | null>(null);
  const [myRank, setMyRank] = useState<MyRank | null>(null);
  const [period, setPeriod] = useState<'DAILY' | 'WEEKLY' | 'MONTHLY' | 'ALL_TIME'>('MONTHLY');
  const [activeTab, setActiveTab] = useState('revenue');

  useEffect(() => {
    fetchLeaderboardData();
    fetchMyRank();
  }, [period]);

  const fetchLeaderboardData = async () => {
    setLoading(true);
    try {
      const response = await fetch(`/api/v1/leaderboard/all?period=${period}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      const result = await response.json();
      if (result.success) {
        setLeaderboardData(result.data);
      } else {
        message.error(result.message || 'Failed to fetch leaderboard data');
      }
    } catch (error) {
      console.error('Error fetching leaderboard:', error);
      message.error('Failed to fetch leaderboard data');
    } finally {
      setLoading(false);
    }
  };

  const fetchMyRank = async () => {
    try {
      const response = await fetch(`/api/v1/leaderboard/my-rank?period=${period}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      const result = await response.json();
      if (result.success) {
        setMyRank(result.data);
      }
    } catch (error) {
      console.error('Error fetching my rank:', error);
    }
  };

  const getTierColor = (tier: string): string => {
    const colors: Record<string, string> = {
      'DIAMOND': '#b9f2ff',
      'PLATINUM': '#e5e4e2',
      'GOLD': '#ffd700',
      'SILVER': '#c0c0c0',
      'BRONZE': '#cd7f32'
    };
    return colors[tier] || '#default';
  };

  const getTierIcon = (tier: string) => {
    switch (tier) {
      case 'DIAMOND':
        return <CrownOutlined style={{ color: '#b9f2ff' }} />;
      case 'PLATINUM':
        return <StarOutlined style={{ color: '#e5e4e2' }} />;
      case 'GOLD':
        return <TrophyOutlined style={{ color: '#ffd700' }} />;
      case 'SILVER':
        return <StarOutlined style={{ color: '#c0c0c0' }} />;
      default:
        return null;
    }
  };

  const getRankBadge = (rank: number) => {
    if (rank === 1) return <CrownOutlined style={{ fontSize: 24, color: '#ffd700' }} />;
    if (rank === 2) return <TrophyOutlined style={{ fontSize: 20, color: '#c0c0c0' }} />;
    if (rank === 3) return <TrophyOutlined style={{ fontSize: 18, color: '#cd7f32' }} />;
    return <span style={{ fontWeight: 'bold', fontSize: 16 }}>#{rank}</span>;
  };

  const formatValue = (value: number, type: string): string => {
    if (type === 'roi') {
      return `${(value * 100).toFixed(2)}%`;
    }
    if (type === 'growth') {
      return `${(value * 100).toFixed(2)}%`;
    }
    return `$${value.toLocaleString()}`;
  };

  const columns: ColumnsType<LeaderboardEntry> = [
    {
      title: 'Rank',
      dataIndex: 'rank',
      key: 'rank',
      width: 80,
      render: (rank: number) => (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {getRankBadge(rank)}
        </div>
      )
    },
    {
      title: 'Merchant',
      dataIndex: 'tenant_name',
      key: 'tenant_name',
      render: (name: string, record) => (
        <div>
          <div style={{ fontWeight: 500 }}>{name}</div>
          <div style={{ fontSize: 12, color: '#999' }}>{record.shop_name}</div>
        </div>
      )
    },
    {
      title: 'Tier',
      dataIndex: 'tier',
      key: 'tier',
      width: 100,
      render: (tier: string) => (
        <Tag color={getTierColor(tier)} icon={getTierIcon(tier)}>
          {tier}
        </Tag>
      )
    },
    {
      title: activeTab === 'revenue' ? 'Profit' : activeTab === 'roi' ? 'ROI' : 'Growth Rate',
      dataIndex: 'value',
      key: 'value',
      sorter: (a, b) => a.value - b.value,
      render: (value: number) => (
        <span style={{ fontWeight: 'bold', fontSize: 16, color: '#52c41a' }}>
          {formatValue(value, activeTab)}
        </span>
      )
    },
    {
      title: 'Growth',
      dataIndex: 'growth_rate',
      key: 'growth_rate',
      width: 100,
      render: (rate: number) => (
        <span style={{ color: rate >= 0 ? '#52c41a' : '#ff4d4f' }}>
          {rate >= 0 ? <RiseOutlined /> : null} {(rate * 100).toFixed(1)}%
        </span>
      )
    },
    {
      title: 'Verified',
      dataIndex: 'is_verified',
      key: 'is_verified',
      width: 80,
      render: (verified: boolean) => (
        verified ? (
          <Badge status="success" text="Verified" />
        ) : (
          <Badge status="default" text="Pending" />
        )
      )
    }
  ];

  const renderMyRankCard = () => {
    if (!myRank) return null;

    const rankData = myRank[activeTab as keyof MyRank] as { rank: number; percentile: number } | null;

    return (
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={24}>
          <Col span={8}>
            <Statistic
              title="My Revenue Rank"
              value={myRank.revenue?.rank || '-'}
              suffix={myRank.revenue ? `/ ${leaderboardData?.revenue.total || 0}` : ''}
              prefix={<DollarOutlined />}
            />
            {myRank.revenue && (
              <div style={{ marginTop: 8, color: '#999' }}>
                Top {myRank.revenue.percentile.toFixed(1)}%
              </div>
            )}
          </Col>
          <Col span={8}>
            <Statistic
              title="My ROI Rank"
              value={myRank.roi?.rank || '-'}
              suffix={myRank.roi ? `/ ${leaderboardData?.roi.total || 0}` : ''}
              prefix={<PercentageOutlined />}
            />
            {myRank.roi && (
              <div style={{ marginTop: 8, color: '#999' }}>
                Top {myRank.roi.percentile.toFixed(1)}%
              </div>
            )}
          </Col>
          <Col span={8}>
            <Statistic
              title="My Growth Rank"
              value={myRank.growth?.rank || '-'}
              suffix={myRank.growth ? `/ ${leaderboardData?.growth.total || 0}` : ''}
              prefix={<RiseOutlined />}
            />
            {myRank.growth && (
              <div style={{ marginTop: 8, color: '#999' }}>
                Top {myRank.growth.percentile.toFixed(1)}%
              </div>
            )}
          </Col>
        </Row>
      </Card>
    );
  };

  const renderLeaderboardTable = (data: LeaderboardEntry[], type: string) => {
    return (
      <Table
        columns={columns}
        dataSource={data}
        rowKey="tenant_id"
        pagination={{ pageSize: 10 }}
        loading={loading}
        scroll={{ x: 800 }}
      />
    );
  };

  return (
    <div style={{ padding: 24 }}>
      <Card>
        <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <h1 style={{ margin: 0 }}>
              <TrophyOutlined style={{ marginRight: 8, color: '#ffd700' }} />
              Merchant Leaderboard
            </h1>
            <p style={{ color: '#999', margin: '8px 0 0 0' }}>
              See how you compare with other merchants
            </p>
          </div>
          <div>
            <Select
              value={period}
              onChange={(value) => setPeriod(value)}
              style={{ width: 150, marginRight: 16 }}
            >
              <Option value="DAILY">Daily</Option>
              <Option value="WEEKLY">Weekly</Option>
              <Option value="MONTHLY">Monthly</Option>
              <Option value="ALL_TIME">All Time</Option>
            </Select>
            <Button type="primary" onClick={fetchLeaderboardData}>
              Refresh
            </Button>
          </div>
        </div>

        {renderMyRankCard()}

        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane
            tab={
              <span>
                <DollarOutlined />
                Revenue Ranking
              </span>
            }
            key="revenue"
          >
            {leaderboardData && renderLeaderboardTable(leaderboardData.revenue.rankings, 'revenue')}
          </TabPane>
          <TabPane
            tab={
              <span>
                <PercentageOutlined />
                ROI Ranking
              </span>
            }
            key="roi"
          >
            {leaderboardData && renderLeaderboardTable(leaderboardData.roi.rankings, 'roi')}
          </TabPane>
          <TabPane
            tab={
              <span>
                <RiseOutlined />
                Growth Ranking
              </span>
            }
            key="growth"
          >
            {leaderboardData && renderLeaderboardTable(leaderboardData.growth.rankings, 'growth')}
          </TabPane>
        </Tabs>

        {leaderboardData && (
          <div style={{ marginTop: 16, color: '#999', fontSize: 12 }}>
            Last updated: {new Date(leaderboardData.updatedAt).toLocaleString()}
          </div>
        )}
      </Card>

      <Card style={{ marginTop: 16 }}>
        <h3>
          <FireOutlined style={{ marginRight: 8, color: '#ff4d4f' }} />
          TOP 10 Merchants Showcase
        </h3>
        <Row gutter={[16, 16]}>
          {leaderboardData?.revenue.rankings.slice(0, 10).map((entry, index) => (
            <Col span={4} key={entry.tenant_id}>
              <Card
                hoverable
                style={{
                  textAlign: 'center',
                  background: index === 0 ? 'linear-gradient(135deg, #ffd700 0%, #ffecb3 100%)' : undefined
                }}
              >
                <div style={{ fontSize: 24, marginBottom: 8 }}>
                  {getRankBadge(entry.rank)}
                </div>
                <div style={{ fontWeight: 'bold', marginBottom: 4 }}>
                  {entry.tenant_name}
                </div>
                <Tag color={getTierColor(entry.tier)} icon={getTierIcon(entry.tier)}>
                  {entry.tier}
                </Tag>
                <div style={{ marginTop: 8, color: '#52c41a', fontWeight: 'bold' }}>
                  ${entry.value.toLocaleString()}
                </div>
                {entry.is_verified && (
                  <Badge status="success" style={{ marginTop: 4 }} />
                )}
              </Card>
            </Col>
          ))}
        </Row>
      </Card>
    </div>
  );
};

export default LeaderboardPage;
