import {
  Injectable,
  computed,
  inject
} from '@angular/core';

import {
  ThemeContainerKey,
  ThemeGridEditorItem,
  ThemeGridRect
} from '../../domain/models/theme.model';
import { createDefaultThemeDocument, createDefaultThemeLayout } from '../../domain/logic/theme-defaults.logic';
import { ThemeRegistryService } from './theme-registry.service';
import { ThemeService } from './theme.service';

@Injectable({ providedIn: 'root' })
export class LayoutSyncService {
  readonly draftLayout = computed(() => this.theme.draftTheme().layout);

  readonly registry = inject(ThemeRegistryService);
  readonly theme = inject(ThemeService);

  containers() {
    return this.registry.layoutContainers();
  }

  itemsForContainer(containerKey: ThemeContainerKey): ThemeGridEditorItem[] {
    const draftTheme = this.theme.draftTheme();
    const defaults = createDefaultThemeLayout();

    return this.registry
      .entries()
      .filter((entry) => entry.layoutEditable && entry.container === containerKey)
      .map((entry) => ({
        key: entry.key,
        label: entry.label,
        description: entry.description,
        grid: draftTheme.layout[entry.key]?.grid ?? defaults[entry.key].grid
      }));
  }

  updateGrid(key: string, grid: ThemeGridRect): void {
    this.theme.ensureLayoutEntry(key);
    this.theme.updateStructuredDraft(
      (draft: ReturnType<typeof createDefaultThemeDocument>) => {
        draft.layout[key] = {
          ...draft.layout[key],
          grid
        };
      },
      true,
      `${key} layout updated.`
    );
  }

  resetContainer(containerKey: ThemeContainerKey): void {
    const defaults = createDefaultThemeLayout();

    this.theme.updateStructuredDraft(
      (draft: ReturnType<typeof createDefaultThemeDocument>) => {
        for (const entry of this.registry.entries()) {
          if (entry.container === containerKey && entry.layoutEditable) {
            draft.layout[entry.key] = defaults[entry.key];
          }
        }
      },
      true,
      `${containerKey} restored to its default layout.`
    );
  }
}
