import { Container } from '@novadi/core';
import {
  registerCoreServices,
  CalendarApp,
  IndexedDBContext,
  SettingsService,
  ViewConfigService,
  EventService,
  EventBus,
  CalendarEvents,
  EventPersistenceManager
} from 'calendar';
import { registerSchedules } from 'calendar/schedules';

async function init() {
  // Check if database already exists
  const databases = await indexedDB.databases();
  const dbExists = databases.some(db => db.name === 'CalendarTestDB');

  const container = new Container();
  const builder = container.builder();
  registerCoreServices(builder, {
    dbConfig: { dbName: 'CalendarTestDB', dbVersion: 4 }
  });
  registerSchedules(builder);
  const app = builder.build();

  console.log('Container created');

  // Initialize IndexedDB
  const dbContext = app.resolveType<IndexedDBContext>();
  await dbContext.initialize();
  console.log('IndexedDB initialized');

  const settingsService = app.resolveType<SettingsService>();
  const viewConfigService = app.resolveType<ViewConfigService>();
  const eventService = app.resolveType<EventService>();

  if (dbExists) {
    console.log('Database exists, skipping seed');
  } else {
    console.log('Seeding data...');
    await seedData(settingsService, viewConfigService, eventService);
  }

  // Initialize and render
  const calendarApp = app.resolveType<CalendarApp>();
  const containerEl = document.querySelector('swp-calendar-container') as HTMLElement;
  await calendarApp.init(containerEl);

  const eventBus = app.resolveType<EventBus>();
  eventBus.emit(CalendarEvents.CMD_RENDER, { viewId: 'simple' });

  console.log('Calendar rendered');

  // Debug listeners
  document.addEventListener('event:drag-end', (e) => {
    console.log('event:drag-end:', (e as CustomEvent).detail);
  });
  document.addEventListener('event:updated', (e) => {
    console.log('event:updated:', (e as CustomEvent).detail);
  });

  const persistenceManager = app.resolveType<EventPersistenceManager>();
  console.log('EventPersistenceManager resolved:', persistenceManager);
}

async function seedData(
  settingsService: SettingsService,
  viewConfigService: ViewConfigService,
  eventService: EventService
) {
  // Grid settings
  await settingsService.save({
    id: 'grid',
    dayStartHour: 8,
    dayEndHour: 17,
    workStartHour: 9,
    workEndHour: 16,
    hourHeight: 64,
    snapInterval: 15,
    syncStatus: 'synced'
  });

  // Workweek settings
  await settingsService.save({
    id: 'workweek',
    presets: {
      standard: { id: 'standard', label: 'Standard', workDays: [1, 2, 3, 4, 5], periodDays: 7 }
    },
    defaultPreset: 'standard',
    firstDayOfWeek: 1,
    syncStatus: 'synced'
  });

  // Simple view config
  await viewConfigService.save({
    id: 'simple',
    groupings: [{ type: 'date', values: [], idProperty: 'date', derivedFrom: 'start' }],
    syncStatus: 'synced'
  });

  // Add test events
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  console.log('Event date:', today.toISOString());

  const start1 = new Date(today);
  start1.setHours(9, 0, 0, 0);
  const end1 = new Date(today);
  end1.setHours(10, 0, 0, 0);

  await eventService.save({
    id: '1',
    title: 'Morgenmøde',
    start: start1,
    end: end1,
    type: 'meeting',
    allDay: false,
    syncStatus: 'synced'
  });

  const start2 = new Date(today);
  start2.setHours(12, 0, 0, 0);
  const end2 = new Date(today);
  end2.setHours(13, 0, 0, 0);

  await eventService.save({
    id: '2',
    title: 'Frokost',
    start: start2,
    end: end2,
    type: 'break',
    allDay: false,
    syncStatus: 'synced'
  });
}

init().catch(console.error);
