import { Picker } from "@react-native-picker/picker";
import * as Calendar from "expo-calendar";
import * as SQLite from "expo-sqlite";
import React, { useEffect, useState } from "react";
import { FlatList, StyleSheet, Text, View } from "react-native";

const db = SQLite.openDatabaseSync("events.db");

export interface EventItem {
  id: string;
  title: string;
  startDate: string;
  endDate: string;
}

const CalendarSync: React.FC = () => {
  const [events, setEvents] = useState<EventItem[]>([]);
  const [selectedYear, setSelectedYear] = useState<number>(
    new Date().getFullYear()
  );

  // Initialisierung: SQLite laden, dann Kalender synchronisieren
  useEffect(() => {
    initDB();
    loadEventsFromDB();
    syncCalendarEvents(selectedYear);
  }, [selectedYear]);

  // Erstellt die Tabelle, falls nicht vorhanden
  const initDB = async () => {
    await db.execAsync(
      "CREATE TABLE IF NOT EXISTS events (id TEXT PRIMARY KEY, title TEXT, startDate TEXT, endDate TEXT);"
    );
  };

  const loadEventsFromDB = async () => {
    const stmt = await db.prepareAsync("SELECT * FROM events;");
    const loadedEvents: EventItem[] = [];
    const result = await stmt.executeAsync([]);
    for await (const row of result) {
      loadedEvents.push(row as EventItem);
    }
    setEvents(loadedEvents);
    await stmt.finalizeAsync();
  };

  // Synchronisiert Kalender-Events und speichert sie in SQLite
  const syncCalendarEvents = async (year: number) => {
    const perm = await Calendar.requestCalendarPermissionsAsync();
    if (!perm.granted) return;
    const calendars = await Calendar.getCalendarsAsync();
    const start = new Date(year, 0, 1);
    const end = new Date(year, 11, 31, 23, 59, 59);
    let allEvents: EventItem[] = [];
    for (const cal of calendars) {
      const calEvents = await Calendar.getEventsAsync([cal.id], start, end);
      allEvents = allEvents.concat(
        calEvents.map((e) => ({
          id: e.id,
          title: e.title || "(Kein Titel)",
          startDate:
            typeof e.startDate === "string"
              ? e.startDate
              : new Date(e.startDate).toISOString(),
          endDate:
            typeof e.endDate === "string"
              ? e.endDate
              : new Date(e.endDate).toISOString(),
        }))
      );
    }
    // Speichern in SQLite
    await db.execAsync("DELETE FROM events;");
    for (const ev of allEvents) {
      await db.execAsync(
        `INSERT OR REPLACE INTO events (id, title, startDate, endDate) VALUES ('${
          ev.id
        }', '${ev.title.replace(/'/g, "''")}', '${ev.startDate}', '${
          ev.endDate
        }');`
      );
    }
    await loadEventsFromDB();
  };

  // UI
  const renderItem = ({ item }: { item: EventItem }) => (
    <View style={styles.item}>
      <Text style={styles.title}>{item.title}</Text>
      <Text style={styles.time}>
        {new Date(item.startDate).toLocaleString()} -{" "}
        {new Date(item.endDate).toLocaleString()}
      </Text>
    </View>
  );

  return (
    <View style={styles.container}>
      <Text style={styles.header}>Kalender Events ({selectedYear})</Text>
      <Picker
        selectedValue={selectedYear}
        style={{ height: 50, width: 180, marginBottom: 16 }}
        onValueChange={(year) => setSelectedYear(year)}
      >
        {[...Array(10)].map((_, i) => {
          const year = new Date().getFullYear() - 5 + i;
          return (
            <Picker.Item key={year} label={year.toString()} value={year} />
          );
        })}
      </Picker>
      <FlatList
        data={events}
        keyExtractor={(item) => item.id}
        renderItem={renderItem}
        ListEmptyComponent={<Text>Keine Events gefunden.</Text>}
      />
    </View>
  );
};

export default CalendarSync;

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, backgroundColor: "#fff" },
  header: { fontSize: 20, fontWeight: "bold", marginBottom: 16 },
  item: {
    marginBottom: 12,
    padding: 12,
    borderRadius: 8,
    backgroundColor: "#f2f2f2",
  },
  title: { fontSize: 16, fontWeight: "600" },
  time: { fontSize: 14, color: "#555" },
});
