import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router, ActivatedRoute, RouterLink } from '@angular/router';
import { RecipeService, Recipe } from '../../services/recipe.service';

@Component({
  selector: 'app-recipe-form',
  imports: [CommonModule, FormsModule, RouterLink],
  templateUrl: './recipe-form.component.html',
  styleUrl: './recipe-form.component.css'
})
export class RecipeFormComponent implements OnInit {
  isEditMode: boolean = false;
  recipeId: string = '';
  ingredientInput: string = '';
  categories: string[] = ['Breakfast', 'Lunch', 'Dinner', 'Dessert', 'Snack', 'Other'];
  submitting: boolean = false;
  errorMessage: string = '';

  recipe: Recipe = {
    title: '',
    description: '',
    category: 'Dinner',
    ingredients: [],
    instructions: '',
    prepTime: 0,
    cookTime: 0,
    rating: 3
  };

  constructor(
    private recipeService: RecipeService,
    private router: Router,
    private route: ActivatedRoute
  ) {}

  ngOnInit(): void {
    this.recipeId = this.route.snapshot.paramMap.get('id') || '';
    this.isEditMode = !!this.recipeId && this.router.url.includes('/edit');

    if (this.isEditMode) {
      this.recipeService.getRecipe(this.recipeId).subscribe({
        next: (data) => { this.recipe = data; },
        error: () => { this.errorMessage = 'Could not load recipe.'; }
      });
    }
  }

  addIngredient(): void {
    const trimmed = this.ingredientInput.trim();
    if (trimmed) {
      this.recipe.ingredients = [...this.recipe.ingredients, trimmed];
      this.ingredientInput = '';
    }
  }

  removeIngredient(index: number): void {
    this.recipe.ingredients = this.recipe.ingredients.filter((_, i) => i !== index);
  }

  onIngredientKeydown(event: KeyboardEvent): void {
    if (event.key === 'Enter') {
      event.preventDefault();
      this.addIngredient();
    }
  }

  isFormValid(): boolean {
    return !!this.recipe.title.trim() &&
           !!this.recipe.category &&
           this.recipe.ingredients.length > 0 &&
           !!this.recipe.instructions.trim();
  }

  onSubmit(): void {
    if (!this.isFormValid()) return;
    this.submitting = true;

    const action = this.isEditMode
      ? this.recipeService.updateRecipe(this.recipeId, this.recipe)
      : this.recipeService.addRecipe(this.recipe);

    action.subscribe({
      next: () => this.router.navigate(['/recipes']),
      error: () => {
        this.errorMessage = 'Failed to save recipe. Make sure the backend is running.';
        this.submitting = false;
      }
    });
  }
}
