import { useCallback, useEffect, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { Droplets, Plus, Trash2 } from "lucide-react";
import {
  copyYesterdayMeals,
  createReminder,
  deleteDrink,
  deleteMeal,
  deleteReminder,
  fetchDailySummary,
  fetchDrinkCatalog,
  fetchFavoriteCatalogItems,
  fetchFavoriteRecipes,
  fetchGoals,
  fetchHistory,
  fetchMealSuggestions,
  fetchRecentMeals,
  fetchReminders,
  logDrink,
  logMeal,
  previewMeal,
  saveGoals,
  updateReminder,
} from "@/api/diet.api";
import { fetchIngredientCatalogItems } from "@/api/ingredient-catalog.api";
import { fetchRecipes } from "@/api/recipes.api";
import { extractApiError } from "@/api/axiosInstance";
import { DateNavigator } from "@/components/diet/DateNavigator";
import { HistoryChart } from "@/components/diet/HistoryChart";
import { ErrorState } from "@/components/ui/ErrorState";
import { Skeleton } from "@/components/ui/Skeleton";
import {
  CONSUMPTION_CATEGORIES,
  DietReminderType,
  REMINDER_DAYS_MASK_ALL,
  type DietSuggestion,
  type LogMealInput,
  type MealPreview,
  type UserDailyGoals,
} from "@/types/diet.types";
import { ingredientDisplayName } from "@/utils/ingredient-catalog.util";
import { addDaysIso, todayIso } from "@/utils/date.util";
import { nextSort, sortBy, sortIndicator, type SortDirection } from "@/utils/sort.util";

type MealLogSortColumn = "name" | "calories";
type DrinkLogSortColumn = "name" | "volume";
type ReminderSortColumn = "title" | "time";

type Tab = "today" | "history" | "goals" | "reminders";

function ProgressRing({
  label,
  consumed,
  goal,
  remaining,
  unit,
  remainingLabel,
}: {
  label: string;
  consumed: number;
  goal?: number | null;
  remaining?: number | null;
  unit: string;
  remainingLabel: string;
}) {
  const pct = goal && goal > 0 ? Math.min((consumed / goal) * 100, 100) : 0;

  return (
    <div className="card p-4">
      <p className="text-sm font-medium text-slate-500 dark:text-slate-400">{label}</p>
      <p className="mt-1 text-2xl font-bold">
        {consumed}
        {goal != null ? (
          <span className="text-base font-normal text-slate-400">
            {" "}
            / {goal}
            {unit}
          </span>
        ) : null}
      </p>
      {remaining != null ? (
        <p className="mt-1 text-xs text-slate-500">
          {remainingLabel}: {remaining}
          {unit}
        </p>
      ) : null}
      {goal != null ? (
        <div className="mt-3 h-2 overflow-hidden rounded-full bg-slate-100 dark:bg-slate-800">
          <div
            className="h-full rounded-full bg-brand-600 transition-all"
            style={{ width: `${pct}%` }}
          />
        </div>
      ) : (
        <p className="mt-2 text-xs text-slate-400">{unit}</p>
      )}
    </div>
  );
}

function mealMacroLine(m: {
  calories?: number | null;
  proteinG?: number | null;
  fatG?: number | null;
  carbsG?: number | null;
}): string {
  if (m.calories == null) return "";
  return `${m.calories} kcal · P ${Number(m.proteinG ?? 0).toFixed(1)}g · F ${Number(m.fatG ?? 0).toFixed(1)}g · C ${Number(m.carbsG ?? 0).toFixed(1)}g`;
}

export function DietTrackerPage() {
  const { t, i18n } = useTranslation();
  const queryClient = useQueryClient();
  const [tab, setTab] = useState<Tab>("today");
  const [date, setDate] = useState(todayIso);
  const [historyDays, setHistoryDays] = useState(7);
  const [editingReminderId, setEditingReminderId] = useState<number | null>(null);
  const [editReminderTitle, setEditReminderTitle] = useState("");
  const [editReminderTime, setEditReminderTime] = useState("09:00");
  const [editReminderType, setEditReminderType] = useState(DietReminderType.Water);
  const [recipeSearch, setRecipeSearch] = useState("");
  const [selectedRecipeId, setSelectedRecipeId] = useState<number | null>(null);
  const [mealCategory, setMealCategory] = useState(2);
  const [customMealName, setCustomMealName] = useState("");
  const [portions, setPortions] = useState(1);
  const [catalogItemId, setCatalogItemId] = useState<number | null>(null);
  const [grams, setGrams] = useState(150);
  const [mealPreview, setMealPreview] = useState<MealPreview | null>(null);
  const [goalsForm, setGoalsForm] = useState<UserDailyGoals>({});
  const [reminderTitle, setReminderTitle] = useState("");
  const [reminderTime, setReminderTime] = useState("09:00");
  const [reminderType, setReminderType] = useState(DietReminderType.Water);
  const [mealSort, setMealSort] = useState<{ column: MealLogSortColumn; direction: SortDirection }>({
    column: "name",
    direction: "asc",
  });
  const [drinkSort, setDrinkSort] = useState<{ column: DrinkLogSortColumn; direction: SortDirection }>({
    column: "name",
    direction: "asc",
  });
  const [reminderSort, setReminderSort] = useState<{ column: ReminderSortColumn; direction: SortDirection }>({
    column: "time",
    direction: "asc",
  });

  const summaryQuery = useQuery({
    queryKey: ["diet", "summary", date],
    queryFn: () => fetchDailySummary(date),
  });

  const suggestionsQuery = useQuery({
    queryKey: ["diet", "suggestions", date],
    queryFn: () => fetchMealSuggestions(date),
    enabled: tab === "today" && !!summaryQuery.data,
  });

  const catalogQuery = useQuery({
    queryKey: ["diet", "catalog"],
    queryFn: fetchDrinkCatalog,
  });

  const ingredientItemsQuery = useQuery({
    queryKey: ["ingredient-catalog", "all"],
    queryFn: () => fetchIngredientCatalogItems(),
  });

  const recipesQuery = useQuery({
    queryKey: ["recipes", "diet-search", recipeSearch],
    queryFn: () => fetchRecipes({ search: recipeSearch }),
    enabled: recipeSearch.trim().length >= 2,
  });

  const goalsQuery = useQuery({
    queryKey: ["diet", "goals"],
    queryFn: fetchGoals,
    enabled: tab === "goals",
  });

  const remindersQuery = useQuery({
    queryKey: ["diet", "reminders"],
    queryFn: fetchReminders,
    enabled: tab === "reminders",
  });

  const historyFrom = addDaysIso(date, -(historyDays - 1));
  const historyQuery = useQuery({
    queryKey: ["diet", "history", historyFrom, date],
    queryFn: () => fetchHistory(historyFrom, date),
    enabled: tab === "history",
  });

  const recentsQuery = useQuery({
    queryKey: ["diet", "recent"],
    queryFn: () => fetchRecentMeals(8),
    enabled: tab === "today",
  });

  const favoriteRecipesQuery = useQuery({
    queryKey: ["diet", "favorites", "recipes"],
    queryFn: fetchFavoriteRecipes,
    enabled: tab === "today",
  });

  const favoriteCatalogQuery = useQuery({
    queryKey: ["diet", "favorites", "catalog"],
    queryFn: fetchFavoriteCatalogItems,
    enabled: tab === "today",
  });

  const invalidateDiet = () => {
    void queryClient.invalidateQueries({ queryKey: ["diet"] });
  };

  const resetMealForm = () => {
    setRecipeSearch("");
    setSelectedRecipeId(null);
    setCustomMealName("");
    setCatalogItemId(null);
    setPortions(1);
    setGrams(150);
    setMealPreview(null);
  };

  const logMealMutation = useMutation({
    mutationFn: (input: LogMealInput) => logMeal(input),
    onSuccess: () => {
      resetMealForm();
      invalidateDiet();
    },
  });

  const logDrinkMutation = useMutation({
    mutationFn: logDrink,
    onSuccess: invalidateDiet,
  });

  const saveGoalsMutation = useMutation({
    mutationFn: saveGoals,
    onSuccess: invalidateDiet,
  });

  const createReminderMutation = useMutation({
    mutationFn: createReminder,
    onSuccess: () => {
      setReminderTitle("");
      void queryClient.invalidateQueries({ queryKey: ["diet", "reminders"] });
    },
  });

  const deleteMealMutation = useMutation({
    mutationFn: deleteMeal,
    onSuccess: invalidateDiet,
  });

  const deleteDrinkMutation = useMutation({
    mutationFn: deleteDrink,
    onSuccess: invalidateDiet,
  });

  const deleteReminderMutation = useMutation({
    mutationFn: deleteReminder,
    onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["diet", "reminders"] }),
  });

  const updateReminderMutation = useMutation({
    mutationFn: ({ id, input }: { id: number; input: Parameters<typeof updateReminder>[1] }) =>
      updateReminder(id, input),
    onSuccess: () => {
      setEditingReminderId(null);
      void queryClient.invalidateQueries({ queryKey: ["diet", "reminders"] });
    },
  });

  const copyYesterdayMutation = useMutation({
    mutationFn: () => copyYesterdayMeals(date),
    onSuccess: invalidateDiet,
  });

  const summary = summaryQuery.data;

  const buildMealPayload = useCallback((): LogMealInput | null => {
    if (selectedRecipeId) {
      return {
        recipeId: selectedRecipeId,
        mealCategory,
        logDate: date,
        portions,
      };
    }
    if (catalogItemId && grams > 0) {
      return { catalogItemId, grams, mealCategory, logDate: date };
    }
    if (customMealName.trim()) {
      return { name: customMealName.trim(), mealCategory, logDate: date };
    }
    return null;
  }, [catalogItemId, customMealName, date, grams, mealCategory, portions, selectedRecipeId]);

  useEffect(() => {
    if (goalsQuery.data) {
      setGoalsForm(goalsQuery.data);
    }
  }, [goalsQuery.data]);

  useEffect(() => {
    const payload = buildMealPayload();
    if (!payload) {
      setMealPreview(null);
      return;
    }
    const timer = window.setTimeout(() => {
      void previewMeal(payload, date)
        .then(setMealPreview)
        .catch(() => setMealPreview(null));
    }, 250);
    return () => window.clearTimeout(timer);
  }, [buildMealPayload, date]);

  const suggestionName = (s: DietSuggestion) =>
    i18n.language.startsWith("pl") && s.namePl ? s.namePl : s.name;

  const canLogMeal = buildMealPayload() != null;

  async function handleLogMeal() {
    const payload = buildMealPayload();
    if (!payload) return;
    await logMealMutation.mutateAsync(payload);
  }

  async function handleLogSuggestion(s: DietSuggestion) {
    await logMealMutation.mutateAsync({
      catalogItemId: s.catalogItemId,
      grams: s.suggestedGrams,
      mealCategory,
      logDate: date,
    });
  }

  const tabs: { id: Tab; label: string }[] = [
    { id: "today", label: t("diet.tabToday") },
    { id: "history", label: t("diet.tabHistory") },
    { id: "goals", label: t("diet.tabGoals") },
    { id: "reminders", label: t("diet.tabReminders") },
  ];

  const ingredientItems = ingredientItemsQuery.data ?? [];
  const suggestions = suggestionsQuery.data ?? [];

  const sortedMeals = useMemo(() => {
    if (!summary) return [];
    const { column, direction } = mealSort;
    return sortBy(summary.meals, direction, (meal) => (column === "name" ? meal.name : meal.calories));
  }, [summary, mealSort]);

  const sortedDrinks = useMemo(() => {
    if (!summary) return [];
    const { column, direction } = drinkSort;
    return sortBy(summary.drinks, direction, (drink) =>
      column === "name" ? drink.name : drink.volumeMl,
    );
  }, [summary, drinkSort]);

  const sortedReminders = useMemo(() => {
    const { column, direction } = reminderSort;
    return sortBy(remindersQuery.data ?? [], direction, (reminder) =>
      column === "title" ? reminder.title : reminder.timeOfDay,
    );
  }, [remindersQuery.data, reminderSort]);

  return (
    <div className="space-y-6">
      <header>
        <h1 className="text-2xl font-extrabold tracking-tight sm:text-3xl">{t("diet.title")}</h1>
        <p className="mt-1 text-slate-500 dark:text-slate-400">{t("diet.subtitle")}</p>
      </header>

      <div className="flex flex-wrap gap-2">
        {tabs.map(({ id, label }) => (
          <button
            key={id}
            type="button"
            onClick={() => setTab(id)}
            className={`rounded-xl px-4 py-2 text-sm font-semibold transition ${
              tab === id
                ? "bg-brand-600 text-white"
                : "bg-slate-100 text-slate-600 hover:bg-slate-200 dark:bg-slate-800 dark:text-slate-300"
            }`}
          >
            {label}
          </button>
        ))}
      </div>

      {(tab === "today" || tab === "history") && (
        <DateNavigator date={date} onChange={setDate} />
      )}

      {tab === "today" && (
        <>
          {summaryQuery.isLoading ? (
            <Skeleton className="h-48" />
          ) : summaryQuery.isError ? (
            <ErrorState
              message={extractApiError(summaryQuery.error, t("errors.loadDietFailed"))}
              onRetry={() => void summaryQuery.refetch()}
            />
          ) : summary ? (
            <>
              <section className="card space-y-3 p-5">
                <h2 className="text-lg font-bold">{t("diet.quickLog")}</h2>
                <div className="flex flex-wrap gap-2">
                  <button
                    type="button"
                    className="btn-secondary !py-1.5 !text-sm"
                    disabled={copyYesterdayMutation.isPending}
                    onClick={() => void copyYesterdayMutation.mutateAsync()}
                  >
                    {t("diet.copyYesterday")}
                  </button>
                </div>
                {(recentsQuery.data?.length ?? 0) > 0 ? (
                  <div>
                    <p className="text-sm font-medium text-slate-500">{t("diet.recentMeals")}</p>
                    <div className="mt-2 flex flex-wrap gap-2">
                      {recentsQuery.data!.map((m) => (
                        <button
                          key={`${m.name}-${m.lastLoggedAt}`}
                          type="button"
                          className="rounded-lg border border-slate-200 px-3 py-1.5 text-sm hover:border-brand-400 dark:border-slate-700"
                          disabled={logMealMutation.isPending}
                          onClick={() =>
                            void logMealMutation.mutateAsync(
                              m.recipeId
                                ? { recipeId: m.recipeId, mealCategory: m.mealCategory, logDate: date, portions: m.portions }
                                : { name: m.name, mealCategory: m.mealCategory, logDate: date },
                            )
                          }
                        >
                          {m.name}
                        </button>
                      ))}
                    </div>
                  </div>
                ) : null}
                {(favoriteRecipesQuery.data?.length ?? 0) > 0 ? (
                  <div>
                    <p className="text-sm font-medium text-slate-500">{t("diet.favorites")}</p>
                    <div className="mt-2 flex flex-wrap gap-2">
                      {favoriteRecipesQuery.data!.map((f) => (
                        <button
                          key={f.recipeId}
                          type="button"
                          className="rounded-lg border border-brand-200 bg-brand-50 px-3 py-1.5 text-sm dark:border-brand-900 dark:bg-brand-950/30"
                          disabled={logMealMutation.isPending}
                          onClick={() =>
                            void logMealMutation.mutateAsync({
                              recipeId: f.recipeId,
                              mealCategory: f.mealCategory,
                              logDate: date,
                            })
                          }
                        >
                          {f.name}
                        </button>
                      ))}
                    </div>
                  </div>
                ) : null}
                {(favoriteCatalogQuery.data?.length ?? 0) > 0 ? (
                  <div>
                    <p className="text-sm font-medium text-slate-500">
                      {t("diet.favorites")} · {t("diet.fromCatalog")}
                    </p>
                    <div className="mt-2 flex flex-wrap gap-2">
                      {favoriteCatalogQuery.data!.map((f) => (
                        <button
                          key={f.catalogItemId}
                          type="button"
                          className="rounded-lg border border-slate-200 px-3 py-1.5 text-sm dark:border-slate-700"
                          disabled={logMealMutation.isPending}
                          onClick={() =>
                            void logMealMutation.mutateAsync({
                              catalogItemId: f.catalogItemId,
                              grams: 150,
                              mealCategory,
                              logDate: date,
                            })
                          }
                        >
                          {i18n.language.startsWith("pl") && f.namePl ? f.namePl : f.name}
                        </button>
                      ))}
                    </div>
                  </div>
                ) : null}
              </section>

              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
                <ProgressRing
                  label={t("diet.calories")}
                  consumed={summary.calories.consumed}
                  goal={summary.calories.goal}
                  remaining={summary.calories.remaining}
                  unit=" kcal"
                  remainingLabel={t("diet.remaining")}
                />
                <ProgressRing
                  label={t("diet.water")}
                  consumed={summary.waterMl.consumed}
                  goal={summary.waterMl.goal}
                  remaining={summary.waterMl.remaining}
                  unit="ml"
                  remainingLabel={t("diet.remaining")}
                />
                <ProgressRing
                  label={t("recipes.protein")}
                  consumed={Number(summary.proteinG.consumed)}
                  goal={summary.proteinG.goal != null ? Number(summary.proteinG.goal) : null}
                  remaining={
                    summary.proteinG.remaining != null ? Number(summary.proteinG.remaining) : null
                  }
                  unit="g"
                  remainingLabel={t("diet.remaining")}
                />
                <ProgressRing
                  label={t("recipes.fat")}
                  consumed={Number(summary.fatG.consumed)}
                  goal={summary.fatG.goal != null ? Number(summary.fatG.goal) : null}
                  remaining={summary.fatG.remaining != null ? Number(summary.fatG.remaining) : null}
                  unit="g"
                  remainingLabel={t("diet.remaining")}
                />
                <ProgressRing
                  label={t("recipes.carbs")}
                  consumed={Number(summary.carbsG.consumed)}
                  goal={summary.carbsG.goal != null ? Number(summary.carbsG.goal) : null}
                  remaining={
                    summary.carbsG.remaining != null ? Number(summary.carbsG.remaining) : null
                  }
                  unit="g"
                  remainingLabel={t("diet.remaining")}
                />
              </div>

              {suggestions.length > 0 ? (
                <section className="card p-5">
                  <h2 className="text-lg font-bold">{t("diet.suggestionsTitle")}</h2>
                  <p className="mt-1 text-sm text-slate-500">{t("diet.suggestionsHint")}</p>
                  <ul className="mt-4 space-y-2">
                    {suggestions.map((s) => (
                      <li
                        key={s.catalogItemId}
                        className="flex flex-wrap items-center justify-between gap-2 rounded-xl bg-slate-50 px-3 py-2 dark:bg-slate-800/50"
                      >
                        <div>
                          <p className="font-medium">{suggestionName(s)}</p>
                          <p className="text-xs text-slate-400">
                            {s.suggestedGrams}g · {s.calories ?? "?"} kcal · P{" "}
                            {Number(s.proteinG ?? 0).toFixed(1)}g ·{" "}
                            {t(`diet.suggestionReasons.${s.reasonKey}`)}
                          </p>
                        </div>
                        <button
                          type="button"
                          className="btn-secondary !py-1.5 !text-xs"
                          disabled={logMealMutation.isPending}
                          onClick={() => void handleLogSuggestion(s)}
                        >
                          + {t("diet.logSuggestion")}
                        </button>
                      </li>
                    ))}
                  </ul>
                </section>
              ) : null}

              <section className="card space-y-4 p-5">
                <h2 className="flex items-center gap-2 text-lg font-bold">
                  <Droplets className="h-5 w-5 text-sky-500" />
                  {t("diet.logDrink")}
                </h2>
                <div className="flex flex-wrap gap-2">
                  {catalogQuery.data?.map((item) => (
                    <button
                      key={item.id}
                      type="button"
                      disabled={logDrinkMutation.isPending}
                      onClick={() =>
                        void logDrinkMutation.mutateAsync({
                          drinkCatalogId: item.id,
                          volumeMl: item.defaultVolumeMl,
                          logDate: date,
                        })
                      }
                      className="inline-flex items-center gap-2 rounded-xl border border-slate-200 px-3 py-2 text-sm font-medium hover:border-brand-400 hover:bg-brand-50 dark:border-slate-700 dark:hover:bg-brand-950/30"
                    >
                      <span>{item.iconEmoji ?? "🥤"}</span>
                      {item.name}
                      <span className="text-slate-400">+{item.defaultVolumeMl}ml</span>
                    </button>
                  ))}
                </div>
              </section>

              <section className="card space-y-4 p-5">
                <h2 className="text-lg font-bold">{t("diet.logMeal")}</h2>
                <label className="block text-sm">
                  <span className="font-medium">{t("common.category")}</span>
                  <select
                    className="select mt-1 w-full"
                    value={mealCategory}
                    onChange={(e) => setMealCategory(Number(e.target.value))}
                  >
                    {CONSUMPTION_CATEGORIES.map((c) => (
                      <option key={c.value} value={c.value}>
                        {t(c.labelKey)}
                      </option>
                    ))}
                  </select>
                </label>
                <label className="block text-sm">
                  <span className="font-medium">{t("diet.searchRecipe")}</span>
                  <input
                    className="input mt-1 w-full"
                    value={recipeSearch}
                    onChange={(e) => {
                      setRecipeSearch(e.target.value);
                      setSelectedRecipeId(null);
                      setCatalogItemId(null);
                      setMealPreview(null);
                    }}
                    placeholder={t("recipes.searchRecipes")}
                  />
                </label>
                {recipesQuery.data && recipesQuery.data.length > 0 ? (
                  <ul className="max-h-40 space-y-1 overflow-y-auto rounded-xl border border-slate-200 p-2 dark:border-slate-700">
                    {recipesQuery.data.map((r) => (
                      <li key={r.id}>
                        <button
                          type="button"
                          onClick={() => {
                            setSelectedRecipeId(r.id);
                            setCustomMealName("");
                            setCatalogItemId(null);
                          }}
                          className={`w-full rounded-lg px-3 py-2 text-left text-sm ${
                            selectedRecipeId === r.id
                              ? "bg-brand-600 text-white"
                              : "hover:bg-slate-100 dark:hover:bg-slate-800"
                          }`}
                        >
                          {r.name}
                        </button>
                      </li>
                    ))}
                  </ul>
                ) : null}
                <div className="grid gap-3 sm:grid-cols-2">
                  <label className="block text-sm">
                    <span className="font-medium">{t("diet.portions")}</span>
                    <input
                      type="number"
                      min={0.25}
                      step={0.25}
                      className="input mt-1 w-full"
                      value={portions}
                      onChange={(e) => setPortions(Number(e.target.value))}
                    />
                  </label>
                  <label className="block text-sm">
                    <span className="font-medium">{t("diet.fromCatalog")}</span>
                    <select
                      className="select mt-1 w-full"
                      value={catalogItemId ?? ""}
                      onChange={(e) => {
                        const id = e.target.value ? Number(e.target.value) : null;
                        setCatalogItemId(id);
                        if (id) {
                          setSelectedRecipeId(null);
                          setCustomMealName("");
                        }
                      }}
                    >
                      <option value="">{t("diet.noCatalogItem")}</option>
                      {ingredientItems.map((item) => (
                        <option key={item.id} value={item.id}>
                          {ingredientDisplayName(item, i18n.language)}
                        </option>
                      ))}
                    </select>
                  </label>
                </div>
                {catalogItemId ? (
                  <label className="block text-sm">
                    <span className="font-medium">{t("diet.grams")}</span>
                    <input
                      type="number"
                      min={1}
                      className="input mt-1 w-full"
                      value={grams}
                      onChange={(e) => setGrams(Number(e.target.value))}
                    />
                  </label>
                ) : null}
                <label className="block text-sm">
                  <span className="font-medium">{t("diet.orCustomMeal")}</span>
                  <input
                    className="input mt-1 w-full"
                    value={customMealName}
                    onChange={(e) => {
                      setCustomMealName(e.target.value);
                      setSelectedRecipeId(null);
                      setCatalogItemId(null);
                    }}
                    placeholder={t("manage.recipeNamePlaceholder")}
                  />
                </label>

                {mealPreview ? (
                  <div className="rounded-xl border border-brand-200 bg-brand-50/60 p-4 dark:border-brand-900 dark:bg-brand-950/20">
                    <p className="font-semibold">
                      {t("diet.mealPreview")}: {mealPreview.meal.name}
                    </p>
                    <p className="mt-2 text-sm">
                      {mealPreview.meal.calories ?? "?"} kcal · P{" "}
                      {Number(mealPreview.meal.proteinG ?? 0).toFixed(1)}g · F{" "}
                      {Number(mealPreview.meal.fatG ?? 0).toFixed(1)}g · C{" "}
                      {Number(mealPreview.meal.carbsG ?? 0).toFixed(1)}g
                    </p>
                    <p className="mt-2 text-sm text-slate-600 dark:text-slate-300">
                      {t("diet.remainingAfter")}: {mealPreview.remainingAfter.calories ?? "?"} kcal,
                      P {mealPreview.remainingAfter.proteinG ?? "?"}g, F{" "}
                      {mealPreview.remainingAfter.fatG ?? "?"}g, C{" "}
                      {mealPreview.remainingAfter.carbsG ?? "?"}g
                    </p>
                  </div>
                ) : null}

                <button
                  type="button"
                  className="btn-primary inline-flex items-center gap-2"
                  disabled={logMealMutation.isPending || !canLogMeal}
                  onClick={() => void handleLogMeal()}
                >
                  <Plus className="h-4 w-4" />
                  {t("diet.markEaten")}
                </button>
              </section>

              <section className="grid gap-4 lg:grid-cols-2">
                <div className="card p-5">
                  <h3 className="font-bold">{t("diet.mealsOnDate", { date })}</h3>
                  {summary.meals.length > 0 ? (
                    <div className="mt-3 grid grid-cols-[1fr_auto_auto] gap-2 border-b border-slate-200 px-3 pb-2 text-xs font-semibold uppercase tracking-wide text-slate-500 dark:border-slate-700">
                      <button
                        type="button"
                        className="text-left hover:text-slate-700"
                        onClick={() => setMealSort((current) => nextSort(current, "name"))}
                      >
                        {t("ingredientCatalog.columns.name")}
                        {sortIndicator(mealSort, "name")}
                      </button>
                      <button
                        type="button"
                        className="text-right hover:text-slate-700"
                        onClick={() => setMealSort((current) => nextSort(current, "calories"))}
                      >
                        {t("recipes.calories")}
                        {sortIndicator(mealSort, "calories")}
                      </button>
                      <span />
                    </div>
                  ) : null}
                  <ul className="mt-3 space-y-2">
                    {summary.meals.length === 0 ? (
                      <li className="text-sm text-slate-400">{t("diet.nothingLogged")}</li>
                    ) : (
                      sortedMeals.map((m) => (
                        <li
                          key={m.id}
                          className="flex items-center justify-between gap-2 rounded-lg bg-slate-50 px-3 py-2 dark:bg-slate-800/50"
                        >
                          <div>
                            <p className="font-medium">{m.name}</p>
                            <p className="text-xs text-slate-400">
                              {mealMacroLine(m) || t("diet.noMacros")}
                            </p>
                          </div>
                          <button
                            type="button"
                            aria-label={t("diet.removeEntry")}
                            onClick={() => void deleteMealMutation.mutateAsync(m.id)}
                            className="text-slate-400 hover:text-red-500"
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                        </li>
                      ))
                    )}
                  </ul>
                </div>
                <div className="card p-5">
                  <h3 className="font-bold">{t("diet.drinksOnDate", { date })}</h3>
                  {summary.drinks.length > 0 ? (
                    <div className="mt-3 grid grid-cols-[1fr_auto_auto] gap-2 border-b border-slate-200 px-3 pb-2 text-xs font-semibold uppercase tracking-wide text-slate-500 dark:border-slate-700">
                      <button
                        type="button"
                        className="text-left hover:text-slate-700"
                        onClick={() => setDrinkSort((current) => nextSort(current, "name"))}
                      >
                        {t("ingredientCatalog.columns.name")}
                        {sortIndicator(drinkSort, "name")}
                      </button>
                      <button
                        type="button"
                        className="text-right hover:text-slate-700"
                        onClick={() => setDrinkSort((current) => nextSort(current, "volume"))}
                      >
                        {t("diet.water")}
                        {sortIndicator(drinkSort, "volume")}
                      </button>
                      <span />
                    </div>
                  ) : null}
                  <ul className="mt-3 space-y-2">
                    {summary.drinks.length === 0 ? (
                      <li className="text-sm text-slate-400">{t("diet.nothingLogged")}</li>
                    ) : (
                      sortedDrinks.map((d) => (
                        <li
                          key={d.id}
                          className="flex items-center justify-between gap-2 rounded-lg bg-slate-50 px-3 py-2 dark:bg-slate-800/50"
                        >
                          <div>
                            <p className="font-medium">{d.name}</p>
                            <p className="text-xs text-slate-400">{d.volumeMl} ml</p>
                          </div>
                          <button
                            type="button"
                            aria-label={t("diet.removeEntry")}
                            onClick={() => void deleteDrinkMutation.mutateAsync(d.id)}
                            className="text-slate-400 hover:text-red-500"
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                        </li>
                      ))
                    )}
                  </ul>
                </div>
              </section>
            </>
          ) : null}
        </>
      )}

      {tab === "history" && (
        <div className="card space-y-4 p-5">
          <div className="flex flex-wrap items-center gap-2">
            <h2 className="text-lg font-bold">{t("diet.historyCalories")}</h2>
            <select
              className="select !w-auto"
              value={historyDays}
              onChange={(e) => setHistoryDays(Number(e.target.value))}
            >
              <option value={7}>7 {t("diet.days")}</option>
              <option value={30}>30 {t("diet.days")}</option>
            </select>
          </div>
          {historyQuery.isLoading ? (
            <Skeleton className="h-48" />
          ) : historyQuery.data ? (
            <HistoryChart days={historyQuery.data} />
          ) : null}
        </div>
      )}

      {tab === "goals" && (
        <div className="card max-w-lg space-y-4 p-5">
          <h2 className="text-lg font-bold">{t("diet.dailyGoals")}</h2>
          <p className="text-sm text-slate-500">{t("diet.goalsHint")}</p>
          {[
            { key: "calorieGoal" as const, label: t("diet.calorieGoal") },
            { key: "proteinGoalG" as const, label: t("manage.proteinG") },
            { key: "fatGoalG" as const, label: t("manage.fatG") },
            { key: "carbsGoalG" as const, label: t("manage.carbsG") },
            { key: "waterGoalMl" as const, label: t("diet.waterGoal") },
          ].map(({ key, label }) => (
            <label key={key} className="block text-sm">
              <span className="font-medium">{label}</span>
              <input
                type="number"
                min={0}
                className="input mt-1 w-full"
                value={goalsForm[key] ?? ""}
                onChange={(e) =>
                  setGoalsForm((prev) => ({
                    ...prev,
                    [key]: e.target.value === "" ? null : Number(e.target.value),
                  }))
                }
              />
            </label>
          ))}
          <button
            type="button"
            className="btn-primary"
            disabled={saveGoalsMutation.isPending}
            onClick={() => void saveGoalsMutation.mutateAsync(goalsForm)}
          >
            {t("diet.saveGoals")}
          </button>
        </div>
      )}

      {tab === "reminders" && (
        <div className="grid gap-6 lg:grid-cols-2">
          <div className="card space-y-4 p-5">
            <h2 className="text-lg font-bold">{t("diet.addReminder")}</h2>
            <label className="block text-sm">
              <span className="font-medium">{t("diet.reminderType")}</span>
              <select
                className="select mt-1 w-full"
                value={reminderType}
                onChange={(e) => setReminderType(Number(e.target.value))}
              >
                <option value={DietReminderType.Water}>{t("diet.reminderWater")}</option>
                <option value={DietReminderType.Meal}>{t("diet.reminderMeal")}</option>
                <option value={DietReminderType.Custom}>{t("diet.reminderCustom")}</option>
              </select>
            </label>
            <label className="block text-sm">
              <span className="font-medium">{t("diet.reminderTitle")}</span>
              <input
                className="input mt-1 w-full"
                value={reminderTitle}
                onChange={(e) => setReminderTitle(e.target.value)}
                placeholder={t("diet.reminderTitlePlaceholder")}
              />
            </label>
            <label className="block text-sm">
              <span className="font-medium">{t("diet.reminderTime")}</span>
              <input
                type="time"
                className="input mt-1 w-full"
                value={reminderTime}
                onChange={(e) => setReminderTime(e.target.value)}
              />
            </label>
            <button
              type="button"
              className="btn-primary"
              disabled={!reminderTitle.trim() || createReminderMutation.isPending}
              onClick={() =>
                void createReminderMutation.mutateAsync({
                  reminderType,
                  title: reminderTitle.trim(),
                  timeOfDay: reminderTime,
                  daysOfWeekMask: REMINDER_DAYS_MASK_ALL,
                })
              }
            >
              {t("diet.saveReminder")}
            </button>
          </div>
          <div className="card p-5">
            <h2 className="text-lg font-bold">{t("diet.yourReminders")}</h2>
            {(remindersQuery.data?.length ?? 0) > 0 ? (
              <div className="mt-3 grid grid-cols-[1fr_auto_auto] gap-2 border-b border-slate-200 px-3 pb-2 text-xs font-semibold uppercase tracking-wide text-slate-500 dark:border-slate-700">
                <button
                  type="button"
                  className="text-left hover:text-slate-700"
                  onClick={() => setReminderSort((current) => nextSort(current, "title"))}
                >
                  {t("diet.reminderTitle")}
                  {sortIndicator(reminderSort, "title")}
                </button>
                <button
                  type="button"
                  className="text-right hover:text-slate-700"
                  onClick={() => setReminderSort((current) => nextSort(current, "time"))}
                >
                  {t("diet.reminderTime")}
                  {sortIndicator(reminderSort, "time")}
                </button>
                <span />
              </div>
            ) : null}
            <ul className="mt-3 space-y-2">
              {remindersQuery.data?.length === 0 ? (
                <li className="text-sm text-slate-400">{t("diet.noReminders")}</li>
              ) : (
                sortedReminders.map((r) => (
                  <li
                    key={r.id}
                    className="rounded-lg bg-slate-50 px-3 py-2 dark:bg-slate-800/50"
                  >
                    {editingReminderId === r.id ? (
                      <div className="space-y-2">
                        <input
                          className="input w-full"
                          value={editReminderTitle}
                          onChange={(e) => setEditReminderTitle(e.target.value)}
                        />
                        <input
                          type="time"
                          className="input w-full"
                          value={editReminderTime}
                          onChange={(e) => setEditReminderTime(e.target.value)}
                        />
                        <div className="flex gap-2">
                          <button
                            type="button"
                            className="btn-primary !py-1.5 !text-xs"
                            disabled={updateReminderMutation.isPending}
                            onClick={() =>
                              void updateReminderMutation.mutateAsync({
                                id: r.id,
                                input: {
                                  reminderType: editReminderType,
                                  title: editReminderTitle.trim(),
                                  timeOfDay: editReminderTime,
                                  daysOfWeekMask: r.daysOfWeekMask,
                                  isEnabled: r.isEnabled,
                                },
                              })
                            }
                          >
                            {t("common.save")}
                          </button>
                          <button
                            type="button"
                            className="btn-secondary !py-1.5 !text-xs"
                            onClick={() => setEditingReminderId(null)}
                          >
                            {t("common.cancel")}
                          </button>
                        </div>
                      </div>
                    ) : (
                      <div className="flex items-center justify-between gap-2">
                        <div>
                          <p className="font-medium">{r.title}</p>
                          <p className="text-xs text-slate-400">{r.timeOfDay.slice(0, 5)}</p>
                        </div>
                        <div className="flex gap-2">
                          <button
                            type="button"
                            className="text-xs font-semibold text-brand-600"
                            onClick={() => {
                              setEditingReminderId(r.id);
                              setEditReminderTitle(r.title);
                              setEditReminderTime(r.timeOfDay.slice(0, 5));
                              setEditReminderType(r.reminderType);
                            }}
                          >
                            {t("diet.editReminder")}
                          </button>
                          <button
                            type="button"
                            onClick={() => void deleteReminderMutation.mutateAsync(r.id)}
                            className="text-slate-400 hover:text-red-500"
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                        </div>
                      </div>
                    )}
                  </li>
                ))
              )}
            </ul>
          </div>
        </div>
      )}
    </div>
  );
}
