import React, { useEffect, useState } from 'react';
import {
  ScheduleComponent,
  Day,
  Week,
  WorkWeek,
  Month,
  Agenda,
  Inject,
  ViewsDirective,
  ViewDirective,
} from '@syncfusion/ej2-react-schedule';
import { DropDownListComponent } from '@syncfusion/ej2-react-dropdowns';
import { L10n, loadCldr, setCulture } from '@syncfusion/ej2-base';
import type { EventRenderedArgs, ActionEventArgs } from '@syncfusion/ej2-react-schedule';
import { fetchEvents } from './apiEvents';
import { fetchGroups } from './apiGroups';
import { getGroupColor } from './groupColors';
import { deleteEvent } from './apiEvents';
import CustomEventModal from './components/CustomEventModal';

// Typ für Gruppe ergänzen
type Group = {
  id: string;
  name: string;
};

// Typ für Event hinzufügen
type Event = {
  Id: string;
  Subject: string;
  StartTime: Date;
  EndTime: Date;
  IsAllDay: boolean;
};

type RawEvent = {
  Id: string;
  Subject: string;
  StartTime: string;
  EndTime: string;
  IsAllDay: boolean;
};

import * as de from 'cldr-data/main/de/ca-gregorian.json';
import * as numbers from 'cldr-data/main/de/numbers.json';
import * as timeZoneNames from 'cldr-data/main/de/timeZoneNames.json';
import * as numberingSystems from 'cldr-data/supplemental/numberingSystems.json';

// CLDR-Daten laden
loadCldr(
  (de as unknown as { default: object }).default,
  (numbers as unknown as { default: object }).default,
  (timeZoneNames as unknown as { default: object }).default,
  (numberingSystems as unknown as { default: object }).default
);

// Deutsche Lokalisierung für den Scheduler
L10n.load({
  de: {
    schedule: {
      day: 'Tag',
      week: 'Woche',
      workWeek: 'Arbeitswoche',
      month: 'Monat',
      agenda: 'Agenda',
      today: 'Heute',
      noEvents: 'Keine Termine',
      allDay: 'Ganztägig',
      start: 'Start',
      end: 'Ende',
      event: 'Termin',
      save: 'Speichern',
      cancel: 'Abbrechen',
      delete: 'Löschen',
      edit: 'Bearbeiten',
      newEvent: 'Neuer Termin',
      title: 'Titel',
      description: 'Beschreibung',
      location: 'Ort',
      recurrence: 'Wiederholung',
      repeat: 'Wiederholen',
      deleteEvent: 'Termin löschen',
      deleteContent: 'Möchten Sie diesen Termin wirklich löschen?',
      moreDetails: 'Mehr Details',
      addTitle: 'Termintitel',
    },
  },
});

// Kultur setzen
setCulture('de');

const Appointments: React.FC = () => {
  const [groups, setGroups] = useState<Group[]>([]);
  const [selectedGroupId, setSelectedGroupId] = useState<string | null>(null);
  const [events, setEvents] = useState<Event[]>([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [modalInitialData, setModalInitialData] = useState({});
  const [schedulerKey, setSchedulerKey] = useState(0);

  // Gruppen laden
  useEffect(() => {
    fetchGroups()
      .then(data => {
        // Nur Gruppen mit id berücksichtigen (nicht zugeordnet ignorieren)
        const filtered = Array.isArray(data)
          ? data.filter(g => g.id && g.name && g.name !== 'nicht zugeordnet')
          : [];
        setGroups(filtered);
        if (filtered.length > 0) setSelectedGroupId(filtered[0].id);
      })
      .catch(console.error);
  }, []);

  // Termine für die ausgewählte Gruppe laden
  useEffect(() => {
    if (selectedGroupId) {
      fetchEvents(selectedGroupId)
        .then((data: RawEvent[]) => {
          const mapped: Event[] = data.map(e => ({
            Id: e.Id,
            Subject: e.Subject,
            StartTime: new Date(e.StartTime.endsWith('Z') ? e.StartTime : e.StartTime + 'Z'),
            EndTime: new Date(e.EndTime.endsWith('Z') ? e.EndTime : e.EndTime + 'Z'),
            IsAllDay: e.IsAllDay,
          }));
          setEvents(mapped);
        })
        .catch(console.error);
    } else {
      setEvents([]);
    }
  }, [selectedGroupId]);

  return (
    <div>
      <h1 className="text-2xl font-bold mb-4">Terminmanagement</h1>
      <div
        style={{ marginBottom: 16, maxWidth: 500, display: 'flex', alignItems: 'center', gap: 12 }}
      >
        <label htmlFor="groupDropdown" className="mb-0 mr-2" style={{ whiteSpace: 'nowrap' }}>
          Raumgruppe auswählen:
        </label>
        <DropDownListComponent
          id="groupDropdown"
          dataSource={groups}
          fields={{ text: 'name', value: 'id' }}
          placeholder="Gruppe auswählen"
          value={selectedGroupId}
          change={e => {
            setEvents([]); // Events sofort leeren
            setSelectedGroupId(e.value as string);
          }}
          style={{ flex: 1 }}
        />
      </div>
      <button
        className="e-btn e-success mb-4"
        onClick={() => {
          setModalInitialData({});
          setModalOpen(true);
        }}
      >
        Neuen Termin anlegen
      </button>
      <CustomEventModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        onSave={async eventData => {
          setModalOpen(false);
          console.log('onSave wird aufgerufen');
          if (selectedGroupId) {
            const data = await fetchEvents(selectedGroupId);
            console.log('Events nach Save:', data);
            const mapped: Event[] = data.map(e => ({
              Id: e.Id,
              Subject: e.Subject,
              StartTime: new Date(e.StartTime.endsWith('Z') ? e.StartTime : e.StartTime + 'Z'),
              EndTime: new Date(e.EndTime.endsWith('Z') ? e.EndTime : e.EndTime + 'Z'),
              IsAllDay: e.IsAllDay,
            }));
            setEvents(mapped);
            setSchedulerKey(prev => prev + 1); // <-- Key erhöhen
          }
        }}
        initialData={modalInitialData}
        groupName={groups.find(g => g.id === selectedGroupId) ?? { id: selectedGroupId, name: '' }}
      />
      <ScheduleComponent
        key={schedulerKey} // <-- dynamischer Key
        height="750px"
        locale="de"
        currentView="Week"
        eventSettings={{
          dataSource: events,
        }}
        cellClick={args => {
          // args.startTime und args.endTime sind Date-Objekte
          args.cancel = true; // Verhindert die Standardaktion
          setModalInitialData({
            startDate: args.startTime,
            startTime: args.startTime,
            endTime: args.endTime,
          });
          setModalOpen(true);
        }}
        eventRendered={(args: EventRenderedArgs) => {
          if (selectedGroupId && args.data && args.data.Id) {
            const groupColor = getGroupColor(selectedGroupId, groups);
            if (groupColor) {
              args.element.style.backgroundColor = groupColor;
            }
          }
        }}
        actionBegin={async (args: ActionEventArgs) => {
          if (args.requestType === 'eventRemove') {
            // args.data ist ein Array von zu löschenden Events
            const toDelete = Array.isArray(args.data) ? args.data : [args.data];
            for (const ev of toDelete) {
              try {
                await deleteEvent(ev.Id); // Deine API-Funktion
              } catch (err) {
                // Optional: Fehlerbehandlung
                console.error('Fehler beim Löschen:', err);
              }
            }
            // Events nach Löschen neu laden
            if (selectedGroupId) {
              fetchEvents(selectedGroupId)
                .then((data: RawEvent[]) => {
                  const mapped: Event[] = data.map(e => ({
                    Id: e.Id,
                    Subject: e.Subject,
                    StartTime: new Date(e.StartTime),
                    EndTime: new Date(e.EndTime),
                    IsAllDay: e.IsAllDay,
                  }));
                  setEvents(mapped);
                })
                .catch(console.error);
            }
            // Syncfusion soll das Event nicht selbst löschen
            args.cancel = true;
          }
        }}
        firstDayOfWeek={1}
      >
        <ViewsDirective>
          <ViewDirective option="Day" />
          <ViewDirective option="Week" />
          <ViewDirective option="WorkWeek" />
          <ViewDirective option="Month" />
          <ViewDirective option="Agenda" />
        </ViewsDirective>
        <Inject services={[Day, Week, WorkWeek, Month, Agenda]} />
      </ScheduleComponent>
    </div>
  );
};

export default Appointments;
