import { useEffect } from "react";
import { Loader2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { RecipeDetail } from "@/components/recipes/RecipeDetail";
import { useRecipe } from "@/hooks/useRecipes";

interface RecipePreviewModalProps {
  recipeId: number | null;
  portions?: number;
  onClose: () => void;
}

export function RecipePreviewModal({ recipeId, portions, onClose }: RecipePreviewModalProps) {
  const { t } = useTranslation();
  const { data: recipe, isLoading, isError } = useRecipe(recipeId ?? 0);

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

  if (!recipeId) 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 items-start justify-between gap-3">
          {portions != null && portions !== 1 ? (
            <p className="text-sm text-slate-500">
              {t("generators.diet.plannedPortions", { count: portions })}
            </p>
          ) : (
            <span />
          )}
          <button type="button" className="btn-secondary !px-2 !py-2" onClick={onClose}>
            <X className="h-4 w-4" />
          </button>
        </div>
        {isLoading ? (
          <div className="flex items-center gap-2 text-slate-400">
            <Loader2 className="h-4 w-4 animate-spin" /> {t("common.loading")}
          </div>
        ) : isError || !recipe ? (
          <p className="text-sm text-red-600">{t("errors.loadRecipeFailed")}</p>
        ) : (
          <RecipeDetail recipe={recipe} />
        )}
      </div>
    </div>
  );
}
