import React, { useCallback, useEffect, useMemo } from 'react';
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  RefreshControl,
  ActivityIndicator,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { Ionicons } from '@expo/vector-icons';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { useBookingStore } from '../../stores/booking.store';
import { BookingCard } from '../../components/cards/BookingCard';
import type { BookingRecord } from '../../types/booking';
import type { BookingStackParamList } from './types';

type NavigationProp = NativeStackNavigationProp<BookingStackParamList, 'BookingList'>;

function formatDateLabel(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(tomorrow.getDate() + 1);

  if (date.getTime() === today.getTime()) return 'Сегодня';
  if (date.getTime() === tomorrow.getTime()) return 'Завтра';

  const days = ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'];
  const months = [
    'янв',
    'фев',
    'мар',
    'апр',
    'мая',
    'июн',
    'июл',
    'авг',
    'сен',
    'окт',
    'ноя',
    'дек',
  ];
  return `${days[date.getDay()]}, ${date.getDate()} ${months[date.getMonth()]}`;
}

function getDaysList(): string[] {
  const result: string[] = [];
  const today = new Date();
  for (let i = -1; i <= 6; i++) {
    const d = new Date(today);
    d.setDate(d.getDate() + i);
    const str = `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
    result.push(str);
  }
  return result;
}

export function BookingListScreen(): React.JSX.Element {
  const styles = createStyles();
  const navigation = useNavigation<NavigationProp>();
  const {
    records,
    selectedDate,
    isLoading,
    isRefreshing,
    error,
    setSelectedDate,
    fetchMyRecords,
    refreshMyRecords,
  } = useBookingStore();

  const days = useMemo(() => getDaysList(), []);

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

  const sortedRecords = useMemo(
    () =>
      [...records].sort((a, b) => new Date(a.startAt).getTime() - new Date(b.startAt).getTime()),
    [records],
  );

  const stats = useMemo(() => {
    const total = records.length;
    const confirmed = records.filter(
      (r) => r.status === 'CONFIRMED' || r.status === 'IN_PROGRESS',
    ).length;
    const completed = records.filter((r) => r.status === 'COMPLETED').length;
    return { total, confirmed, completed };
  }, [records]);

  const handleRecordPress = useCallback(
    (record: BookingRecord) => {
      navigation.navigate('BookingDetail', { recordId: record.id });
    },
    [navigation],
  );

  const renderItem = useCallback(
    ({ item }: { item: BookingRecord }) => (
      <BookingCard record={item} onPress={handleRecordPress} />
    ),
    [handleRecordPress],
  );

  const renderEmptyState = useCallback(() => {
    if (isLoading) return null;
    return (
      <View style={styles.emptyContainer}>
        <Ionicons name="calendar-outline" size={48} color={colors.textMuted} />
        <Text style={styles.emptyTitle}>Нет записей</Text>
        <Text style={styles.emptySubtitle}>На этот день записей нет</Text>
      </View>
    );
  }, [isLoading, styles]);

  return (
    <View style={styles.container}>
      {error && (
        <View style={styles.errorBanner}>
          <Text style={styles.errorText}>{error}</Text>
        </View>
      )}

      {/* Date selector */}
      <View style={styles.dateSelector}>
        <FlatList
          horizontal
          showsHorizontalScrollIndicator={false}
          data={days}
          keyExtractor={(item) => item}
          contentContainerStyle={styles.dateSelectorContent}
          renderItem={({ item }) => {
            const isActive = item === selectedDate;
            const label = formatDateLabel(item);
            const dayNum = new Date(item + 'T00:00:00').getDate().toString();
            return (
              <TouchableOpacity
                style={[styles.dateItem, isActive && styles.dateItemActive]}
                onPress={() => setSelectedDate(item)}
                activeOpacity={0.7}
              >
                <Text style={[styles.dateDayLabel, isActive && styles.dateDayLabelActive]}>
                  {label.split(',')[0] || label}
                </Text>
                <Text style={[styles.dateDayNum, isActive && styles.dateDayNumActive]}>
                  {dayNum}
                </Text>
              </TouchableOpacity>
            );
          }}
        />
      </View>

      {/* Stats row */}
      <View style={styles.statsRow}>
        <View style={styles.statItem}>
          <Text style={styles.statValue}>{stats.total}</Text>
          <Text style={styles.statLabel}>Всего</Text>
        </View>
        <View style={styles.statItem}>
          <Text style={[styles.statValue, { color: '#2196F3' }]}>{stats.confirmed}</Text>
          <Text style={styles.statLabel}>Активных</Text>
        </View>
        <View style={styles.statItem}>
          <Text style={[styles.statValue, { color: colors.success }]}>{stats.completed}</Text>
          <Text style={styles.statLabel}>Завершено</Text>
        </View>
      </View>

      {/* Records list */}
      {isLoading && !isRefreshing ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={colors.primary} />
        </View>
      ) : (
        <FlatList
          data={sortedRecords}
          renderItem={renderItem}
          keyExtractor={(item) => item.id}
          contentContainerStyle={styles.listContent}
          ListEmptyComponent={renderEmptyState}
          refreshControl={
            <RefreshControl
              refreshing={isRefreshing}
              onRefresh={() => void refreshMyRecords()}
              tintColor={colors.primary}
              colors={[colors.primary]}
            />
          }
        />
      )}
    </View>
  );
}

const createStyles = () =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background,
    },
    errorBanner: {
      backgroundColor: colors.error,
      padding: spacing.md,
    },
    errorText: {
      ...typography.bodySmall,
      color: colors.white,
      textAlign: 'center',
    },
    dateSelector: {
      backgroundColor: colors.card,
      borderBottomWidth: 1,
      borderBottomColor: colors.border,
    },
    dateSelectorContent: {
      paddingHorizontal: spacing.md,
      paddingVertical: spacing.sm,
    },
    dateItem: {
      alignItems: 'center',
      paddingHorizontal: spacing.md,
      paddingVertical: spacing.sm,
      borderRadius: 12,
      marginRight: spacing.xs,
      minWidth: 56,
    },
    dateItemActive: {
      backgroundColor: colors.primary,
    },
    dateDayLabel: {
      ...typography.caption,
      color: colors.textMuted,
      marginBottom: 2,
    },
    dateDayLabelActive: {
      color: colors.white,
    },
    dateDayNum: {
      ...typography.body,
      fontWeight: '600',
      color: colors.text,
    },
    dateDayNumActive: {
      color: colors.white,
    },
    statsRow: {
      flexDirection: 'row',
      backgroundColor: colors.card,
      paddingHorizontal: spacing.lg,
      paddingVertical: spacing.md,
      marginBottom: spacing.sm,
      borderBottomWidth: 1,
      borderBottomColor: colors.border,
    },
    statItem: {
      flex: 1,
      alignItems: 'center',
    },
    statValue: {
      ...typography.h3,
      color: colors.text,
    },
    statLabel: {
      ...typography.caption,
      color: colors.textMuted,
    },
    loadingContainer: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
    },
    listContent: {
      padding: spacing.lg,
      paddingBottom: 100,
    },
    emptyContainer: {
      alignItems: 'center',
      paddingTop: spacing.xxxl * 2,
    },
    emptyTitle: {
      ...typography.subtitle,
      color: colors.text,
      marginTop: spacing.md,
      marginBottom: spacing.sm,
    },
    emptySubtitle: {
      ...typography.body,
      color: colors.textMuted,
      textAlign: 'center',
    },
  });
