import React, { useCallback, useEffect, useState } from 'react';
import { View, Text, FlatList, StyleSheet, ActivityIndicator, Alert } from 'react-native';
import { useRoute } from '@react-navigation/native';
import type { RouteProp } from '@react-navigation/native';
import { Ionicons } from '@expo/vector-icons';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { bookingService } from '../../services/booking';
import { useBookingStore } from '../../stores/booking.store';
import { BookingCard } from '../../components/cards/BookingCard';
import type { BookingRecord, BookingGroupEvent } from '../../types/booking';
import { formatBookingTime } from '../../types/booking';
import type { BookingStackParamList } from './types';

type DetailRoute = RouteProp<BookingStackParamList, 'GroupEventDetail'>;

export function GroupEventDetailScreen(): React.JSX.Element {
  const styles = createStyles();
  const route = useRoute<DetailRoute>();
  const { eventId } = route.params;

  const [event, setEvent] = useState<BookingGroupEvent | null>(null);
  const [participants, setParticipants] = useState<BookingRecord[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { markAttendance } = useBookingStore();

  useEffect(() => {
    async function load() {
      setIsLoading(true);
      setError(null);
      try {
        const [ev, parts] = await Promise.all([
          bookingService.getGroupEvent(eventId),
          bookingService.getGroupEventParticipants(eventId),
        ]);
        setEvent(ev);
        setParticipants(parts);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Ошибка загрузки');
      } finally {
        setIsLoading(false);
      }
    }
    void load();
  }, [eventId]);

  const handleMarkAttendance = useCallback(
    (record: BookingRecord) => {
      if (record.status !== 'CONFIRMED' && record.status !== 'IN_PROGRESS') return;

      Alert.alert('Отметка посещения', `${record.clientName}`, [
        { text: 'Отмена', style: 'cancel' },
        {
          text: 'Пришёл',
          onPress: () => {
            void markAttendance(record.id, 'COMPLETED').then(() => {
              setParticipants((prev) =>
                prev.map((r) => (r.id === record.id ? { ...r, status: 'COMPLETED' as const } : r)),
              );
            });
          },
        },
        {
          text: 'Не пришёл',
          style: 'destructive',
          onPress: () => {
            void markAttendance(record.id, 'NO_SHOW').then(() => {
              setParticipants((prev) =>
                prev.map((r) => (r.id === record.id ? { ...r, status: 'NO_SHOW' as const } : r)),
              );
            });
          },
        },
      ]);
    },
    [markAttendance],
  );

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

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

  if (!event) {
    return (
      <View style={styles.loadingContainer}>
        <Text style={styles.errorMsg}>{error || 'Занятие не найдено'}</Text>
      </View>
    );
  }

  const fillPercent =
    event.maxParticipants > 0
      ? Math.round((event.currentParticipants / event.maxParticipants) * 100)
      : 0;

  return (
    <View style={styles.container}>
      {/* Event header */}
      <View style={styles.header}>
        <Text style={styles.title}>{event.title}</Text>
        <Text style={styles.timeLabel}>{formatBookingTime(event.startAt, event.endAt)}</Text>
        {event.staff && (
          <Text style={styles.staffLabel}>
            Тренер: {event.staff.firstName} {event.staff.lastName}
          </Text>
        )}

        <View style={styles.statsRow}>
          <View style={styles.statItem}>
            <Ionicons name="people" size={18} color={colors.primary} />
            <Text style={styles.statText}>
              {event.currentParticipants} / {event.maxParticipants}
            </Text>
          </View>
          <View style={styles.progressBarLarge}>
            <View
              style={[
                styles.progressFill,
                {
                  width: `${Math.min(fillPercent, 100)}%`,
                  backgroundColor: fillPercent >= 100 ? colors.error : colors.success,
                },
              ]}
            />
          </View>
        </View>
      </View>

      {/* Participants list */}
      <Text style={styles.sectionTitle}>Участники ({participants.length})</Text>

      <FlatList
        data={participants}
        renderItem={renderItem}
        keyExtractor={(item) => item.id}
        contentContainerStyle={styles.listContent}
        ListEmptyComponent={
          <View style={styles.emptyContainer}>
            <Text style={styles.emptyText}>Пока нет записавшихся</Text>
          </View>
        }
      />
    </View>
  );
}

const createStyles = () =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background,
    },
    loadingContainer: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: colors.background,
    },
    errorMsg: {
      ...typography.body,
      color: colors.error,
    },
    header: {
      backgroundColor: colors.card,
      padding: spacing.lg,
      borderBottomWidth: 1,
      borderBottomColor: colors.border,
    },
    title: {
      ...typography.h3,
      color: colors.text,
      marginBottom: spacing.xs,
    },
    timeLabel: {
      ...typography.body,
      color: colors.primary,
      fontWeight: '600',
      marginBottom: spacing.xs,
    },
    staffLabel: {
      ...typography.bodySmall,
      color: colors.textSecondary,
      marginBottom: spacing.md,
    },
    statsRow: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.md,
    },
    statItem: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.xs,
    },
    statText: {
      ...typography.body,
      fontWeight: '600',
      color: colors.text,
    },
    progressBarLarge: {
      flex: 1,
      height: 6,
      borderRadius: 3,
      backgroundColor: colors.border,
      overflow: 'hidden',
    },
    progressFill: {
      height: '100%',
      borderRadius: 3,
    },
    sectionTitle: {
      ...typography.subtitle,
      color: colors.text,
      paddingHorizontal: spacing.lg,
      paddingTop: spacing.lg,
      paddingBottom: spacing.sm,
    },
    listContent: {
      padding: spacing.lg,
      paddingTop: 0,
      paddingBottom: 100,
    },
    emptyContainer: {
      alignItems: 'center',
      paddingTop: spacing.xxxl,
    },
    emptyText: {
      ...typography.body,
      color: colors.textMuted,
    },
  });
