import React, { useCallback, useEffect, useState } from 'react';
import {
  View, Text, StyleSheet, ScrollView,
  ActivityIndicator, RefreshControl, TouchableOpacity,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import type { BottomTabNavigationProp } from '@react-navigation/bottom-tabs';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { Card } from '../../components/ui';
import { useAuthStore } from '../../stores/auth.store';
import { api } from '../../services/api';
import type { MainTabParamList } from '../../app/navigation';
import type { StatsSummary } from '../../types/stats';
import type { Training } from '../../types/training';

interface DebtsSummary {
  totalAmount: number;
  count: number;
}

function formatCurrency(amount: number): string {
  return amount.toLocaleString('ru-RU') + ' \u20BD';
}

function formatTime(time: string): string {
  return time.substring(0, 5);
}

function formatTrainingDate(dateStr: string): string {
  const date = new Date(dateStr + 'T00:00:00');
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const tomorrow = new Date(today);
  tomorrow.setDate(today.getDate() + 1);

  if (date.getTime() === today.getTime()) return 'Сегодня';
  if (date.getTime() === tomorrow.getTime()) return 'Завтра';
  return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' });
}

function getTrainingStatusColor(status: string): string {
  const map: Record<string, string> = {
    PLANNED: colors.warning,
    CONFIRMED: colors.success,
    COMPLETED: colors.success,
    CANCELLED: colors.error,
  };
  return map[status] || colors.textMuted;
}

export function HomeScreen(): React.JSX.Element {
  const styles = createStyles();
  const user = useAuthStore((state) => state.user);
  const greeting = user ? `${user.firstName} ${user.lastName}` : 'Пользователь';
  const navigation = useNavigation<BottomTabNavigationProp<MainTabParamList>>();

  const [stats, setStats] = useState<StatsSummary | null>(null);
  const [trainings, setTrainings] = useState<Training[]>([]);
  const [debtsSummary, setDebtsSummary] = useState<DebtsSummary | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);

  const loadData = useCallback(async () => {
    const today = new Date();
    const dateFrom = today.toISOString().split('T')[0];
    const dateTo = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000)
      .toISOString().split('T')[0];

    const results = await Promise.allSettled([
      api.get<StatsSummary>('/stats/summary', {
        params: { dateFrom, dateTo },
      }),
      api.get<{ data: Training[] }>('/trainings', {
        params: { dateFrom, dateTo, limit: 5, status: 'PLANNED' },
      }),
      api.get<DebtsSummary>('/sales/debts/summary'),
    ]);

    if (results[0].status === 'fulfilled') setStats(results[0].value);
    if (results[1].status === 'fulfilled') setTrainings(results[1].value.data);
    if (results[2].status === 'fulfilled') setDebtsSummary(results[2].value);
  }, []);

  useEffect(() => {
    (async () => {
      setIsLoading(true);
      await loadData();
      setIsLoading(false);
    })();
  }, [loadData]);

  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true);
    await loadData();
    setIsRefreshing(false);
  }, [loadData]);

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

  return (
    <ScrollView
      style={styles.container}
      contentContainerStyle={styles.content}
      refreshControl={
        <RefreshControl
          refreshing={isRefreshing}
          onRefresh={handleRefresh}
          colors={[colors.primary]}
          tintColor={colors.primary}
        />
      }
    >
      <Text style={styles.greeting}>{`Привет, ${greeting}!`}</Text>

      {/* Stats summary */}
      <Card style={styles.card}>
        <Text style={styles.cardTitle}>Статистика</Text>
        <View style={styles.statsRow}>
          <View style={styles.statItem}>
            <Text style={styles.statValue}>
              {stats?.completedTrainings ?? 0}
            </Text>
            <Text style={styles.statLabel}>Тренировки</Text>
          </View>
          <View style={styles.statItem}>
            <Text style={styles.statValue}>
              {stats?.totalClients ?? 0}
            </Text>
            <Text style={styles.statLabel}>Клиенты</Text>
          </View>
          <View style={styles.statItem}>
            <Text style={[styles.statValue, { color: colors.success }]}>
              {formatCurrency(stats?.paidSalesAmount ?? 0)}
            </Text>
            <Text style={styles.statLabel}>Продажи</Text>
          </View>
        </View>
      </Card>

      {/* Upcoming trainings */}
      <Card style={styles.card}>
        <View style={styles.cardHeader}>
          <Text style={styles.cardTitle}>Ближайшие занятия</Text>
          <Text style={styles.cardBadge}>
            {stats?.upcomingTrainings ?? trainings.length}
          </Text>
        </View>
        {trainings.length > 0 ? (
          trainings.map((t) => (
            <TouchableOpacity
              key={t.id}
              style={styles.trainingRow}
              activeOpacity={0.7}
              onPress={() =>
                navigation.navigate('ScheduleTab', {
                  screen: 'TrainingDetail',
                  params: { trainingId: t.id },
                })
              }
            >
              <View style={styles.trainingTime}>
                <Text style={styles.trainingDateText}>
                  {formatTrainingDate(t.date)}
                </Text>
                <Text style={styles.trainingTimeText}>
                  {formatTime(t.startTime)}
                </Text>
              </View>
              <View style={styles.trainingInfo}>
                <Text style={styles.trainingClient} numberOfLines={1}>
                  {t.client
                    ? `${t.client.lastName} ${t.client.firstName}`
                    : 'Клиент'}
                </Text>
                <Text style={styles.trainingService} numberOfLines={1}>
                  {t.service?.name || `${t.duration} мин`}
                </Text>
              </View>
              <View
                style={[
                  styles.statusDot,
                  { backgroundColor: getTrainingStatusColor(t.status) },
                ]}
              />
            </TouchableOpacity>
          ))
        ) : (
          <Text style={styles.cardPlaceholder}>
            Нет запланированных занятий
          </Text>
        )}
      </Card>

      {/* Debts */}
      <Card style={styles.card}>
        <Text style={styles.cardTitle}>Долги клиентов</Text>
        {debtsSummary && debtsSummary.count > 0 ? (
          <View style={styles.debtsBanner}>
            <View style={styles.debtsInfo}>
              <Text style={styles.debtsAmount}>
                {formatCurrency(debtsSummary.totalAmount)}
              </Text>
              <Text style={styles.debtsCount}>
                {debtsSummary.count}{' '}
                {debtsSummary.count === 1
                  ? 'долг'
                  : debtsSummary.count < 5
                    ? 'долга'
                    : 'долгов'}
              </Text>
            </View>
            <TouchableOpacity
              activeOpacity={0.7}
              onPress={() =>
                navigation.navigate('More', {
                  screen: 'SalesList',
                })
              }
            >
              <Text style={styles.debtsLink}>Подробнее</Text>
            </TouchableOpacity>
          </View>
        ) : (
          <Text style={styles.cardPlaceholder}>Нет активных долгов</Text>
        )}
      </Card>

      {/* Quick stats */}
      {stats && (stats.sleepingClients > 0 || stats.newClients > 0) && (
        <Card style={styles.card}>
          <Text style={styles.cardTitle}>Важное</Text>
          {stats.newClients > 0 && (
            <View style={styles.alertRow}>
              <View style={[styles.alertDot, { backgroundColor: colors.success }]} />
              <Text style={styles.alertText}>
                {stats.newClients} новых клиентов
              </Text>
            </View>
          )}
          {stats.sleepingClients > 0 && (
            <TouchableOpacity
              style={styles.alertRow}
              activeOpacity={0.7}
              onPress={() =>
                navigation.navigate('More', {
                  screen: 'SleepingClients',
                })
              }
            >
              <View style={[styles.alertDot, { backgroundColor: colors.error }]} />
              <Text style={styles.alertText}>
                {stats.sleepingClients} спящих клиентов
              </Text>
            </TouchableOpacity>
          )}
        </Card>
      )}
    </ScrollView>
  );
}

const createStyles = () => StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  content: {
    padding: spacing.lg,
  },
  loadingContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.background,
  },
  greeting: {
    ...typography.h2,
    color: colors.text,
    marginBottom: spacing.xl,
  },
  card: {
    marginBottom: spacing.lg,
  },
  cardHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: spacing.md,
  },
  cardTitle: {
    ...typography.subtitle,
    color: colors.text,
    marginBottom: spacing.md,
  },
  cardBadge: {
    ...typography.caption,
    fontWeight: '700',
    color: colors.white,
    backgroundColor: colors.primary,
    borderRadius: 12,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.xs,
    overflow: 'hidden',
    marginBottom: spacing.md,
  },
  cardPlaceholder: {
    ...typography.body,
    color: colors.textMuted,
  },
  statsRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  statItem: {
    alignItems: 'center',
  },
  statValue: {
    ...typography.h2,
    color: colors.primary,
  },
  statLabel: {
    ...typography.caption,
    color: colors.textSecondary,
    marginTop: spacing.xs,
  },
  trainingRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: spacing.sm,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  trainingTime: {
    width: 70,
    marginRight: spacing.md,
  },
  trainingDateText: {
    ...typography.caption,
    color: colors.textMuted,
  },
  trainingTimeText: {
    ...typography.body,
    fontWeight: '600',
    color: colors.text,
  },
  trainingInfo: {
    flex: 1,
  },
  trainingClient: {
    ...typography.body,
    fontWeight: '500',
    color: colors.text,
  },
  trainingService: {
    ...typography.caption,
    color: colors.textSecondary,
    marginTop: 2,
  },
  statusDot: {
    width: 10,
    height: 10,
    borderRadius: 5,
    marginLeft: spacing.sm,
  },
  debtsBanner: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: colors.error + '10',
    borderRadius: 12,
    padding: spacing.md,
  },
  debtsInfo: {},
  debtsAmount: {
    ...typography.subtitle,
    color: colors.error,
  },
  debtsCount: {
    ...typography.caption,
    color: colors.textMuted,
    marginTop: 2,
  },
  debtsLink: {
    ...typography.bodySmall,
    fontWeight: '600',
    color: colors.primary,
  },
  alertRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: spacing.sm,
  },
  alertDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    marginRight: spacing.md,
  },
  alertText: {
    ...typography.body,
    color: colors.text,
  },
});
