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";

export function RecipeDetailPage() {
  const { t } = useTranslation();
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const recipeId = Number(id);
  const { data: recipe, isLoading, isError, error, refetch } = useRecipe(recipeId);

  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 && recipe && <RecipeDetail recipe={recipe} />}
    </div>
  );
}
