import { useMemo, useState } from "react";
import { UtensilsCrossed } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useRecipes } from "@/hooks/useRecipes";
import { MealCategory } from "@/types/recipe.types";
import { useMealCategoryLabel } from "@/i18n/useMealCategoryLabel";
import { RecipeCard } from "@/components/recipes/RecipeCard";
import { GridSkeleton } from "@/components/ui/Skeleton";
import { EmptyState } from "@/components/ui/EmptyState";
import { ErrorState } from "@/components/ui/ErrorState";
import { extractApiError } from "@/api/axiosInstance";
import { nextSort, sortBy, sortIndicator, type SortDirection } from "@/utils/sort.util";

type RecipeSortColumn = "name" | "calories" | "prepTime";

const RECIPE_SORT_COLUMNS: { id: RecipeSortColumn; labelKey: string }[] = [
  { id: "name", labelKey: "manage.recipeName" },
  { id: "calories", labelKey: "recipes.calories" },
  { id: "prepTime", labelKey: "manage.prepTimeMin" },
];

interface CategoryPageProps {
  category: MealCategory;
}

export function CategoryPage({ category }: CategoryPageProps) {
  const { t } = useTranslation();
  const label = useMealCategoryLabel(category);
  const { data: recipes, isLoading, isError, error, refetch } = useRecipes(category);
  const [recipeSort, setRecipeSort] = useState<{ column: RecipeSortColumn; direction: SortDirection }>({
    column: "name",
    direction: "asc",
  });

  const sortedRecipes = useMemo(() => {
    if (!recipes) return [];
    const { column, direction } = recipeSort;
    return sortBy(recipes, direction, (recipe) => {
      switch (column) {
        case "name":
          return recipe.name;
        case "calories":
          return recipe.calories;
        case "prepTime":
          return recipe.prepTimeMinutes;
      }
    });
  }, [recipes, recipeSort]);

  const toggleRecipeSort = (column: RecipeSortColumn) => {
    setRecipeSort((current) => nextSort(current, column));
  };

  return (
    <div className="space-y-6">
      <header>
        <h1 className="text-2xl font-extrabold tracking-tight sm:text-3xl">{label}</h1>
        <p className="mt-1 text-slate-500 dark:text-slate-400">
          {recipes ? t("common.recipeCount", { count: recipes.length }) : t("common.loading")}
        </p>
      </header>

      {isLoading && <GridSkeleton />}

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

      {!isLoading && !isError && recipes && recipes.length === 0 && (
        <EmptyState
          icon={UtensilsCrossed}
          title={t("recipes.emptyCategoryTitle", { category: label })}
          description={t("recipes.emptyCategoryDescription")}
        />
      )}

      {!isLoading && !isError && recipes && recipes.length > 0 && (
        <>
          <div className="flex flex-wrap gap-2 text-sm">
            {RECIPE_SORT_COLUMNS.map(({ id, labelKey }) => (
              <button
                key={id}
                type="button"
                onClick={() => toggleRecipeSort(id)}
                className="rounded-lg border border-slate-200 px-3 py-1.5 font-medium hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
              >
                {t(labelKey)}
                {sortIndicator(recipeSort, id)}
              </button>
            ))}
          </div>
          <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
            {sortedRecipes.map((recipe) => (
              <RecipeCard key={recipe.id} recipe={recipe} />
            ))}
          </div>
        </>
      )}
    </div>
  );
}
