import React, { useCallback, useEffect } from 'react';
import {
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  StyleSheet,
  RefreshControl,
  ActivityIndicator,
} from 'react-native';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { Card } from '../../components/ui';
import { FunnelChart } from '../../components/charts/FunnelChart';
import { useStatsStore } from '../../stores/stats.store';
import type { StatsPeriod } from '../../types/stats';
import type { FunnelConversionStats } from '../../types/funnel';

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

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

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

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 StatsScreen(): React.JSX.Element {
  const styles = createStyles();
  const summary = useStatsStore((state) => state.summary);
  const funnel = useStatsStore((state) => state.funnel);
  const selectedPeriod = useStatsStore((state) => state.selectedPeriod);
  const isLoading = useStatsStore((state) => state.isLoading);
  const isRefreshing = useStatsStore((state) => state.isRefreshing);
  const error = useStatsStore((state) => state.error);
  const fetchAll = useStatsStore((state) => state.fetchAll);
  const refreshAll = useStatsStore((state) => state.refreshAll);
  const setSelectedPeriod = useStatsStore((state) => state.setSelectedPeriod);

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

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

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

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

  return (
    <View style={styles.container}>
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={handleRefresh}
            tintColor={colors.primary}
            colors={[colors.primary]}
          />
        }
      >
        <Text style={styles.title}>Статистика</Text>

        <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.kpiGrid}>
            <View style={styles.kpiRow}>
              <Card style={styles.kpiCard}>
                <Text style={styles.kpiValue}>
                  {formatNumber(summary.completedTrainings)}
                </Text>
                <Text style={styles.kpiLabel}>Тренировки</Text>
                <Text style={styles.kpiSubtext}>
                  из {summary.totalTrainings} всего
                </Text>
              </Card>
              <Card style={styles.kpiCard}>
                <Text style={styles.kpiValue}>
                  {formatNumber(summary.totalClients)}
                </Text>
                <Text style={styles.kpiLabel}>Клиенты</Text>
                <Text style={styles.kpiSubtext}>
                  +{summary.newClients} новых
                </Text>
              </Card>
            </View>
            <View style={styles.kpiRow}>
              <Card style={styles.kpiCard}>
                <Text style={styles.kpiValue}>
                  {formatCurrency(summary.paidSalesAmount)}
                </Text>
                <Text style={styles.kpiLabel}>Продажи</Text>
                <Text style={styles.kpiSubtext}>
                  из {formatCurrency(summary.totalSalesAmount)}
                </Text>
              </Card>
              <Card style={styles.kpiCard}>
                <Text style={styles.kpiValue}>
                  {formatNumber(summary.upcomingTrainings)}
                </Text>
                <Text style={styles.kpiLabel}>Ближайшие</Text>
                <Text style={styles.kpiSubtext}>
                  {summary.sleepingClients} спящих
                </Text>
              </Card>
            </View>
          </View>
        )}

        {funnel && (
          <View style={styles.funnelSection}>
            <FunnelChart stats={funnel as unknown as FunnelConversionStats} />
          </View>
        )}
      </ScrollView>
    </View>
  );
}

const createStyles = () => StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  loadingContainer: {
    flex: 1,
    backgroundColor: colors.background,
    justifyContent: 'center',
    alignItems: 'center',
  },
  scrollContent: {
    padding: spacing.lg,
    paddingBottom: spacing.xxxl * 2,
  },
  title: {
    ...typography.h2,
    color: colors.text,
    marginBottom: spacing.lg,
  },
  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',
  },
  kpiGrid: {
    marginBottom: spacing.xl,
  },
  kpiRow: {
    flexDirection: 'row',
    marginBottom: spacing.md,
  },
  kpiCard: {
    flex: 1,
    marginHorizontal: spacing.xs,
    alignItems: 'center',
  },
  kpiValue: {
    ...typography.h2,
    color: colors.text,
    marginBottom: spacing.xs,
  },
  kpiLabel: {
    ...typography.bodySmall,
    fontWeight: '600',
    color: colors.textSecondary,
    marginBottom: spacing.xs,
  },
  kpiSubtext: {
    ...typography.caption,
    color: colors.textMuted,
  },
  funnelSection: {
    marginBottom: spacing.xl,
  },
});
