/**
 * Calendar — events, Google Calendar sync, showing schedule.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  SectionList,
  TouchableOpacity,
  RefreshControl,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTheme } from '../themes/ThemeProvider';
import { getCalendarEvents, CalendarEvent } from '../services/api';

export default function CalendarScreen() {
  const { theme } = useTheme();
  const [events, setEvents] = useState<CalendarEvent[]>([]);
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    const res = await getCalendarEvents();
    if (res.success && res.data) setEvents(res.data);
  }, []);

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

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

  const groupByDate = (items: CalendarEvent[]): { title: string; data: CalendarEvent[] }[] => {
    const groups: Record<string, CalendarEvent[]> = {};
    for (const event of items) {
      const date = event.start_time.split('T')[0];
      if (!groups[date]) groups[date] = [];
      groups[date].push(event);
    }
    return Object.entries(groups)
      .sort(([a], [b]) => a.localeCompare(b))
      .map(([date, data]) => ({
        title: new Date(date + 'T12:00:00').toLocaleDateString('en-US', {
          weekday: 'long',
          month: 'long',
          day: 'numeric',
        }),
        data: data.sort((a, b) => a.start_time.localeCompare(b.start_time)),
      }));
  };

  const sections = groupByDate(events);

  const eventTypeColor = (type: string): string => {
    switch (type) {
      case 'showing': return theme.colors.info;
      case 'meeting': return theme.colors.success;
      case 'deadline': return theme.colors.error;
      case 'open_house': return theme.colors.accent;
      case 'closing': return '#8B5CF6';
      default: return theme.colors.primary;
    }
  };

  const formatTime = (ts: string): string => {
    try {
      return new Date(ts).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
    } catch {
      return '';
    }
  };

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      <SectionList
        sections={sections}
        keyExtractor={(item) => String(item.id)}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        renderSectionHeader={({ section }) => (
          <Text style={[styles.dateHeader, { color: theme.colors.text, backgroundColor: theme.colors.background }]}>
            {section.title}
          </Text>
        )}
        renderItem={({ item }) => (
          <View style={[styles.eventRow, { backgroundColor: theme.colors.card, borderBottomColor: theme.colors.border }]}>
            <View style={[styles.typeDot, { backgroundColor: eventTypeColor(item.event_type) }]} />
            <View style={styles.eventInfo}>
              <Text style={[styles.eventTitle, { color: theme.colors.text }]}>{item.title}</Text>
              <Text style={[styles.eventTime, { color: theme.colors.textSecondary }]}>
                {formatTime(item.start_time)}
                {item.end_time ? ` - ${formatTime(item.end_time)}` : ''}
              </Text>
              {item.location ? (
                <Text style={[styles.eventLocation, { color: theme.colors.textSecondary }]}>
                  {item.location}
                </Text>
              ) : null}
            </View>
            {item.google_event_id && (
              <Text style={[styles.syncBadge, { color: theme.colors.info }]}>Synced</Text>
            )}
          </View>
        )}
        ListEmptyComponent={
          <View style={styles.empty}>
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>No events</Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  dateHeader: {
    fontSize: 15,
    fontWeight: '700',
    paddingHorizontal: 16,
    paddingVertical: 10,
  },
  eventRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  typeDot: { width: 10, height: 10, borderRadius: 5, marginRight: 12 },
  eventInfo: { flex: 1 },
  eventTitle: { fontSize: 15, fontWeight: '500' },
  eventTime: { fontSize: 13, marginTop: 2 },
  eventLocation: { fontSize: 12, marginTop: 2 },
  syncBadge: { fontSize: 10, fontWeight: '600' },
  empty: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 15 },
});
