import { Component, computed, effect, input, output, signal } from '@angular/core';

import { TooltipDirective } from '../../directives/tooltip/tooltip.directive';

let nextFilterCardId = 0;

@Component({
  selector: 'app-filter-card',
  standalone: true,
  imports: [TooltipDirective],
  templateUrl: './filter-card.html',
  styles: `
    :host { display: block; }
    .filter-card-body-grid {
      display: grid;
      grid-template-rows: 1fr;
      transition: grid-template-rows 200ms ease, visibility 200ms ease;
      visibility: visible;
    }
    .filter-card-body-grid.is-collapsed {
      grid-template-rows: 0fr;
      visibility: hidden;
    }
    .filter-card-body-content { min-height: 0; overflow: hidden; }
    @media (prefers-reduced-motion: reduce) {
      .filter-card-body-grid { transition: none; }
    }
  `
})
export class FilterCard {
  readonly title = input<string>('Filters');
  readonly titleIcon = input<string | null>(null);
  readonly defaultCollapsed = input<boolean>(false);
  readonly collapsible = input<boolean>(true);
  readonly showToggleButton = input<boolean>(true);
  readonly collapsedIcon = input<string>('ri-filter-3-line');
  readonly expandedIcon = input<string>('ri-arrow-up-s-line');
  readonly collapsedTooltip = input<string>('Show Filters');
  readonly expandedTooltip = input<string>('Hide Filters');
  readonly cardClass = input<string>('');
  readonly headerClass = input<string>('');
  readonly bodyClass = input<string>('');
  readonly toggleButtonClass = input<string>('');
  readonly contentId = input<string>('');

  readonly collapseChanged = output<boolean>();
  readonly collapsed = signal(false);

  private readonly generatedContentId = `filter-card-content-${++nextFilterCardId}`;

  readonly resolvedContentId = computed(() => this.contentId().trim() || this.generatedContentId);
  readonly currentIcon = computed(() =>
    this.collapsed() ? this.collapsedIcon() : this.expandedIcon()
  );
  readonly currentTooltip = computed(() =>
    this.collapsed() ? this.collapsedTooltip() : this.expandedTooltip()
  );

  constructor() {
    effect(() => this.collapsed.set(this.defaultCollapsed()));
  }

  toggleCollapse(): void {
    if (!this.collapsible()) {
      return;
    }

    const collapsed = !this.collapsed();
    this.collapsed.set(collapsed);
    this.collapseChanged.emit(collapsed);
  }
}
