"use client";

import { toast } from "sonner";
import { getApiErrorMessages } from "@/lib/api/errors";
import type { FormikHelpers } from "formik";
import { formatDateToYYYYMMDD } from "@/lib/helpers";
import { type CreateTimeSlot } from "./createTimeSlotTypes";
import type { SaveMutation } from "@/features/shared/saveMutation";

interface TimeSlotFormValues {
  date: string;
  startTime: string;
  endTime: string;
  needed: string;
}

/**
 * Saving one time slot, new or edited.
 *
 * The date is reformatted to `YYYY-MM-DD` and **refused if that fails** rather
 * than sent as-is: the picker can hand back a value the API would reject with a
 * 422 the organiser could not act on. Times gain the seconds the API expects.
 */
/**
 * The slot body both calls send; the update nests it under `data`.
 *
 * The key is **`opportunity_id`**, not `opportunity`. Verified against
 * `LearnServeTimeSlotController::store()`, which validates
 * `'opportunity_id' => ['required', 'integer', 'exists:learn_serve_opportunities,id']`
 * — so the previous `opportunity` key meant every *create* was rejected with
 * 422 "The opportunity id field is required". There is no
 * `prepareForValidation` or middleware remapping it; the controller reads
 * `$data['opportunity_id']` directly on the next line.
 *
 * The edit path was unaffected: `update()` validates every field with
 * `sometimes` and takes the opportunity from the query string, so the stray
 * key was simply ignored there. That is why this only ever broke creating a
 * slot.
 *
 * Covered by `tests/timeSlotPayload.test.ts`.
 */
export interface TimeSlotPayload {
  /* `Number`, because the rule is `integer`. */
  opportunity_id: number;
  date: string;
  start_time: string;
  end_time: string;
  participants_needed: number;
}

export function useTimeSlotSubmit({
  opportunityId,
  isEditing,
  editTimeSlot,
  t,
  selectedLanguage,
  setOpenForm,
  refetch,
  createTimeSlotMutation,
  updateTimeSlotMutation,
}: {
  opportunityId: string | number;
  isEditing: boolean;
  editTimeSlot?: CreateTimeSlot | null;
  t: (key: string) => string;
  selectedLanguage: string;
  /** Closes the form panel. */
  setOpenForm: () => void;
  /** Reloads the slot list behind it. */
  refetch: () => void;
  createTimeSlotMutation: SaveMutation<TimeSlotPayload, unknown>;
  /** Update takes the slot id and the opportunity alongside the body. */
  updateTimeSlotMutation: SaveMutation<
    { id: string; opportunity_id: string; data: TimeSlotPayload },
    unknown
  >;
}) {
  return async (
    values: TimeSlotFormValues,
    { resetForm }: FormikHelpers<TimeSlotFormValues>
  ) => {
    try {
      const formattedDate = formatDateToYYYYMMDD(values.date);
      if (!formattedDate) {
        toast.error(t("COMMON.INVALID_DATE_FORMAT"));
        return;
      }

      const payload: TimeSlotPayload = {
        opportunity_id: Number(opportunityId),
        date: formattedDate,
        start_time: `${values.startTime}:00`,
        end_time: `${values.endTime}:00`,
        participants_needed: parseInt(values.needed, 10),
      };

      if (isEditing && editTimeSlot) {
        if (!editTimeSlot.id) {
          toast.error(t("COMMON.TOAST.MISSING_TIME_SLOT_ID"));
          return;
        }

        await updateTimeSlotMutation.mutateAsync({
          id: String(editTimeSlot.id),
          opportunity_id: String(opportunityId),
          data: payload,
        });
        toast.success(t("COMMON.TOAST.UPDATE_TIME_SLOT_SUCCESS"));
      } else {
        await createTimeSlotMutation.mutateAsync(payload);
        toast.success(t("COMMON.TOAST.CREATE_TIME_SLOT_SUCCESS"));
      }

      resetForm();
      setOpenForm();
      refetch();
    } catch (error) {
      /*
       * Through the shared helper, which reads both the current
       * `response_status.validation_errors` envelope and the older
       * `errors: { field: { en, ar } }` one. The hand-rolled version this
       * replaces covered only the older shape, so a migrated endpoint would have
       * collapsed every field-level reason into the generic fallback.
       */
      const messages = getApiErrorMessages(error, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
        return;
      }

      /*
       * One shape the shared helper does not cover, and this endpoint does use:
       * a bare top-level `{ date: ["..."] }`, DRF-style, with no `errors` or
       * `response_status` wrapper. Kept explicitly rather than dropped — it is
       * the message that explains a rejected slot date.
       */
      const bareDateError = (
        error as { response?: { data?: { date?: string[] } } }
      )?.response?.data?.date?.[0];

      toast.error(
        bareDateError ||
          (isEditing
            ? t("COMMON.TOAST.UPDATE_TIME_SLOT_FAILED")
            : t("COMMON.TOAST.CREATE_TIME_SLOT_FAILED"))
      );
    }
  };
}
