import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core';
import { RouterLink } from '@angular/router';
import { take } from 'rxjs/operators';
import { forkJoin } from 'rxjs';
import { TranslatePipe } from '../../../i18n/translate.pipe';
import { LangRoutePipe } from '../../../pipes/lang-route.pipe';
import { LanguageService } from '../../../services/language.service';
import { ProjectEditorFacade } from '../facade/project-editor.facade';
import { BackofficeDataService } from '../../../core/backoffice/backoffice-data.service';
import { BUILDER_GROUPS } from '../builder/builder-groups.model';
import { BuilderSectionStatus } from '../models/project-editor.model';
import { IconComponent } from '../../../shared/ui/icon/icon.component';
import { AppIconName } from '../../../shared/ui/icon/icon-registry';

const STATUS_ICON: Record<BuilderSectionStatus, AppIconName> = {
  complete: 'checkCircle',
  'in-progress': 'circle',
  'not-started': 'circle',
  unknown: 'help',
};

const STATUS_LABEL_KEY: Record<BuilderSectionStatus, string> = {
  complete: 'builder.statusComplete',
  'in-progress': 'builder.statusInProgress',
  'not-started': 'builder.statusNotStarted',
  unknown: 'builder.statusUnknown',
};

type ReadinessState = 'loading' | 'true' | 'false' | 'unknown';

interface ReadinessItem {
  labelKey: string;
  state: ReadinessState;
}

const SECTION_LABEL_KEYS: Record<string, string> = {
  general: 'builder.general',
  branding: 'builder.branding',
  theme: 'builder.theme',
  header: 'builder.header',
  footer: 'builder.footer',
  homepage: 'builder.homepage',
  widgets: 'builder.widgets',
  'static-pages': 'builder.staticPages',
  features: 'builder.marketplaceFeatures',
  languages: 'builder.languagesTab',
  navigation: 'builder.navigationTab',
  preview: 'builder.preview',
};

@Component({
  selector: 'app-builder-overview-page',
  standalone: true,
  imports: [RouterLink, TranslatePipe, LangRoutePipe, IconComponent],
  templateUrl: './builder-overview-page.component.html',
  styleUrl: './builder-overview-page.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BuilderOverviewPageComponent {
  readonly facade = inject(ProjectEditorFacade);
  private readonly languageService = inject(LanguageService);
  private readonly backofficeData = inject(BackofficeDataService);

  readonly groups = BUILDER_GROUPS;
  readonly sectionLabelKeys = SECTION_LABEL_KEYS;

  readonly bootstrap = this.facade.bootstrap;
  readonly readinessPercent = this.facade.readinessPercent;
  readonly nextRecommendedSection = this.facade.nextRecommendedSection;
  readonly groupStatus = this.facade.groupStatus;
  readonly modifiedSections = this.facade.modifiedSections;
  readonly dirty = this.facade.dirty;
  readonly status = this.facade.status;

  private readonly catalogCounts = signal<{ categories: number; products: number } | 'loading' | 'error'>('loading');

  readonly nextStepLabelKey = computed(() => {
    const section = this.nextRecommendedSection();
    return section ? SECTION_LABEL_KEYS[section] : null;
  });

  readonly nextStepRoute = computed(() => {
    const section = this.nextRecommendedSection();
    return section ? ['/', this.languageService.currentLanguage(), 'edit', section] : null;
  });

  readonly readinessChecklist = computed<ReadinessItem[]>(() => {
    const current = this.bootstrap();
    const counts = this.catalogCounts();
    const item = (labelKey: string, state: ReadinessState): ReadinessItem => ({ labelKey, state });

    if (!current) {
      return [
        item('dashboard.healthProductsCount', 'loading'),
      ];
    }

    const staticPages = current.staticPages;
    const staticPagesCount = staticPages ? (Array.isArray(staticPages) ? staticPages.length : Object.keys(staticPages).length) : 0;

    return [
      item('builder.readinessLogoUploaded', current.branding?.logoUrl ? 'true' : 'false'),
      item('builder.readinessThemeConfigured', current.theme?.themeId ? 'true' : 'false'),
      item('builder.readinessHomepageConfigured', this.facade.homepageWidgets().length > 0 ? 'true' : 'false'),
      item('builder.readinessLanguagesConfigured', (current.localization?.supportedLocales?.length ?? 0) > 0 ? 'true' : 'false'),
      item('builder.readinessContentPagesAdded', staticPagesCount > 0 ? 'true' : 'false'),
      item('builder.readinessCategoriesExist', counts === 'loading' ? 'loading' : counts === 'error' ? 'unknown' : counts.categories > 0 ? 'true' : 'false'),
      item('builder.readinessProductsExist', counts === 'loading' ? 'loading' : counts === 'error' ? 'unknown' : counts.products > 0 ? 'true' : 'false'),
      item('builder.readinessPreviewReviewed', 'unknown'),
      item('builder.readinessPublished', this.facade.lastPublishedAt() !== null ? 'true' : 'false'),
    ];
  });

  readonly statusIcon = STATUS_ICON;
  readonly statusLabelKey = STATUS_LABEL_KEY;

  constructor() {
    this.facade.loadBootstrap();
    forkJoin({
      categories: this.backofficeData.loadCategories(),
      products: this.backofficeData.loadProducts(),
    }).pipe(take(1)).subscribe({
      next: ({ categories, products }) => this.catalogCounts.set({ categories: categories.length, products: products.length }),
      error: () => this.catalogCounts.set('error'),
    });
  }

  groupSectionRoute(sectionId: string): string[] {
    return ['/', this.languageService.currentLanguage(), 'edit', sectionId];
  }

  formatTimestamp(timestamp: number | null): string | null {
    return timestamp ? new Date(timestamp).toLocaleString(this.languageService.currentLanguage()) : null;
  }
}
