import {
  type CreateRecipeInput,
  type DietView,
  ErrorCode,
  type IngredientView,
  type RecipeVisibility,
  createRecipeSchema,
} from "@batch-cooking/shared";
import { type FormEvent, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import { ApiError, apiClient } from "../api/client";
import { DietTagSelect } from "../features/recipes/DietTagSelect";
import { IngredientPicker } from "../features/recipes/IngredientPicker";
import { IngredientRow } from "../features/recipes/IngredientRow";
import { type StepDraft, StepListEditor } from "../features/recipes/StepListEditor";
import "../features/recipes/recipes.scss";
import { makeClientKey } from "../lib/client-key";
import { errorMessageService } from "../services/error-message.service";

/** In display order — mirrors `RecipeVisibility` (schema.prisma/shared types). */
const VISIBILITY_OPTIONS: RecipeVisibility[] = ["PERSONAL", "HOUSE", "PUBLIC"];

/** One selected ingredient line — `key` is a client-only stable identity, same reasoning as `StepDraft`. */
interface IngredientLine {
  key: string;
  ingredient: IngredientView;
  quantity: string;
  unit: string;
}

/** Load state for the reference ingredient list (+ the existing recipe, when editing) this form needs before it can render. */
type LoadState = "loading" | "loaded" | "error";

/**
 * Create/edit form for one recipe — routed at `/recettes/nouvelle` and
 * `/recettes/:id/modifier`. Same component for both: edit mode is just
 * "there's an `:id` param", which also drives preloading the existing
 * recipe's fields. Saving always sends the recipe's *whole* content (name,
 * ingredients, steps) — there's no partial-field save here, matching the
 * API's `PATCH /recipes/:id` contract (see `recipe.service.ts`).
 */
export function RecipeFormPage() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const recipeId = id !== undefined ? Number(id) : null;
  const isEditing = recipeId !== null;

  const [loadState, setLoadState] = useState<LoadState>("loading");
  const [ingredientsCatalog, setIngredientsCatalog] = useState<IngredientView[]>([]);
  const [dietsCatalog, setDietsCatalog] = useState<DietView[]>([]);

  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [picture, setPicture] = useState("");
  const [visibility, setVisibility] = useState<RecipeVisibility>("PERSONAL");
  const [dietIds, setDietIds] = useState<number[]>([]);
  const [ingredientLines, setIngredientLines] = useState<IngredientLine[]>([]);
  const [steps, setSteps] = useState<StepDraft[]>([]);

  const [formError, setFormError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    let cancelled = false;
    setLoadState("loading");

    Promise.all([
      apiClient.getIngredients(),
      apiClient.getDiets(),
      recipeId !== null ? apiClient.getRecipe(recipeId) : Promise.resolve(null),
    ])
      .then(([ingredients, diets, recipe]) => {
        if (cancelled) return;
        setIngredientsCatalog(ingredients);
        setDietsCatalog(diets);
        if (recipe) {
          setName(recipe.name);
          setDescription(recipe.description ?? "");
          setPicture(recipe.picture ?? "");
          setVisibility(recipe.visibility);
          setDietIds(recipe.diets.map((diet) => diet.id));
          setIngredientLines(
            recipe.ingredients.map((line) => ({
              key: makeClientKey(),
              ingredient: line.ingredient,
              quantity: String(line.quantity),
              unit: line.unit,
            })),
          );
          setSteps(
            recipe.steps.map((step) => ({
              key: makeClientKey(),
              description: step.description,
              picture: step.picture ?? "",
            })),
          );
        }
        setLoadState("loaded");
      })
      .catch(() => {
        if (!cancelled) setLoadState("error");
      });

    return () => {
      cancelled = true;
    };
  }, [recipeId]);

  function addIngredient(ingredient: IngredientView) {
    setIngredientLines((lines) => [
      ...lines,
      { key: makeClientKey(), ingredient, quantity: "", unit: "" },
    ]);
  }

  function updateIngredientLine(
    key: string,
    patch: Partial<Pick<IngredientLine, "quantity" | "unit">>,
  ) {
    setIngredientLines((lines) =>
      lines.map((line) => (line.key === key ? { ...line, ...patch } : line)),
    );
  }

  function removeIngredientLine(key: string) {
    setIngredientLines((lines) => lines.filter((line) => line.key !== key));
  }

  // Gates the submit button — the schema (checked again on submit, see
  // `handleSubmit`) is the source of truth, this is just instant feedback
  // that doesn't need a round trip through zod on every keystroke.
  const canSubmit =
    name.trim().length > 0 &&
    ingredientLines.length > 0 &&
    ingredientLines.every((line) => Number(line.quantity) > 0 && line.unit.trim().length > 0) &&
    steps.length > 0 &&
    steps.every((step) => step.description.trim().length > 0);

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setFormError(null);

    const payload: CreateRecipeInput = {
      name: name.trim(),
      description: description.trim() || null,
      picture: picture.trim() || null,
      visibility,
      dietIds,
      ingredients: ingredientLines.map((line) => ({
        ingredientId: line.ingredient.id,
        quantity: Number(line.quantity),
        unit: line.unit.trim(),
      })),
      steps: steps.map((step) => ({
        description: step.description.trim(),
        picture: step.picture.trim() || null,
      })),
    };

    const result = createRecipeSchema.safeParse(payload);
    if (!result.success) {
      setFormError(result.error.issues[0]?.message ?? t("recipes.form.genericError"));
      return;
    }

    setIsSubmitting(true);
    try {
      const saved =
        recipeId !== null
          ? await apiClient.updateRecipe(recipeId, result.data)
          : await apiClient.createRecipe(result.data);
      navigate(`/recettes/${saved.id}`);
    } catch (err) {
      const code = err instanceof ApiError ? err.code : ErrorCode.INTERNAL_ERROR;
      setFormError(errorMessageService.getLabel(code));
    } finally {
      setIsSubmitting(false);
    }
  }

  if (loadState === "loading") {
    return (
      <div className="recipe-form">
        <p className="recipes-page__status">{t("recipes.loading")}</p>
      </div>
    );
  }

  if (loadState === "error") {
    return (
      <div className="recipe-form">
        <p className="recipes-page__status recipes-page__status--error">{t("common.loadError")}</p>
      </div>
    );
  }

  const selectedIds = ingredientLines.map((line) => line.ingredient.id);

  return (
    <form className="recipe-form" onSubmit={handleSubmit} noValidate>
      <h1>{isEditing ? t("recipes.form.editTitle") : t("recipes.form.newTitle")}</h1>

      <label htmlFor="recipe-name">{t("recipes.form.nameLabel")}</label>
      <input id="recipe-name" value={name} onChange={(e) => setName(e.target.value)} />

      <label htmlFor="recipe-description">{t("recipes.form.descriptionLabel")}</label>
      <textarea
        id="recipe-description"
        value={description}
        onChange={(e) => setDescription(e.target.value)}
        rows={3}
      />

      <label htmlFor="recipe-picture">{t("recipes.form.pictureLabel")}</label>
      <input
        id="recipe-picture"
        type="url"
        value={picture}
        onChange={(e) => setPicture(e.target.value)}
        placeholder="https://…"
      />

      <label htmlFor="recipe-visibility">{t("recipes.form.visibilityLabel")}</label>
      <select
        id="recipe-visibility"
        value={visibility}
        onChange={(e) => setVisibility(e.target.value as RecipeVisibility)}
      >
        {VISIBILITY_OPTIONS.map((option) => (
          <option key={option} value={option}>
            {t(`recipes.form.visibility.${option}`)}
          </option>
        ))}
      </select>

      <DietTagSelect diets={dietsCatalog} value={dietIds} onChange={setDietIds} />

      <section className="recipe-form__section">
        <h2>{t("recipes.ingredientsTitle")}</h2>
        <ul className="recipe-form__ingredient-list">
          {ingredientLines.map((line) => (
            <IngredientRow
              key={line.key}
              ingredient={line.ingredient}
              quantity={line.quantity}
              unit={line.unit}
              onQuantityChange={(quantity) => updateIngredientLine(line.key, { quantity })}
              onUnitChange={(unit) => updateIngredientLine(line.key, { unit })}
              onRemove={() => removeIngredientLine(line.key)}
            />
          ))}
        </ul>
        <IngredientPicker
          ingredients={ingredientsCatalog}
          excludeIds={selectedIds}
          onSelect={addIngredient}
        />
      </section>

      <section className="recipe-form__section">
        <h2>{t("recipes.stepsTitle")}</h2>
        <StepListEditor steps={steps} onChange={setSteps} />
      </section>

      {formError && <p className="form-error">{formError}</p>}

      <div className="recipe-form__actions">
        <button type="submit" disabled={isSubmitting || !canSubmit}>
          {isSubmitting ? t("recipes.form.submitting") : t("recipes.form.submit")}
        </button>
      </div>
    </form>
  );
}
