import { CommonModule } from '@angular/common';
import { ChangeDetectionStrategy, Component, Input, inject } from '@angular/core';
import { NgComponentOutlet } from '@angular/common';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { PageRenderModel } from '../../dynamic-renderer/page-renderer/page-renderer.model';
import { WidgetRenderNode } from '../../dynamic-renderer/widget-host/widget-host.model';
import { ResolvedWidget } from '../../widgets/contracts/widget-component.contract';
import { WidgetHostService } from '../../dynamic-renderer/widget-host/widget-host.service';
import { LanguageService } from '../../services/language.service';
import { Category } from '../../core/categories/models/category-domain.model';
import { AuthService } from '@marketplaces/auth';

@Component({
  selector: 'app-dynamic-page-layout',
  standalone: true,
  imports: [CommonModule, NgComponentOutlet],
  template: `
    @if (model) {
      <main class="dynamic-page-layout" [attr.data-layout]="model.layout">
        @for (section of model.sections; track section.id) {
          <section
            class="section dynamic-section"
            [attr.data-section-type]="section.type"
            [attr.data-section-layout]="section.layout?.strategy ?? section.type"
            [class.dynamic-section--desktop-hidden]="section.visibility?.desktop === false"
            [class.dynamic-section--tablet-hidden]="section.visibility?.tablet === false"
            [class.dynamic-section--mobile-hidden]="section.visibility?.mobile === false"
          >
            <div class="page-container">
              <div
                class="dynamic-section__content"
                [style.--section-columns]="section.layout?.columns ?? null"
                [style.--section-gap]="section.layout?.gap ?? null"
                [style.--section-align]="section.layout?.align ?? null"
              >
                @for (widget of section.widgets; track widget.id) {
                  @if (isWidgetPermitted(widget.source)) {
                  <div
                    class="dynamic-widget"
                    [attr.data-widget-type]="widget.type"
                    [attr.data-widget-title]="widget.source.title ?? null"
                    [attr.data-widget-subtitle]="widget.source.subtitle ?? null"
                    [attr.data-widget-animation]="widget.source.animation?.name ?? null"
                    [style.--widget-padding]="widget.padding ?? null"
                    [style.--widget-animation-duration]="widget.source.animation?.duration ?? null"
                    [style.--widget-animation-delay]="widget.source.animation?.delay ?? null"
                    [style.--widget-animation-timing]="widget.source.animation?.timingFunction ?? null"
                    [style.animation-name]="widget.source.animation?.name ?? null"
                    [ngStyle]="widget.source.style ?? null"
                    [class.dynamic-widget--desktop-hidden]="widget.visibility?.desktop === false"
                    [class.dynamic-widget--tablet-hidden]="widget.visibility?.tablet === false"
                    [class.dynamic-widget--mobile-hidden]="widget.visibility?.mobile === false"
                  >
                    @if (resolveWidget(widget, section, model.id) | async; as resolved) {
                      @if (widget.type === 'categories') {
                        <ng-container *ngComponentOutlet="$any(resolved).component; inputs: { section: $any(resolved).section, data: $any(resolved).data, categorySelectedCallback: onCategorySelected.bind(this) }"></ng-container>
                      } @else {
                        <ng-container *ngComponentOutlet="$any(resolved).component; inputs: { section: $any(resolved).section, data: $any(resolved).data }"></ng-container>
                      }
                    }
                  </div>
                  }
                }
              </div>
            </div>
          </section>
        }
      </main>
    }
  `,
  styles: [
    `
      .dynamic-page-layout { display: block; }

      .dynamic-page-layout[data-layout='sidebar-left'] .dynamic-section[data-section-type='sidebar-left'] .dynamic-section__content {
        grid-template-columns: minmax(240px, 320px) minmax(0, 1fr);
      }

      .dynamic-page-layout[data-layout='minimal'] .dynamic-section[data-section-type='hero'] {
        display: none;
      }

      .dynamic-page-layout[data-layout='carousel-home'] .dynamic-section[data-section-type='hero'] {
        order: -1;
      }

      .dynamic-section__content {
        display: grid;
        gap: var(--section-gap, 1rem);
        align-items: var(--section-align, stretch);
      }

      .dynamic-widget {
        padding: var(--widget-padding, 0);
        animation-duration: var(--widget-animation-duration, initial);
        animation-delay: var(--widget-animation-delay, initial);
        animation-timing-function: var(--widget-animation-timing, initial);
      }

      .dynamic-section[data-section-layout='grid'] .dynamic-section__content {
        grid-template-columns: repeat(var(--section-columns, 1), minmax(0, 1fr));
      }

      .dynamic-section[data-section-layout='hero'] .dynamic-section__content {
        grid-template-columns: minmax(0, 1fr);
      }

      .dynamic-section--desktop-hidden { display: none; }

      @media (max-width: 1023px) {
        .dynamic-section--tablet-hidden { display: none; }
        .dynamic-widget--tablet-hidden { display: none; }

        .dynamic-page-layout[data-layout='sidebar-left'] .dynamic-section[data-section-type='sidebar-left'] .dynamic-section__content {
          grid-template-columns: 1fr;
        }
      }

      @media (max-width: 767px) {
        .dynamic-section--mobile-hidden { display: none; }
        .dynamic-widget--mobile-hidden { display: none; }
      }

      .dynamic-widget--desktop-hidden { display: none; }
    `
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DynamicPageLayoutComponent {
  @Input() model: PageRenderModel | null = null;

  private readonly authService = inject(AuthService);

  constructor(
    private readonly widgetHost: WidgetHostService,
    private readonly router: Router,
    private readonly languageService: LanguageService
  ) {}

  resolveWidget(widget: WidgetRenderNode, section: PageRenderModel['sections'][number], pageId: string): Observable<ResolvedWidget> {
    return this.widgetHost.resolveWidget(widget.source, section.source, pageId);
  }

  onCategorySelected(category: Category): void {
    this.router.navigate([`/${this.languageService.currentLanguage()}/catalog`, category.id]);
  }

  isWidgetPermitted(widget: WidgetRenderNode['source']): boolean {
    const permissions = widget.permissions;
    if (!permissions) {
      return true;
    }

    if (permissions.requireAuthenticated && !this.authService.isAuthenticated()) {
      return false;
    }

    return true;
  }
}
