import { MEALS, type Meal, WEEK_DAYS, type WeekDay } from "@batch-cooking/shared";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import { RecipeImportForm } from "../../features/recipes/sources/RecipeImportForm";
import "../../features/recipes/recipes.scss";

/**
 * Reads and validates `?planningDate=&planningWeekDay=&planningMeal=` off
 * this page's own URL — `null` unless all three are present and well-formed
 * (a closed-set match against `WEEK_DAYS`/`MEALS`, same validation
 * `addPlanningItemSchema` enforces server-side), so a hand-typed or stale
 * URL just falls back to this page's normal "land on the recipe" behavior
 * rather than throwing. See this component's own doc comment.
 */
function parsePlanningSlot(
  searchParams: URLSearchParams,
): { date: string; weekDay: WeekDay; meal: Meal } | null {
  const date = searchParams.get("planningDate");
  const weekDay = searchParams.get("planningWeekDay");
  const meal = searchParams.get("planningMeal");
  if (
    date === null ||
    !/^\d{4}-\d{2}-\d{2}$/.test(date) ||
    weekDay === null ||
    !(WEEK_DAYS as readonly string[]).includes(weekDay) ||
    meal === null ||
    !(MEALS as readonly string[]).includes(meal)
  ) {
    return null;
  }
  return { date, weekDay: weekDay as WeekDay, meal: meal as Meal };
}

/**
 * Standalone route wrapper around `RecipeImportForm`, at
 * `/recettes/importer/:sourceKey/:externalId` — a directly-linkable
 * fallback (a stale bookmark, a reload mid-flow) rather than the normal way
 * this form is reached now: `RecipePickerDialog` embeds `RecipeImportForm`
 * directly as one of its own steps, without ever navigating here, when
 * picking a not-yet-imported source item turns out to need a person's
 * input (see that dialog's own doc comment). Landing on a real page instead
 * of a dialog step just changes where a successful import goes afterwards —
 * this page's own `handleImported` navigates, the dialog's own handler
 * closes itself instead.
 *
 * `?planningDate=&planningWeekDay=&planningMeal=` would only realistically
 * be set by a stale URL at this point (the dialog's own path never
 * navigates), still parsed the same defensive way as before.
 */
export function ImportRecipePage() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { sourceKey, externalId } = useParams<{ sourceKey: string; externalId: string }>();
  const [searchParams] = useSearchParams();
  const planningSlot = parsePlanningSlot(searchParams);

  if (sourceKey === undefined || externalId === undefined) {
    return (
      <div className="recipe-form">
        <p className="recipes-page__status recipes-page__status--error">
          {t("recipes.sources.import.loadError")}
        </p>
      </div>
    );
  }

  return (
    <div>
      <h1>{t("recipes.sources.import.title")}</h1>
      <RecipeImportForm
        sourceKey={sourceKey}
        externalId={externalId}
        planningSlot={planningSlot ?? undefined}
        onImported={({ recipe, planningItem }) => {
          void navigate(planningItem ? "/" : `/recettes/${recipe.id}`);
        }}
      />
    </div>
  );
}
