import { Component, inject, OnInit, signal } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { RecipeService } from '../../core/services/recipe.service';
import { RecipeDetail } from '../../core/models/recipe.models';
import { RecipeDetailViewComponent } from '../recipes/recipe-detail-view.component';
import { ErrorStateComponent } from '../../shared/components/error-state.component';
import { SkeletonComponent } from '../../shared/components/skeleton.component';
import { extractApiError } from '../../core/utils/api-error.util';

@Component({
  selector: 'app-recipe-detail-page',
  standalone: true,
  imports: [TranslatePipe, RecipeDetailViewComponent, ErrorStateComponent, SkeletonComponent],
  template: `
    <div class="space-y-6">
      <button type="button" (click)="goBack()" class="btn-secondary">
        ← {{ 'common.back' | translate }}
      </button>

      @if (loading()) {
        <div class="space-y-6">
          <app-skeleton className="h-6 w-24" />
          <app-skeleton className="h-9 w-2/3" />
          <div class="grid grid-cols-2 gap-3 sm:grid-cols-4">
            @for (i of [0, 1, 2, 3]; track i) {
              <app-skeleton className="h-20" />
            }
          </div>
          <app-skeleton className="h-64" />
        </div>
      }

      @if (error()) {
        <app-error-state [message]="error()!" [showRetry]="true" (retry)="load()" />
      }

      @if (!loading() && !error() && recipe()) {
        <app-recipe-detail-view [recipe]="recipe()!" (recipeUpdated)="recipe.set($event)" />
      }
    </div>
  `,
})
export class RecipeDetailPageComponent implements OnInit {
  private readonly route = inject(ActivatedRoute);
  private readonly location = inject(Location);
  private readonly recipeService = inject(RecipeService);
  private readonly translate = inject(TranslateService);

  readonly loading = signal(true);
  readonly error = signal<string | null>(null);
  readonly recipe = signal<RecipeDetail | null>(null);

  ngOnInit(): void {
    this.load();
  }

  load(): void {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    if (!Number.isFinite(id)) {
      this.error.set(this.translate.instant('errors.loadRecipeFailed'));
      this.loading.set(false);
      return;
    }

    this.loading.set(true);
    this.error.set(null);
    this.recipeService.getRecipeById(id).subscribe({
      next: (data) => {
        this.recipe.set(data);
        this.loading.set(false);
      },
      error: (err) => {
        this.error.set(extractApiError(err, this.translate.instant('errors.loadRecipeFailed')));
        this.loading.set(false);
      },
    });
  }

  goBack(): void {
    this.location.back();
  }
}
