import React, { useCallback, useEffect, useState } from 'react';
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  RefreshControl,
  ActivityIndicator,
} from 'react-native';
import { colors } from '../../theme/colors';
import { Card } from '../../components/ui';
import { useStatsStore } from '../../stores/stats.store';
import type { TrainerFunnelBreakdown, StatsPeriod } from '../../types/stats';
import { createStyles } from './styles';

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

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

function getFunnelStages() {
  return [
    { key: 'totalNew' as const, label: 'Новые', color: '#4A90D9' },
    { key: 'totalAssigned' as const, label: 'Назначены', color: colors.primary },
    { key: 'totalCompleted' as const, label: 'Проведены', color: '#F5A623' },
    { key: 'totalRegular' as const, label: 'Постоянные', color: colors.success },
  ];
}

function formatCurrency(value: number): string {
  if (value >= 1000000) return `${(value / 1000000).toFixed(1)}M`;
  if (value >= 1000) return `${(value / 1000).toFixed(1)}K`;
  return String(value);
}

function overallConversion(totalNew: number, totalRegular: number): number {
  if (totalNew === 0) return 0;
  return Math.round((totalRegular / totalNew) * 100);
}

function trainerConversion(t: TrainerFunnelBreakdown): number {
  if (t.totalNew === 0) return 0;
  return Math.round((t.totalRegular / t.totalNew) * 100);
}

function sortByConversion(trainers: TrainerFunnelBreakdown[]): TrainerFunnelBreakdown[] {
  return [...trainers].sort((a, b) => trainerConversion(b) - trainerConversion(a));
}

export function CoordinatorScreen(): React.JSX.Element {
  const styles = createStyles();
  const summary = useStatsStore((s) => s.summary);
  const funnel = useStatsStore((s) => s.funnel);
  const selectedPeriod = useStatsStore((s) => s.selectedPeriod);
  const isLoading = useStatsStore((s) => s.isLoading);
  const isRefreshing = useStatsStore((s) => s.isRefreshing);
  const error = useStatsStore((s) => s.error);
  const fetchAll = useStatsStore((s) => s.fetchAll);
  const refreshAll = useStatsStore((s) => s.refreshAll);
  const setSelectedPeriod = useStatsStore((s) => s.setSelectedPeriod);

  const [sorted, setSorted] = useState<TrainerFunnelBreakdown[]>([]);

  useEffect(() => {
    void fetchAll();
  }, [fetchAll]);

  useEffect(() => {
    setSorted(funnel?.perTrainer ? sortByConversion(funnel.perTrainer) : []);
  }, [funnel]);

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

  const handleRefresh = useCallback(() => refreshAll(), [refreshAll]);

  const renderTrainerItem = useCallback(
    ({ item, index }: { item: TrainerFunnelBreakdown; index: number }) => {
      const conv = trainerConversion(item);
      return (
        <View style={styles.trainerCard}>
          <View style={styles.trainerHeader}>
            <View style={styles.trainerRank}>
              <Text style={styles.trainerRankText}>{index + 1}</Text>
            </View>
            <Text style={styles.trainerName} numberOfLines={1}>
              {item.firstName} {item.lastName}
            </Text>
            <View style={styles.conversionBadge}>
              <Text style={styles.conversionBadgeText}>{conv}%</Text>
            </View>
          </View>
          <View style={styles.trainerMetrics}>
            <View style={styles.trainerMetricItem}>
              <Text style={styles.trainerMetricValue}>{item.totalNew}</Text>
              <Text style={styles.trainerMetricLabel}>Новые</Text>
            </View>
            <View style={styles.trainerMetricDivider} />
            <View style={styles.trainerMetricItem}>
              <Text style={styles.trainerMetricValue}>{item.totalAssigned}</Text>
              <Text style={styles.trainerMetricLabel}>Назнач.</Text>
            </View>
            <View style={styles.trainerMetricDivider} />
            <View style={styles.trainerMetricItem}>
              <Text style={styles.trainerMetricValue}>{item.totalCompleted}</Text>
              <Text style={styles.trainerMetricLabel}>Провед.</Text>
            </View>
            <View style={styles.trainerMetricDivider} />
            <View style={styles.trainerMetricItem}>
              <Text style={styles.trainerMetricValue}>{item.totalRegular}</Text>
              <Text style={styles.trainerMetricLabel}>Пост.</Text>
            </View>
          </View>
        </View>
      );
    },
    [],
  );

  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>
        )}

        {summary && (
          <View style={styles.summaryRow}>
            <Card style={styles.summaryCard}>
              <Text style={styles.summaryValue}>{summary.totalClients}</Text>
              <Text style={styles.summaryLabel}>Клиенты</Text>
            </Card>
            <Card style={styles.summaryCard}>
              <Text style={[styles.summaryValue, { color: colors.primary }]}>
                {funnel ? `${overallConversion(funnel.totalNew, funnel.totalRegular)}%` : '--'}
              </Text>
              <Text style={styles.summaryLabel}>Конверсия</Text>
            </Card>
            <Card style={styles.summaryCard}>
              <Text style={styles.summaryValue}>{formatCurrency(summary.paidSalesAmount)}</Text>
              <Text style={styles.summaryLabel}>Продажи</Text>
              <Text style={styles.summarySubtext}>{'\u20BD'}</Text>
            </Card>
          </View>
        )}

        {funnel && (
          <View style={styles.funnelSection}>
            <Text style={styles.sectionTitle}>Воронка</Text>
            <Card style={styles.funnelCard}>
              <View style={styles.funnelRow}>
                {getFunnelStages().map((stage, idx) => (
                  <React.Fragment key={stage.key}>
                    <View style={styles.funnelStageItem}>
                      <View style={[styles.funnelDot, { backgroundColor: stage.color }]} />
                      <Text style={styles.funnelStageValue}>{funnel[stage.key]}</Text>
                      <Text style={styles.funnelStageLabel}>{stage.label}</Text>
                    </View>
                    {idx < getFunnelStages().length - 1 && (
                      <View style={styles.funnelArrow}>
                        <Text style={styles.funnelArrowText}>{'\u2192'}</Text>
                      </View>
                    )}
                  </React.Fragment>
                ))}
              </View>
            </Card>
          </View>
        )}

        <Text style={styles.sectionTitle}>Тренеры ({sorted.length})</Text>
      </View>
    ),
    [selectedPeriod, error, summary, funnel, sorted.length, handlePeriodChange],
  );

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

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

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Координатор</Text>
      <FlatList
        data={sorted}
        keyExtractor={(item) => item.trainerId}
        renderItem={renderTrainerItem}
        contentContainerStyle={styles.listContent}
        ListHeaderComponent={renderHeader}
        ListEmptyComponent={renderEmpty}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={() => void handleRefresh()}
            tintColor={colors.primary}
            colors={[colors.primary]}
          />
        }
      />
    </View>
  );
}
