import { useState, useEffect, useCallback } from 'react';
import { List, Typography, Switch, Space, Spin, Empty } from 'antd';
import { TrophyOutlined, CrownOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import UserAvatar from '@/components/social/UserAvatar';

const { Text } = Typography;

interface LeaderboardEntry {
  rank: number;
  userId: string;
  name: string | null;
  email: string;
  score: number;
}

interface PublicLeaderboardProps {
  type: 'canvass' | 'shifts' | 'campaigns';
  showOptIn?: boolean;
  optedIn?: boolean;
  onOptInChange?: (value: boolean) => void;
}

const SCORE_LABELS: Record<string, string> = {
  canvass: 'doors',
  shifts: 'shifts',
  campaigns: 'campaigns',
};

function getMedalColor(rank: number): string | undefined {
  if (rank === 1) return '#FFD700';
  if (rank === 2) return '#C0C0C0';
  if (rank === 3) return '#CD7F32';
  return undefined;
}

export default function PublicLeaderboard({ type, showOptIn, optedIn, onOptInChange }: PublicLeaderboardProps) {
  const [entries, setEntries] = useState<LeaderboardEntry[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchLeaderboard = useCallback(async () => {
    try {
      setLoading(true);
      const { data } = await api.get('/social/spotlight/leaderboard', {
        params: { type, limit: 10 },
      });
      setEntries(data.leaderboard || []);
    } catch {
      // Silently fail for unauthenticated users
      setEntries([]);
    } finally {
      setLoading(false);
    }
  }, [type]);

  useEffect(() => {
    fetchLeaderboard();
  }, [fetchLeaderboard]);

  if (loading) return <Spin style={{ display: 'block', margin: '24px auto' }} />;

  if (entries.length === 0) {
    return <Empty description="No leaderboard data yet" image={Empty.PRESENTED_IMAGE_SIMPLE} />;
  }

  return (
    <div>
      <List
        dataSource={entries}
        renderItem={(entry) => {
          const medalColor = getMedalColor(entry.rank);
          return (
            <List.Item style={{ padding: '10px 0' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%' }}>
                <div style={{ width: 36, textAlign: 'center', flexShrink: 0 }}>
                  {medalColor ? (
                    <CrownOutlined style={{ fontSize: 22, color: medalColor }} />
                  ) : (
                    <Text strong style={{ fontSize: 16 }}>#{entry.rank}</Text>
                  )}
                </div>
                <UserAvatar
                  userId={entry.userId}
                  name={entry.name}
                  email={entry.email}
                  size={36}
                />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <Text strong ellipsis>
                    {entry.name || entry.email.split('@')[0]}
                  </Text>
                </div>
                <Text style={{ flexShrink: 0 }}>
                  <Text strong>{entry.score}</Text>{' '}
                  <Text type="secondary">{SCORE_LABELS[type]}</Text>
                </Text>
              </div>
            </List.Item>
          );
        }}
      />

      {showOptIn && onOptInChange && (
        <div style={{ marginTop: 16, padding: '12px 0', borderTop: '1px solid rgba(255,255,255,0.1)' }}>
          <Space>
            <TrophyOutlined />
            <Text>Show me on leaderboard</Text>
            <Switch
              checked={optedIn}
              onChange={onOptInChange}
              size="small"
            />
          </Space>
        </div>
      )}
    </div>
  );
}
