/**
 * Showing calendar — today's showings with upcoming schedule.
 * ShowingTime replacement: grouped by day, status badges.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  RefreshControl,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { ShowingsStackParamList } from '../../navigation/stacks/ShowingsStack';
import { useTheme } from '../../themes/ThemeProvider';
import ShowingCard from '../../components/ShowingCard';
import { getShowings, Showing } from '../../services/api';

type Props = NativeStackScreenProps<ShowingsStackParamList, 'ShowingCalendar'>;

export default function ShowingCalendar({ navigation }: Props) {
  const { theme } = useTheme();
  const [showings, setShowings] = useState<Showing[]>([]);
  const [refreshing, setRefreshing] = useState(false);
  const [selectedDate, setSelectedDate] = useState<string>('today');

  const loadShowings = useCallback(async () => {
    const params: Record<string, string> = {};
    if (selectedDate === 'today') {
      params.date = new Date().toISOString().split('T')[0];
    } else if (selectedDate === 'upcoming') {
      params.upcoming = 'true';
    }
    const res = await getShowings(params);
    if (res.success && res.data) {
      setShowings(res.data);
    }
  }, [selectedDate]);

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

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await loadShowings();
    setRefreshing(false);
  }, [loadShowings]);

  const groupByDate = (items: Showing[]): Record<string, Showing[]> => {
    const groups: Record<string, Showing[]> = {};
    for (const s of items) {
      const date = s.showing_date;
      if (!groups[date]) groups[date] = [];
      groups[date].push(s);
    }
    return groups;
  };

  const groups = groupByDate(showings);
  const sortedDates = Object.keys(groups).sort();

  const todayCount = showings.filter(
    (s) => s.showing_date === new Date().toISOString().split('T')[0]
  ).length;

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      {/* Date filter */}
      <View style={[styles.filterRow, { backgroundColor: theme.colors.surface }]}>
        {(['today', 'upcoming', 'all'] as const).map((f) => (
          <TouchableOpacity
            key={f}
            style={[
              styles.filterChip,
              {
                backgroundColor: selectedDate === f ? theme.colors.primary : 'transparent',
                borderColor: selectedDate === f ? theme.colors.primary : theme.colors.border,
              },
            ]}
            onPress={() => setSelectedDate(f)}
          >
            <Text style={[styles.filterText, { color: selectedDate === f ? '#FFF' : theme.colors.textSecondary }]}>
              {f === 'today' ? `Today (${todayCount})` : f === 'upcoming' ? 'Upcoming' : 'All'}
            </Text>
          </TouchableOpacity>
        ))}
        <TouchableOpacity
          style={[styles.tourBtn, { backgroundColor: theme.colors.accent }]}
          onPress={() => navigation.navigate('ShowingCart')}
        >
          <Text style={styles.tourBtnText}>Start Tour</Text>
        </TouchableOpacity>
      </View>

      <FlatList
        data={sortedDates}
        keyExtractor={(date) => date}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        renderItem={({ item: date }) => (
          <View>
            <Text style={[styles.dateHeader, { color: theme.colors.text }]}>
              {new Date(date + 'T12:00:00').toLocaleDateString('en-US', {
                weekday: 'long',
                month: 'long',
                day: 'numeric',
              })}
            </Text>
            {groups[date]
              .sort((a, b) => a.showing_time.localeCompare(b.showing_time))
              .map((showing) => (
                <ShowingCard
                  key={showing.id}
                  showing={showing}
                  onPress={() => navigation.navigate('ShowingDetail', { id: showing.id })}
                />
              ))}
          </View>
        )}
        ListEmptyComponent={
          <View style={styles.empty}>
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>
              No showings scheduled
            </Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  filterRow: {
    flexDirection: 'row',
    padding: 12,
    gap: 8,
    alignItems: 'center',
  },
  filterChip: {
    paddingHorizontal: 14,
    paddingVertical: 7,
    borderRadius: 20,
    borderWidth: 1,
  },
  filterText: { fontSize: 13, fontWeight: '600' },
  tourBtn: {
    marginLeft: 'auto',
    paddingHorizontal: 14,
    paddingVertical: 7,
    borderRadius: 20,
  },
  tourBtnText: { color: '#FFF', fontWeight: '700', fontSize: 13 },
  dateHeader: {
    fontSize: 16,
    fontWeight: '700',
    paddingHorizontal: 16,
    paddingTop: 16,
    paddingBottom: 6,
  },
  empty: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 15 },
});
