import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { CheckCircle2, PenLine, RefreshCw, Upload } from "lucide-react";
import { RecipeForm } from "@/components/recipes/RecipeForm";
import { ExcelImportPanel } from "@/components/recipes/ExcelImportPanel";
import { useRecipeManagement } from "@/hooks/useRecipeManagement";
import { fetchRecipeById, fetchRecipes } from "@/api/recipes.api";
import { Skeleton } from "@/components/ui/Skeleton";
import type { CreateRecipeInput } from "@/types/recipe-management.types";
import { MealCategory } from "@/types/recipe.types";

type Tab = "manual" | "import" | "edit";

export function ManageMealsPage() {
  const { t } = useTranslation();
  const [tab, setTab] = useState<Tab>("manual");
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [editingId, setEditingId] = useState<number | null>(null);
  const {
    createRecipe,
    createPending,
    createError,
    resetCreateError,
    updateRecipe,
    updatePending,
    updateError,
    resetUpdateError,
    recalculateMacros,
    recalculatePending,
    recalculateError,
    resetRecalculateError,
  } = useRecipeManagement();

  const recipesQuery = useQuery({
    queryKey: ["recipes", "manage-edit"],
    queryFn: () => fetchRecipes({}),
    enabled: tab === "edit",
  });

  const editRecipeQuery = useQuery({
    queryKey: ["recipes", "detail", editingId],
    queryFn: () => fetchRecipeById(editingId!),
    enabled: editingId != null,
  });

  const handleCreate = async (input: CreateRecipeInput) => {
    resetCreateError();
    setSuccessMessage(null);
    const recipe = await createRecipe(input);
    setSuccessMessage(t("manage.savedSuccess", { name: recipe.name }));
    setTab("manual");
  };

  const handleUpdate = async (input: CreateRecipeInput) => {
    if (!editingId) return;
    resetUpdateError();
    setSuccessMessage(null);
    const recipe = await updateRecipe({ id: editingId, input });
    setSuccessMessage(t("manage.updatedSuccess", { name: recipe.name }));
    setEditingId(null);
  };

  const handleRecalculate = async () => {
    resetRecalculateError();
    setSuccessMessage(null);
    const result = await recalculateMacros();
    setSuccessMessage(
      t("manage.recalculateSuccess", {
        updated: result.recipesUpdated,
        processed: result.recipesProcessed,
        unlinked: result.unlinkedIngredientRows,
      }),
    );
  };

  const editInitialValues: CreateRecipeInput | undefined = editRecipeQuery.data
    ? {
        name: editRecipeQuery.data.name,
        mealCategory: editRecipeQuery.data.mealCategory as MealCategory,
        calories: editRecipeQuery.data.calories,
        protein: editRecipeQuery.data.protein,
        fat: editRecipeQuery.data.fat,
        carbs: editRecipeQuery.data.carbs,
        prepTimeMinutes: editRecipeQuery.data.prepTimeMinutes,
        ingredients: editRecipeQuery.data.ingredients.map((i) => ({
          name: i.name,
          amountGrams: i.amountGrams,
          unit: i.unit ?? "",
          sortOrder: i.sortOrder,
          catalogItemId: i.catalogItemId ?? null,
        })),
        steps: editRecipeQuery.data.steps.map((s) => ({
          stepNumber: s.stepNumber,
          description: s.description,
        })),
      }
    : undefined;

  return (
    <div className="space-y-6">
      <header className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <h1 className="text-2xl font-extrabold tracking-tight sm:text-3xl">{t("manage.title")}</h1>
          <p className="mt-1 text-slate-500 dark:text-slate-400">{t("manage.subtitle")}</p>
        </div>
        <button
          type="button"
          className="btn-secondary shrink-0"
          disabled={recalculatePending}
          onClick={() => void handleRecalculate()}
        >
          <RefreshCw className={`h-4 w-4 ${recalculatePending ? "animate-spin" : ""}`} />
          {recalculatePending ? t("manage.recalculating") : t("manage.recalculateMacros")}
        </button>
      </header>

      {recalculateError ? (
        <div role="alert" className="rounded-xl bg-red-50 p-3 text-sm text-red-700 dark:bg-red-950/40 dark:text-red-300">
          {recalculateError}
        </div>
      ) : null}

      <div className="flex gap-2 border-b border-slate-200 dark:border-slate-800">
        {(
          [
            { id: "manual" as const, label: t("manage.tabManual"), icon: PenLine },
            { id: "edit" as const, label: t("manage.tabEdit"), icon: PenLine },
            { id: "import" as const, label: t("manage.tabImport"), icon: Upload },
          ] as const
        ).map(({ id, label, icon: Icon }) => (
          <button
            key={id}
            type="button"
            onClick={() => {
              setTab(id);
              if (id !== "edit") setEditingId(null);
            }}
            className={`flex items-center gap-2 border-b-2 px-4 py-2.5 text-sm font-semibold transition ${
              tab === id
                ? "border-brand-600 text-brand-600"
                : "border-transparent text-slate-500 hover:text-slate-700 dark:text-slate-400"
            }`}
          >
            <Icon className="h-4 w-4" />
            {label}
          </button>
        ))}
      </div>

      {successMessage && (tab === "manual" || tab === "edit") && (
        <div className="flex items-center gap-2 rounded-xl bg-brand-50 p-3 text-sm font-medium text-brand-800 dark:bg-brand-950/40 dark:text-brand-200">
          <CheckCircle2 className="h-4 w-4 shrink-0" />
          {successMessage}
        </div>
      )}

      {tab === "manual" ? (
        <RecipeForm onSubmit={handleCreate} pending={createPending} error={createError} />
      ) : tab === "import" ? (
        <ExcelImportPanel />
      ) : (
        <div className="grid gap-6 lg:grid-cols-2">
          <div className="card p-5">
            <h2 className="text-lg font-bold">{t("manage.tabEdit")}</h2>
            {recipesQuery.isLoading ? (
              <Skeleton className="mt-4 h-32" />
            ) : (
              <ul className="mt-4 max-h-96 space-y-1 overflow-y-auto">
                {(recipesQuery.data ?? []).map((r) => (
                  <li key={r.id}>
                    <button
                      type="button"
                      onClick={() => setEditingId(r.id)}
                      className={`w-full rounded-lg px-3 py-2 text-left text-sm ${
                        editingId === r.id
                          ? "bg-brand-600 text-white"
                          : "hover:bg-slate-100 dark:hover:bg-slate-800"
                      }`}
                    >
                      {r.name}
                    </button>
                  </li>
                ))}
              </ul>
            )}
          </div>
          <div>
            {editingId == null ? (
              <p className="text-sm text-slate-400">{t("manage.selectRecipeToEdit")}</p>
            ) : editRecipeQuery.isLoading || !editInitialValues ? (
              <Skeleton className="h-64" />
            ) : (
              <RecipeForm
                key={editingId}
                initialValues={editInitialValues}
                onSubmit={handleUpdate}
                pending={updatePending}
                error={updateError}
                submitLabel={t("manage.updateRecipe")}
                resetOnSubmit={false}
              />
            )}
          </div>
        </div>
      )}
    </div>
  );
}
