import React, { useCallback, useEffect } from 'react';
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  RefreshControl,
  ActivityIndicator,
} from 'react-native';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { useStatsStore } from '../../stores/stats.store';
import { useAuthStore } from '../../stores/auth.store';
import type { RatingEntry, StatsPeriod } from '../../types/stats';

interface PeriodTab {
  key: StatsPeriod;
  label: string;
}

const PERIOD_TABS: PeriodTab[] = [
  { key: 'week', label: 'Неделя' },
  { key: 'month', label: 'Месяц' },
  { key: 'quarter', label: 'Квартал' },
  { key: 'year', label: 'Год' },
];

function getRankDisplay(rank: number): string {
  switch (rank) {
    case 1:
      return '\u{1F947}';
    case 2:
      return '\u{1F948}';
    case 3:
      return '\u{1F949}';
    default:
      return String(rank);
  }
}

function formatCurrency(value: number): string {
  if (value >= 1000000) {
    return `${(value / 1000000).toFixed(1)}М ₽`;
  }
  if (value >= 1000) {
    return `${(value / 1000).toFixed(1)}К ₽`;
  }
  return `${value} ₽`;
}

export function RatingScreen(): React.JSX.Element {
  const styles = createStyles();
  const rating = useStatsStore((state) => state.rating);
  const selectedPeriod = useStatsStore((state) => state.selectedPeriod);
  const isLoading = useStatsStore((state) => state.isLoading);
  const error = useStatsStore((state) => state.error);
  const fetchRating = useStatsStore((state) => state.fetchRating);
  const setSelectedPeriod = useStatsStore((state) => state.setSelectedPeriod);
  const currentUserId = useAuthStore((state) => state.user?.id);

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

  const handleRefresh = useCallback(() => {
    fetchRating();
  }, [fetchRating]);

  const handlePeriodChange = useCallback(
    (period: StatsPeriod) => {
      setSelectedPeriod(period);
      fetchRating();
    },
    [setSelectedPeriod, fetchRating],
  );

  const renderItem = useCallback(
    ({ item }: { item: RatingEntry }) => {
      const isCurrentUser = item.userId === currentUserId;
      const isTopThree = item.rank <= 3;

      return (
        <View
          style={[
            styles.ratingItem,
            isCurrentUser && styles.ratingItemHighlighted,
          ]}
        >
          <View style={styles.rankContainer}>
            <Text
              style={[
                styles.rankText,
                isTopThree && styles.rankTextTop,
              ]}
            >
              {getRankDisplay(item.rank)}
            </Text>
          </View>

          <View style={styles.trainerInfo}>
            <Text
              style={[
                styles.trainerName,
                isCurrentUser && styles.trainerNameHighlighted,
              ]}
            >
              {item.firstName} {item.lastName}
            </Text>
            <View style={styles.trainerMeta}>
              <Text style={styles.metaItem}>
                {item.totalTrainings} тренировок
              </Text>
              <Text style={styles.metaSeparator}>{'\u00B7'}</Text>
              <Text style={styles.metaItem}>
                {formatCurrency(item.totalSalesAmount)}
              </Text>
            </View>
          </View>

          <View style={styles.scoreContainer}>
            <Text style={styles.scoreValue}>{item.score}</Text>
            <Text style={styles.scoreLabel}>баллов</Text>
          </View>
        </View>
      );
    },
    [currentUserId],
  );

  const renderEmpty = useCallback(() => {
    if (isLoading) return null;
    return (
      <View style={styles.emptyContainer}>
        <Text style={styles.emptyText}>
          Нет данных по рейтингу за выбранный период
        </Text>
      </View>
    );
  }, [isLoading]);

  const renderHeader = useCallback(
    () => (
      <View>
        <View style={styles.periodContainer}>
          {PERIOD_TABS.map((tab) => {
            const isActive = tab.key === selectedPeriod;
            return (
              <TouchableOpacity
                key={tab.key}
                style={[styles.periodTab, isActive && styles.periodTabActive]}
                onPress={() => handlePeriodChange(tab.key)}
                activeOpacity={0.7}
              >
                <Text
                  style={[
                    styles.periodTabText,
                    isActive && styles.periodTabTextActive,
                  ]}
                >
                  {tab.label}
                </Text>
              </TouchableOpacity>
            );
          })}
        </View>

        {error && (
          <View style={styles.errorBanner}>
            <Text style={styles.errorText}>{error}</Text>
          </View>
        )}
      </View>
    ),
    [selectedPeriod, error, handlePeriodChange],
  );

  if (isLoading && rating.length === 0) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color={colors.primary} />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Рейтинг тренеров</Text>

      <FlatList
        data={rating}
        keyExtractor={(item) => item.userId}
        renderItem={renderItem}
        contentContainerStyle={styles.listContent}
        ListHeaderComponent={renderHeader}
        ListEmptyComponent={renderEmpty}
        refreshControl={
          <RefreshControl
            refreshing={isLoading && rating.length > 0}
            onRefresh={handleRefresh}
            tintColor={colors.primary}
            colors={[colors.primary]}
          />
        }
      />
    </View>
  );
}

const createStyles = () => StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  loadingContainer: {
    flex: 1,
    backgroundColor: colors.background,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    ...typography.h2,
    color: colors.text,
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.lg,
    paddingBottom: spacing.md,
  },
  listContent: {
    paddingHorizontal: spacing.lg,
    paddingBottom: spacing.xxxl * 2,
  },
  periodContainer: {
    flexDirection: 'row',
    backgroundColor: colors.white,
    borderRadius: 12,
    padding: spacing.xs,
    marginBottom: spacing.xl,
  },
  periodTab: {
    flex: 1,
    paddingVertical: spacing.sm,
    alignItems: 'center',
    borderRadius: 10,
  },
  periodTabActive: {
    backgroundColor: colors.primary,
  },
  periodTabText: {
    ...typography.bodySmall,
    fontWeight: '600',
    color: colors.textSecondary,
  },
  periodTabTextActive: {
    color: colors.white,
  },
  errorBanner: {
    backgroundColor: colors.error,
    padding: spacing.md,
    borderRadius: 8,
    marginBottom: spacing.lg,
  },
  errorText: {
    ...typography.bodySmall,
    color: colors.white,
    textAlign: 'center',
  },
  ratingItem: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.white,
    borderRadius: 12,
    padding: spacing.lg,
    marginBottom: spacing.md,
    shadowColor: colors.black,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.06,
    shadowRadius: 6,
    elevation: 2,
  },
  ratingItemHighlighted: {
    borderWidth: 2,
    borderColor: colors.primary,
    backgroundColor: '#FFF8F3',
  },
  rankContainer: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: colors.background,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: spacing.md,
  },
  rankText: {
    ...typography.body,
    fontWeight: '700',
    color: colors.textSecondary,
  },
  rankTextTop: {
    fontSize: 20,
  },
  trainerInfo: {
    flex: 1,
    marginRight: spacing.md,
  },
  trainerName: {
    ...typography.body,
    fontWeight: '600',
    color: colors.text,
    marginBottom: spacing.xs,
  },
  trainerNameHighlighted: {
    color: colors.primary,
  },
  trainerMeta: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  metaItem: {
    ...typography.caption,
    color: colors.textMuted,
  },
  metaSeparator: {
    ...typography.caption,
    color: colors.textMuted,
    marginHorizontal: spacing.xs,
  },
  scoreContainer: {
    alignItems: 'center',
  },
  scoreValue: {
    ...typography.h3,
    color: colors.primary,
  },
  scoreLabel: {
    ...typography.caption,
    color: colors.textMuted,
  },
  emptyContainer: {
    alignItems: 'center',
    paddingTop: spacing.xxxl * 2,
  },
  emptyText: {
    ...typography.body,
    color: colors.textMuted,
    textAlign: 'center',
  },
});
