import { Component, inject, OnInit, signal } from '@angular/core';
import { RouterLink } from '@angular/router';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { AuthService } from '../../core/services/auth.service';
import { RecipeService } from '../../core/services/recipe.service';
import {
  CategoryCount,
  MealCategory,
  MEAL_CATEGORY_I18N_KEYS,
  MEAL_CATEGORY_ROUTES,
} from '../../core/models/recipe.models';
import { ErrorStateComponent } from '../../shared/components/error-state.component';
import { SkeletonComponent } from '../../shared/components/skeleton.component';
import { translatePlural } from '../../core/utils/plural-translate.util';
import { extractApiError } from '../../core/utils/api-error.util';

const CARD_META: Record<
  MealCategory,
  { emoji: string; gradient: string }
> = {
  [MealCategory.Breakfast]: { emoji: '☕', gradient: 'from-amber-400 to-orange-500' },
  [MealCategory.SecondBreakfast]: { emoji: '🥐', gradient: 'from-sky-400 to-blue-500' },
  [MealCategory.Lunch]: { emoji: '🍲', gradient: 'from-brand-400 to-brand-600' },
  [MealCategory.Dinner]: { emoji: '🌙', gradient: 'from-violet-400 to-purple-600' },
};

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [RouterLink, TranslatePipe, ErrorStateComponent, SkeletonComponent],
  template: `
    <div class="space-y-8">
      <header>
        <h1 class="text-2xl font-extrabold tracking-tight sm:text-3xl">
          @if (auth.user()?.userName) {
            {{ 'dashboard.welcomeNamed' | translate: { name: auth.user()!.userName } }}
          } @else {
            {{ 'dashboard.welcome' | translate }}
          }
        </h1>
        <p class="mt-1 text-slate-500 dark:text-slate-400">{{ 'dashboard.subtitle' | translate }}</p>
      </header>

      @if (error()) {
        <app-error-state [message]="error()!" [showRetry]="true" (retry)="load()" />
      } @else {
        <div class="grid grid-cols-1 gap-5 sm:grid-cols-2">
          @if (loading()) {
            @for (i of [0, 1, 2, 3]; track i) {
              <app-skeleton className="h-40" />
            }
          } @else {
            @for (cat of categories(); track cat.category) {
              <a
                [routerLink]="routeFor(cat.category)"
                class="card group relative overflow-hidden p-6 hover:shadow-lg"
              >
                <div
                  class="absolute -right-6 -top-6 grid h-24 w-24 place-items-center rounded-full bg-gradient-to-br text-3xl opacity-90"
                  [class]="metaFor(cat.category).gradient"
                >
                  {{ metaFor(cat.category).emoji }}
                </div>
                <p class="text-sm font-medium text-slate-500 dark:text-slate-400">
                  {{ 'common.category' | translate }}
                </p>
                <h2 class="mt-1 text-xl font-bold">{{ categoryLabel(cat.category) | translate }}</h2>
                <p class="mt-6 text-3xl font-extrabold text-brand-600">{{ cat.count }}</p>
                <p class="text-sm text-slate-500 dark:text-slate-400">
                  {{ recipeCountLabel(cat.count) }}
                </p>
                <span class="mt-4 inline-flex items-center gap-1 text-sm font-semibold text-brand-600 group-hover:gap-2">
                  {{ 'dashboard.viewRecipes' | translate }} →
                </span>
              </a>
            }
          }
        </div>
      }
    </div>
  `,
})
export class DashboardComponent implements OnInit {
  private readonly recipeService = inject(RecipeService);
  private readonly translate = inject(TranslateService);
  readonly auth = inject(AuthService);

  readonly loading = signal(true);
  readonly error = signal<string | null>(null);
  readonly categories = signal<CategoryCount[]>([]);

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

  load(): void {
    this.loading.set(true);
    this.error.set(null);
    this.recipeService.getCategories().subscribe({
      next: (data) => {
        this.categories.set(data);
        this.loading.set(false);
      },
      error: (err) => {
        this.error.set(extractApiError(err, this.translate.instant('errors.loadCategoriesFailed')));
        this.loading.set(false);
      },
    });
  }

  routeFor(category: MealCategory): string {
    return MEAL_CATEGORY_ROUTES[category];
  }

  categoryLabel(category: MealCategory): string {
    return MEAL_CATEGORY_I18N_KEYS[category];
  }

  metaFor(category: MealCategory) {
    return CARD_META[category];
  }

  recipeCountLabel(count: number): string {
    return translatePlural(this.translate, 'common.recipeCount', count);
  }
}
