import { List, Typography, Tag, Space, Collapse } from 'antd';
import { TrophyOutlined, UserOutlined, CrownOutlined } from '@ant-design/icons';

interface TeamMember {
  id: number;
  score: number;
  user: { id: string; name: string | null; email: string };
}

interface LeaderboardTeam {
  id: string;
  name: string;
  score: number;
  captainUserId: string;
  members: TeamMember[];
}

interface ChallengeLeaderboardProps {
  teams: LeaderboardTeam[];
  myTeamId?: string | null;
}

const MEDAL_COLORS = ['#ffd700', '#c0c0c0', '#cd7f32'];

export default function ChallengeLeaderboard({ teams, myTeamId }: ChallengeLeaderboardProps) {
  if (teams.length === 0) {
    return <Typography.Text type="secondary">No teams yet</Typography.Text>;
  }

  const items = teams.map((team, idx) => ({
    key: team.id,
    label: (
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          width: '100%',
          fontWeight: team.id === myTeamId ? 700 : 400,
          color: team.id === myTeamId ? '#1890ff' : undefined,
        }}
      >
        <Space>
          {idx < 3 ? (
            <TrophyOutlined style={{ color: MEDAL_COLORS[idx], fontSize: 16 }} />
          ) : (
            <span style={{ display: 'inline-block', width: 16, textAlign: 'center', opacity: 0.5 }}>
              {idx + 1}
            </span>
          )}
          <span>{team.name}</span>
          {team.id === myTeamId && <Tag color="blue" style={{ marginLeft: 4 }}>You</Tag>}
        </Space>
        <Space>
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            <UserOutlined /> {team.members.length}
          </Typography.Text>
          <Typography.Text strong>{team.score}</Typography.Text>
        </Space>
      </div>
    ),
    children: (
      <List
        size="small"
        dataSource={team.members}
        renderItem={(m: TeamMember) => (
          <List.Item style={{ padding: '4px 0' }}>
            <Space>
              {m.user.id === team.captainUserId && (
                <CrownOutlined style={{ color: '#faad14' }} />
              )}
              <span>{m.user.name || m.user.email}</span>
            </Space>
            <Typography.Text strong>{m.score}</Typography.Text>
          </List.Item>
        )}
      />
    ),
  }));

  return <Collapse items={items} ghost size="small" />;
}
