import { useState } from "react";
import { ArrowLeft } from "lucide-react";
import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useRecipe } from "@/hooks/useRecipes";
import { RecipeDetail } from "@/components/recipes/RecipeDetail";
import { Skeleton } from "@/components/ui/Skeleton";
import { ErrorState } from "@/components/ui/ErrorState";
import { extractApiError } from "@/api/axiosInstance";
import type { RecipeDetail as RecipeDetailModel } from "@/types/recipe.types";

export function RecipeDetailPage() {
  const { t } = useTranslation();
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const recipeId = Number(id);
  const { data: fetchedRecipe, isLoading, isError, error, refetch } = useRecipe(recipeId);
  const [recipe, setRecipe] = useState<RecipeDetailModel | null>(null);
  const displayRecipe = recipe ?? fetchedRecipe ?? null;

  return (
    <div className="space-y-6">
      <button type="button" onClick={() => navigate(-1)} className="btn-secondary">
        <ArrowLeft className="h-4 w-4" />
        {t("common.back")}
      </button>

      {isLoading && (
        <div className="space-y-6">
          <Skeleton className="h-6 w-24" />
          <Skeleton className="h-9 w-2/3" />
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
            {Array.from({ length: 4 }).map((_, i) => (
              <Skeleton key={i} className="h-20" />
            ))}
          </div>
          <Skeleton className="h-64" />
        </div>
      )}

      {isError && (
        <ErrorState
          message={extractApiError(error, t("errors.loadRecipeFailed"))}
          onRetry={() => void refetch()}
        />
      )}

      {!isLoading && !isError && displayRecipe && (
        <RecipeDetail
          recipe={displayRecipe}
          onRecipeUpdated={(updated) => {
            setRecipe(updated);
            void refetch();
          }}
        />
      )}
    </div>
  );
}
