import React, { useEffect, useRef } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  Modal,
  Animated,
  StyleSheet,
  KeyboardAvoidingView,
  Platform,
  Image,
  FlatList,
} from 'react-native';
import { useDubsTheme } from '../theme';
import { useArcadePool } from '../../hooks/useArcadePool';
import { ensurePngAvatar } from '../../utils/avatarUrl';
import type { ArcadeLeaderboardEntry } from '../../types';

export interface ArcadeLeaderboardSheetProps {
  visible: boolean;
  onDismiss: () => void;
  poolId: number;
  /** Highlighted wallet address (e.g. current user) */
  highlightWallet?: string;
}

function RankLabel({ index }: { index: number }) {
  if (index === 0) return <Text style={styles.rankEmoji}>{'\uD83E\uDD47'}</Text>;
  if (index === 1) return <Text style={styles.rankEmoji}>{'\uD83E\uDD48'}</Text>;
  if (index === 2) return <Text style={styles.rankEmoji}>{'\uD83E\uDD49'}</Text>;
  return <Text style={styles.rankNum}>{index + 1}</Text>;
}

export function ArcadeLeaderboardSheet({
  visible,
  onDismiss,
  poolId,
  highlightWallet,
}: ArcadeLeaderboardSheetProps) {
  const t = useDubsTheme();
  const { pool, leaderboard, stats, loading, refetch } = useArcadePool(poolId);

  const overlayOpacity = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(overlayOpacity, {
      toValue: visible ? 1 : 0,
      duration: 250,
      useNativeDriver: true,
    }).start();
  }, [visible, overlayOpacity]);

  // Refresh on open
  useEffect(() => {
    if (visible) refetch();
  }, [visible]); // eslint-disable-line react-hooks/exhaustive-deps

  const renderItem = ({ item, index }: { item: ArcadeLeaderboardEntry; index: number }) => {
    const isMe = highlightWallet && item.wallet_address === highlightWallet;
    return (
      <View
        style={[
          styles.row,
          { backgroundColor: isMe ? `${t.accent}18` : index % 2 === 0 ? t.surface : 'transparent' },
          isMe ? { borderWidth: 1, borderColor: t.accent } : undefined,
        ]}
      >
        <View style={styles.rankCol}>
          <RankLabel index={index} />
        </View>
        {item.avatar ? (
          <Image source={{ uri: ensurePngAvatar(item.avatar) }} style={styles.avatar} />
        ) : (
          <View style={[styles.avatar, { backgroundColor: t.border }]} />
        )}
        <View style={styles.nameCol}>
          <Text style={[styles.name, { color: t.text }]} numberOfLines={1}>
            {item.username || `${item.wallet_address.slice(0, 4)}...${item.wallet_address.slice(-4)}`}
          </Text>
          <Text style={[styles.lives, { color: t.textMuted }]}>
            {item.lives_used} {item.lives_used === 1 ? 'life' : 'lives'} used
          </Text>
        </View>
        <Text style={[styles.score, { color: t.accent }]}>{item.best_score}</Text>
      </View>
    );
  };

  return (
    <Modal
      visible={visible}
      animationType="slide"
      transparent
      onRequestClose={onDismiss}
    >
      <Animated.View style={[styles.overlay, { opacity: overlayOpacity }]}>
        <TouchableOpacity style={styles.overlayTap} activeOpacity={1} onPress={onDismiss} />
      </Animated.View>

      <KeyboardAvoidingView
        style={styles.keyboardView}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      >
        <View style={styles.sheetPositioner}>
          <View style={[styles.sheet, { backgroundColor: t.background }]}>
            {/* Drag handle */}
            <View style={styles.handleRow}>
              <View style={[styles.handle, { backgroundColor: t.textMuted }]} />
            </View>

            {/* Header */}
            <View style={styles.header}>
              <View>
                <Text style={[styles.headerTitle, { color: t.text }]}>Leaderboard</Text>
                {pool && (
                  <Text style={[styles.poolName, { color: t.textMuted }]}>{pool.name}</Text>
                )}
              </View>
              <TouchableOpacity onPress={onDismiss} activeOpacity={0.8}>
                <Text style={[styles.closeButton, { color: t.textMuted }]}>{'\u2715'}</Text>
              </TouchableOpacity>
            </View>

            {/* Stats bar */}
            {stats && (
              <View style={[styles.statsBar, { backgroundColor: t.surface, borderColor: t.border }]}>
                <View style={styles.statItem}>
                  <Text style={[styles.statValue, { color: t.text }]}>{stats.total_entries}</Text>
                  <Text style={[styles.statLabel, { color: t.textMuted }]}>Players</Text>
                </View>
                <View style={[styles.statDivider, { backgroundColor: t.border }]} />
                <View style={styles.statItem}>
                  <Text style={[styles.statValue, { color: t.accent }]}>{stats.top_score}</Text>
                  <Text style={[styles.statLabel, { color: t.textMuted }]}>Top Score</Text>
                </View>
                <View style={[styles.statDivider, { backgroundColor: t.border }]} />
                <View style={styles.statItem}>
                  <Text style={[styles.statValue, { color: t.text }]}>{Math.round(stats.avg_score)}</Text>
                  <Text style={[styles.statLabel, { color: t.textMuted }]}>Avg Score</Text>
                </View>
              </View>
            )}

            {/* Leaderboard list */}
            <FlatList
              data={leaderboard}
              renderItem={renderItem}
              keyExtractor={(item) => String(item.id)}
              style={styles.list}
              contentContainerStyle={styles.listContent}
              ListEmptyComponent={
                <View style={styles.emptyState}>
                  <Text style={[styles.emptyText, { color: t.textMuted }]}>
                    {loading ? 'Loading...' : 'No scores yet'}
                  </Text>
                </View>
              }
            />
          </View>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
}

const styles = StyleSheet.create({
  overlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0,0,0,0.5)',
  },
  overlayTap: { flex: 1 },
  keyboardView: { flex: 1, justifyContent: 'flex-end' },
  sheetPositioner: { flex: 1, justifyContent: 'flex-end' },
  sheet: {
    borderTopLeftRadius: 24,
    borderTopRightRadius: 24,
    paddingHorizontal: 20,
    paddingBottom: 40,
    maxHeight: '80%',
  },
  handleRow: { alignItems: 'center', paddingTop: 10, paddingBottom: 8 },
  handle: { width: 36, height: 4, borderRadius: 2, opacity: 0.4 },
  header: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    justifyContent: 'space-between',
    paddingVertical: 12,
  },
  headerTitle: { fontSize: 20, fontWeight: '700' },
  poolName: { fontSize: 13, fontWeight: '600', marginTop: 2 },
  closeButton: { fontSize: 20, padding: 4 },
  statsBar: {
    flexDirection: 'row',
    borderRadius: 12,
    borderWidth: 1,
    marginBottom: 12,
    overflow: 'hidden',
  },
  statItem: { flex: 1, alignItems: 'center', paddingVertical: 10 },
  statValue: { fontSize: 18, fontWeight: '800' },
  statLabel: { fontSize: 11, fontWeight: '600', marginTop: 2 },
  statDivider: { width: 1, marginVertical: 8 },
  list: { flexGrow: 0 },
  listContent: { paddingBottom: 8 },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 10,
    paddingHorizontal: 12,
    borderRadius: 10,
    marginBottom: 2,
  },
  rankCol: { width: 32, alignItems: 'center' },
  rankEmoji: { fontSize: 18 },
  rankNum: { fontSize: 14, fontWeight: '700', color: '#888' },
  avatar: { width: 32, height: 32, borderRadius: 16, marginRight: 10 },
  nameCol: { flex: 1 },
  name: { fontSize: 14, fontWeight: '600' },
  lives: { fontSize: 11, marginTop: 1 },
  score: { fontSize: 18, fontWeight: '800' },
  emptyState: { paddingVertical: 40, alignItems: 'center' },
  emptyText: { fontSize: 14, fontWeight: '600' },
});
