import { useEffect } from "react";
import { X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { RecipeDetail } from "@/components/recipes/RecipeDetail";
import type { DietGeneratorDraftMeal } from "@/types/generator.types";
import type { RecipeDetail as RecipeDetailModel } from "@/types/recipe.types";

interface DietMealPreviewModalProps {
  meal: DietGeneratorDraftMeal | null;
  onClose: () => void;
}

function toRecipeDetail(meal: DietGeneratorDraftMeal): RecipeDetailModel {
  return {
    id: meal.recipeId,
    name: meal.recipeName,
    mealCategory: meal.mealCategory,
    calories: meal.calories ?? null,
    protein: meal.proteinG ?? null,
    fat: meal.fatG ?? null,
    carbs: meal.carbsG ?? null,
    prepTimeMinutes: meal.prepTimeMinutes ?? null,
    ingredients: (meal.ingredients ?? []).map((ingredient) => ({
      id: ingredient.id,
      name: ingredient.name,
      amountGrams: ingredient.amountGrams ?? null,
      unit: ingredient.unit ?? null,
      sortOrder: ingredient.sortOrder,
      catalogItemId: null,
    })),
    steps: (meal.steps ?? []).map((step) => ({
      id: step.id,
      stepNumber: step.stepNumber,
      description: step.description,
    })),
  };
}

export function DietMealPreviewModal({ meal, onClose }: DietMealPreviewModalProps) {
  const { t } = useTranslation();

  useEffect(() => {
    if (!meal) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [meal, onClose]);

  if (!meal) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-end justify-center bg-black/50 p-4 sm:items-center"
      onClick={onClose}
    >
      <div
        className="card max-h-[90vh] w-full max-w-3xl overflow-y-auto p-6"
        onClick={(event) => event.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-label={t("generators.diet.viewRecipe")}
      >
        <div className="mb-4 flex justify-end">
          <button type="button" className="btn-secondary !px-2 !py-2" onClick={onClose}>
            <X className="h-4 w-4" />
          </button>
        </div>
        <RecipeDetail recipe={toRecipeDetail(meal)} />
      </div>
    </div>
  );
}
