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 type { BookingGroupEvent } from '../../types/booking';
import { formatBookingTime } from '../../types/booking';
import type { BookingStackParamList } from './types';

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

function GroupEventCard({
  event,
  onPress,
}: {
  event: BookingGroupEvent;
  onPress: (event: BookingGroupEvent) => void;
}): React.JSX.Element {
  const styles = createStyles();
  const fillPercent =
    event.maxParticipants > 0
      ? Math.round((event.currentParticipants / event.maxParticipants) * 100)
      : 0;
  const isFull = event.currentParticipants >= event.maxParticipants;

  return (
    <TouchableOpacity style={styles.card} onPress={() => onPress(event)} activeOpacity={0.7}>
      <View style={styles.cardLeft}>
        <Text style={styles.timeText}>{formatBookingTime(event.startAt, event.endAt)}</Text>
        {event.isRecurring && <Ionicons name="repeat-outline" size={14} color={colors.textMuted} />}
      </View>

      <View style={styles.cardContent}>
        <Text style={styles.eventTitle} numberOfLines={1}>
          {event.title}
        </Text>
        {event.service && (
          <Text style={styles.serviceName} numberOfLines={1}>
            {event.service.name}
          </Text>
        )}
        {event.staff && (
          <Text style={styles.staffName} numberOfLines={1}>
            {event.staff.firstName} {event.staff.lastName}
          </Text>
        )}
      </View>

      <View style={styles.cardRight}>
        <View style={styles.participantsContainer}>
          <Ionicons name="people" size={14} color={isFull ? colors.error : colors.success} />
          <Text style={[styles.participantsText, { color: isFull ? colors.error : colors.text }]}>
            {event.currentParticipants}/{event.maxParticipants}
          </Text>
        </View>
        <View style={styles.progressBar}>
          <View
            style={[
              styles.progressFill,
              {
                width: `${Math.min(fillPercent, 100)}%`,
                backgroundColor: isFull ? colors.error : colors.success,
              },
            ]}
          />
        </View>
      </View>
    </TouchableOpacity>
  );
}

export function GroupEventsScreen(): React.JSX.Element {
  const styles = createStyles();
  const navigation = useNavigation<NavigationProp>();
  const { groupEvents, isLoadingGroups, isRefreshing, error, fetchGroupEvents } = useBookingStore();

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

  const sortedEvents = useMemo(
    () =>
      [...groupEvents]
        .filter((e) => e.isActive)
        .sort((a, b) => new Date(a.startAt).getTime() - new Date(b.startAt).getTime()),
    [groupEvents],
  );

  const handleEventPress = useCallback(
    (event: BookingGroupEvent) => {
      navigation.navigate('GroupEventDetail', { eventId: event.id });
    },
    [navigation],
  );

  const renderItem = useCallback(
    ({ item }: { item: BookingGroupEvent }) => (
      <GroupEventCard event={item} onPress={handleEventPress} />
    ),
    [handleEventPress],
  );

  const renderEmptyState = useCallback(() => {
    if (isLoadingGroups) return null;
    return (
      <View style={styles.emptyContainer}>
        <Ionicons name="people-outline" size={48} color={colors.textMuted} />
        <Text style={styles.emptyTitle}>Нет групповых занятий</Text>
        <Text style={styles.emptySubtitle}>Групповые занятия пока не запланированы</Text>
      </View>
    );
  }, [isLoadingGroups, styles]);

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

      {isLoadingGroups && !isRefreshing ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={colors.primary} />
        </View>
      ) : (
        <FlatList
          data={sortedEvents}
          renderItem={renderItem}
          keyExtractor={(item) => item.id}
          contentContainerStyle={styles.listContent}
          ListEmptyComponent={renderEmptyState}
          refreshControl={
            <RefreshControl
              refreshing={isRefreshing}
              onRefresh={() => void fetchGroupEvents()}
              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',
    },
    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',
    },
    card: {
      flexDirection: 'row',
      backgroundColor: colors.card,
      borderRadius: 12,
      padding: spacing.md,
      marginBottom: spacing.sm,
      shadowColor: colors.black,
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.08,
      shadowRadius: 8,
      elevation: 3,
    },
    cardLeft: {
      alignItems: 'center',
      justifyContent: 'center',
      marginRight: spacing.md,
      minWidth: 70,
    },
    timeText: {
      ...typography.bodySmall,
      fontWeight: '600',
      color: colors.primary,
    },
    cardContent: {
      flex: 1,
    },
    eventTitle: {
      ...typography.body,
      fontWeight: '600',
      color: colors.text,
      marginBottom: 2,
    },
    serviceName: {
      ...typography.bodySmall,
      color: colors.textSecondary,
    },
    staffName: {
      ...typography.caption,
      color: colors.textMuted,
      marginTop: 2,
    },
    cardRight: {
      alignItems: 'flex-end',
      justifyContent: 'center',
      marginLeft: spacing.sm,
      minWidth: 56,
    },
    participantsContainer: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 4,
      marginBottom: 4,
    },
    participantsText: {
      ...typography.bodySmall,
      fontWeight: '600',
    },
    progressBar: {
      width: 48,
      height: 4,
      borderRadius: 2,
      backgroundColor: colors.border,
      overflow: 'hidden',
    },
    progressFill: {
      height: '100%',
      borderRadius: 2,
    },
  });
