/**
 * Leaderboard — team rankings by GCI, deals, conversion.
 * Sisu replacement: gamification and healthy competition.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  RefreshControl,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTheme } from '../../themes/ThemeProvider';
import { getLeaderboard } from '../../services/api';

interface AgentRank {
  id: number;
  name: string;
  gci: number;
  deals_closed: number;
  conversion_rate: number;
  avatar_initial: string;
}

type SortField = 'gci' | 'deals_closed' | 'conversion_rate';

export default function Leaderboard() {
  const { theme } = useTheme();
  const [agents, setAgents] = useState<AgentRank[]>([]);
  const [sortBy, setSortBy] = useState<SortField>('gci');
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    const res = await getLeaderboard();
    if (res.success && res.data) setAgents(res.data as AgentRank[]);
  }, []);

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

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await load();
    setRefreshing(false);
  }, [load]);

  const sorted = [...agents].sort((a, b) => b[sortBy] - a[sortBy]);

  const medalColors = ['#FFD700', '#C0C0C0', '#CD7F32'];

  const formatValue = (agent: AgentRank): string => {
    switch (sortBy) {
      case 'gci':
        return agent.gci >= 1_000_000
          ? `$${(agent.gci / 1_000_000).toFixed(1)}M`
          : `$${(agent.gci / 1_000).toFixed(0)}K`;
      case 'deals_closed':
        return String(agent.deals_closed);
      case 'conversion_rate':
        return `${(agent.conversion_rate * 100).toFixed(1)}%`;
    }
  };

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      <View style={[styles.sortRow, { backgroundColor: theme.colors.card }]}>
        {[
          { key: 'gci' as SortField, label: 'GCI' },
          { key: 'deals_closed' as SortField, label: 'Deals' },
          { key: 'conversion_rate' as SortField, label: 'Conversion' },
        ].map((item) => (
          <TouchableOpacity
            key={item.key}
            style={[styles.sortChip, {
              backgroundColor: sortBy === item.key ? theme.colors.primary : 'transparent',
            }]}
            onPress={() => setSortBy(item.key)}
          >
            <Text style={[styles.sortText, { color: sortBy === item.key ? '#FFF' : theme.colors.textSecondary }]}>
              {item.label}
            </Text>
          </TouchableOpacity>
        ))}
      </View>

      <FlatList
        data={sorted}
        keyExtractor={(item) => String(item.id)}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        renderItem={({ item, index }) => (
          <View style={[styles.row, { backgroundColor: theme.colors.card, borderBottomColor: theme.colors.border }]}>
            <View style={[styles.rank, { backgroundColor: index < 3 ? medalColors[index] : theme.colors.inputBg }]}>
              <Text style={[styles.rankText, { color: index < 3 ? '#FFF' : theme.colors.textSecondary }]}>
                {index + 1}
              </Text>
            </View>
            <View style={[styles.avatar, { backgroundColor: theme.colors.primary }]}>
              <Text style={styles.avatarText}>{item.avatar_initial || item.name[0]}</Text>
            </View>
            <View style={styles.info}>
              <Text style={[styles.name, { color: theme.colors.text }]}>{item.name}</Text>
              <Text style={[styles.stats, { color: theme.colors.textSecondary }]}>
                {item.deals_closed} deals • {(item.conversion_rate * 100).toFixed(0)}% conv
              </Text>
            </View>
            <Text style={[styles.value, { color: theme.colors.primary }]}>
              {formatValue(item)}
            </Text>
          </View>
        )}
        ListEmptyComponent={
          <View style={styles.empty}>
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>No data</Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  sortRow: { flexDirection: 'row', padding: 12, gap: 8 },
  sortChip: { paddingHorizontal: 16, paddingVertical: 8, borderRadius: 20 },
  sortText: { fontSize: 14, fontWeight: '600' },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 14,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  rank: { width: 28, height: 28, borderRadius: 14, justifyContent: 'center', alignItems: 'center', marginRight: 10 },
  rankText: { fontSize: 13, fontWeight: '800' },
  avatar: { width: 40, height: 40, borderRadius: 20, justifyContent: 'center', alignItems: 'center', marginRight: 12 },
  avatarText: { color: '#FFF', fontWeight: '700', fontSize: 16 },
  info: { flex: 1 },
  name: { fontSize: 15, fontWeight: '600' },
  stats: { fontSize: 12, marginTop: 2 },
  value: { fontSize: 17, fontWeight: '800' },
  empty: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 15 },
});
