import { Component, computed, input, output, signal } from '@angular/core';
import { RichTextBlock } from '@shared/kernel/rich-text';
import { PlaceholderOption } from '@shared/ui/rich-text-editor/rich-text-editor.component';
import { ButtonComponent } from '@shared/ui/button/button.component';
import { HeadingComponent } from '@shared/ui/heading/heading.component';
import { LetterSection, LibraryPassage } from '@brief/domain/brief';
import { BriefMsg } from '@brief/domain/brief.machine';
import { LetterBlockComponent } from '@brief/ui/letter-block/letter-block.component';
import { PassagePickerComponent } from '@brief/ui/passage-picker/passage-picker.component';

/** Organism: one template section — its ordered blocks plus (when editable) the
    add-passages and add-free-text actions. Maps child events to `BriefMsg`s; sections
    themselves can never be added/removed/reordered (no message exists for it). */
@Component({
  selector: 'app-letter-section',
  imports: [ButtonComponent, HeadingComponent, LetterBlockComponent, PassagePickerComponent],
  styles: [`
    :host{display:block}
    .blocks{display:grid;gap:var(--rhc-space-max-lg);margin-block:var(--rhc-space-max-md)}
    .actions{display:flex;flex-wrap:wrap;gap:var(--rhc-space-max-sm)}
    .required{color:var(--rhc-color-foreground-subtle)}
    .empty{color:var(--rhc-color-foreground-subtle);font-style:italic}
  `],
  template: `
    <app-heading [level]="3">
      {{ section().title }}
      @if (section().required) { <span class="required">· {{ requiredLabel() }}</span> }
    </app-heading>

    <div class="blocks">
      @for (block of section().blocks; track block.blockId) {
        <app-letter-block
          [block]="block"
          [placeholders]="placeholders()"
          [editable]="editable()"
          (contentChanged)="onContent(block.blockId, $event)"
          (removed)="edit.emit({ tag: 'BlockRemoved', blockId: block.blockId })"
          (moved)="onMove(block.blockId, $event)" />
      } @empty {
        <p class="empty">{{ emptyLabel() }}</p>
      }
    </div>

    @if (editable()) {
      <div class="actions">
        <app-button variant="secondary" (click)="pickerOpen.set(!pickerOpen())">{{ addPassageLabel() }}</app-button>
        <app-button variant="subtle" (click)="edit.emit({ tag: 'FreeTextBlockAdded', sectionKey: section().sectionKey })">{{ addFreeLabel() }}</app-button>
      </div>
      @if (pickerOpen()) {
        <app-passage-picker [passages]="sectionPassages()" (insert)="onInsert($event)" />
      }
    }
  `,
})
export class LetterSectionComponent {
  section = input.required<LetterSection>();
  availablePassages = input<readonly LibraryPassage[]>([]);
  placeholders = input<readonly PlaceholderOption[]>([]);
  editable = input(false);
  edit = output<BriefMsg>();

  requiredLabel = input($localize`:@@brief.section.required:verplicht`);
  emptyLabel = input($localize`:@@brief.section.empty:Nog geen tekst in deze sectie.`);
  addPassageLabel = input($localize`:@@brief.section.addPassage:Standaardtekst toevoegen`);
  addFreeLabel = input($localize`:@@brief.section.addFree:Vrije tekst toevoegen`);

  protected pickerOpen = signal(false);
  protected sectionPassages = computed(() => this.availablePassages().filter((p) => p.sectionKey === this.section().sectionKey));

  protected onContent(blockId: string, content: RichTextBlock) {
    this.edit.emit({ tag: 'BlockContentEdited', blockId, content });
  }

  protected onMove(blockId: string, direction: -1 | 1) {
    const i = this.section().blocks.findIndex((b) => b.blockId === blockId);
    this.edit.emit({ tag: 'BlockMovedWithinSection', blockId, toIndex: i + direction });
  }

  protected onInsert(passages: LibraryPassage[]) {
    this.edit.emit({ tag: 'PassagesInserted', sectionKey: this.section().sectionKey, passages });
    this.pickerOpen.set(false);
  }
}
