import { Component, Input, computed, signal } from '@angular/core';
import { TranslatePipe } from '@ngx-translate/core';
import { RecipeDetail } from '../../core/models/recipe.models';
import { CategoryBadgeComponent } from '../../shared/components/category-badge.component';
import { nextSort, sortBy, sortIndicator, type SortDirection } from '../../core/utils/sort.util';

type IngredientSortColumn = 'name' | 'amount';

@Component({
  selector: 'app-recipe-detail-view',
  standalone: true,
  imports: [TranslatePipe, CategoryBadgeComponent],
  template: `
    <article class="space-y-8">
      <header class="space-y-3">
        <app-category-badge [category]="recipe.mealCategory" />
        <h1 class="text-3xl font-extrabold tracking-tight">{{ recipe.name }}</h1>
        @if (recipe.prepTimeMinutes != null) {
          <p class="inline-flex items-center gap-1.5 text-sm text-slate-500 dark:text-slate-400">
            <span aria-hidden="true">⏱</span>
            {{ 'recipes.prepTime' | translate: { count: recipe.prepTimeMinutes } }}
          </p>
        }
      </header>

      <section class="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <div class="rounded-2xl border border-slate-200 bg-white px-4 py-3 text-center dark:border-slate-800 dark:bg-slate-900">
          <p class="text-2xl font-extrabold text-orange-500">
            {{ recipe.calories ?? '—' }}
            @if (recipe.calories != null) {
              <span class="text-sm font-semibold"> kcal</span>
            }
          </p>
          <p class="mt-0.5 text-xs font-medium uppercase tracking-wide text-slate-500 dark:text-slate-400">
            {{ 'recipes.calories' | translate }}
          </p>
        </div>
        <div class="rounded-2xl border border-slate-200 bg-white px-4 py-3 text-center dark:border-slate-800 dark:bg-slate-900">
          <p class="text-2xl font-extrabold text-brand-600">
            {{ recipe.protein ?? '—' }}
            @if (recipe.protein != null) {
              <span class="text-sm font-semibold"> g</span>
            }
          </p>
          <p class="mt-0.5 text-xs font-medium uppercase tracking-wide text-slate-500 dark:text-slate-400">
            {{ 'recipes.protein' | translate }}
          </p>
        </div>
        <div class="rounded-2xl border border-slate-200 bg-white px-4 py-3 text-center dark:border-slate-800 dark:bg-slate-900">
          <p class="text-2xl font-extrabold text-amber-500">
            {{ recipe.fat ?? '—' }}
            @if (recipe.fat != null) {
              <span class="text-sm font-semibold"> g</span>
            }
          </p>
          <p class="mt-0.5 text-xs font-medium uppercase tracking-wide text-slate-500 dark:text-slate-400">
            {{ 'recipes.fat' | translate }}
          </p>
        </div>
        <div class="rounded-2xl border border-slate-200 bg-white px-4 py-3 text-center dark:border-slate-800 dark:bg-slate-900">
          <p class="text-2xl font-extrabold text-sky-500">
            {{ recipe.carbs ?? '—' }}
            @if (recipe.carbs != null) {
              <span class="text-sm font-semibold"> g</span>
            }
          </p>
          <p class="mt-0.5 text-xs font-medium uppercase tracking-wide text-slate-500 dark:text-slate-400">
            {{ 'recipes.carbs' | translate }}
          </p>
        </div>
      </section>

      <div class="grid gap-8 lg:grid-cols-[1fr_1.4fr]">
        <section>
          <h2 class="text-lg font-bold">{{ 'recipes.ingredients' | translate }}</h2>
          @if (recipe.ingredients.length === 0) {
            <p class="mt-3 text-sm text-slate-500">{{ 'recipes.noIngredients' | translate }}</p>
          } @else {
            <div class="mt-4 overflow-hidden rounded-2xl border border-slate-200 dark:border-slate-800">
              <div class="grid grid-cols-[1fr_auto] border-b border-slate-200 bg-slate-50 px-4 py-2 text-xs font-semibold uppercase tracking-wide text-slate-500 dark:border-slate-800 dark:bg-slate-800/50">
                <button type="button" class="text-left hover:text-slate-700 dark:hover:text-slate-200" (click)="toggleIngredientSort('name')">
                  {{ 'ingredientCatalog.columns.name' | translate }}{{ ingredientIndicator('name') }}
                </button>
                <button type="button" class="text-right hover:text-slate-700 dark:hover:text-slate-200" (click)="toggleIngredientSort('amount')">
                  {{ 'diet.grams' | translate }}{{ ingredientIndicator('amount') }}
                </button>
              </div>
              <ul class="divide-y divide-slate-200 dark:divide-slate-800">
                @for (ing of sortedIngredients(); track ing.id) {
                  <li class="grid grid-cols-[1fr_auto] items-center px-4 py-3 text-sm">
                    <span>{{ ing.name }}</span>
                    <span class="font-medium text-slate-500 dark:text-slate-400">
                      {{ formatAmount(ing.amountGrams, ing.unit) }}
                    </span>
                  </li>
                }
              </ul>
            </div>
          }
        </section>

        <section>
          <h2 class="text-lg font-bold">{{ 'recipes.preparation' | translate }}</h2>
          @if (recipe.steps.length === 0) {
            <p class="mt-3 text-sm text-slate-500">{{ 'recipes.noSteps' | translate }}</p>
          } @else {
            <ol class="mt-4 space-y-4">
              @for (step of recipe.steps; track step.id) {
                <li class="flex gap-4">
                  <span class="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-brand-600 text-sm font-bold text-white">
                    {{ step.stepNumber }}
                  </span>
                  <p class="pt-1 text-sm leading-relaxed text-slate-700 dark:text-slate-300">
                    {{ step.description }}
                  </p>
                </li>
              }
            </ol>
          }
        </section>
      </div>
    </article>
  `,
})
export class RecipeDetailViewComponent {
  @Input({ required: true }) recipe!: RecipeDetail;

  readonly ingredientSort = signal<{ column: IngredientSortColumn; direction: SortDirection }>({
    column: 'name',
    direction: 'asc',
  });

  readonly sortedIngredients = computed(() => {
    const { column, direction } = this.ingredientSort();
    return sortBy(this.recipe.ingredients, direction, (ing) =>
      column === 'name' ? ing.name : ing.amountGrams,
    );
  });

  formatAmount(amount: number | null, unit: string | null): string {
    if (amount == null && !unit) return '';
    if (amount == null) return unit ?? '';
    const display = Number.isInteger(amount) ? amount.toString() : amount.toString();
    return unit ? `${display} ${unit}` : `${display} g`;
  }

  toggleIngredientSort(column: IngredientSortColumn): void {
    this.ingredientSort.update((current) => nextSort(current, column));
  }

  ingredientIndicator(column: IngredientSortColumn): string {
    return sortIndicator(this.ingredientSort(), column);
  }
}
