import { useNavigate } from "react-router-dom";
import { EngagementViewRecipe } from "../../services/EngagementService";
import { isApiError } from "../../types/api/error";
import type { Recipe, Tag } from "../../types/recipe"

interface RecipeListItemProps {
  recipe: Recipe;
};

function displayDifficulty(diff: number): string {
  switch (diff) {
    case 1:
      return "Beginner"
    case 2:
      return "Easy"
    case 3:
      return "Intermediate"
    case 4:
      return "Challenging"
    case 5:
      return "Extreme"
    default:
      return ""
  }
}

function displayTags(tags: Tag[]): string {
  return tags.map(tag => tag.Name).join(", ");
}

export default function RecipeListItem({ recipe }: RecipeListItemProps) {
  const navigate = useNavigate();

  // HANDLERS
  const clickHandler = async () => {
    if (!recipe) return;

    // Navigate first, so it feels faster
    await navigate(`/v2/web/recipe/${recipe.Id}`);

    const result = await EngagementViewRecipe(recipe.Id);
    if (isApiError(result)) {
      console.error(result.message);
    }
  }

  return (
    <li className="w-full border-b border-gray-300 px-2 py-4 even:bg-gray-50 hover:bg-gray-100 duration-150">
      <h2 onClick={() => void clickHandler()} className="text-base md:text-lg hover:text-blue-600 duration-100 cursor-pointer">
        {recipe.Title}
      </h2>
      <p className="hidden md:block text-sm text-gray-700 my-1.5">
        Difficulty: <span className="font-semibold">{displayDifficulty(recipe.Difficulty)}</span>
        {" "} | Duration: <span className="font-semibold">{recipe.Duration.Total} min</span>
        {" "} | Category: <span className="font-semibold">{recipe.Category}</span>
      </p>
      <p className="md:hidden text-xs md:text-sm text-gray-700 my-1">
        Difficulty: <span className="font-semibold">{displayDifficulty(recipe.Difficulty)}</span>
      </p>
      <p className="md:hidden text-xs md:text-sm text-gray-700 my-1">
        Duration: <span className="font-semibold">{recipe.Duration.Total} min</span>
      </p>
      <p className="md:hidden text-xs md:text-sm text-gray-700 my-1">
        Category: <span className="font-semibold">{recipe.Category}</span>
      </p>
      {recipe.Tags && (
        <p className="text-xs italic text-gray-500">
          Tags: {displayTags(recipe.Tags)}
        </p>
      )}
    </li>
  );
}
