"use client";

import { toast } from "sonner";
import type { FormikHelpers } from "formik";
import {
  DO_NOT_DISTURB_FIELD_LIVE,
  findNationalityResidency,
  socialMediaOptions,
  speaksArabicToPayload,
} from "@/data/Constants";
import { TRAINER_REQUEST_LIVE } from "@/features/trainer/trainerRequest";
import {
  assertAccountUpdateSucceeded,
  reportAccountUpdateError,
} from "@/features/profile/accountFormErrors";
import { formatDateToYYYYMMDD } from "@/lib/helpers";
import { isUnderage } from "./volunteerAccountRules";
import { type CombinedFormValues } from "./volunteerAccountTypes";
import { type ChoiceSelectOption } from "./volunteerAccountDetailsProps";
import type { ApiResponse } from "@/lib/api/types";
import type { ChoiceItem } from "@/lib/choices";
import type { User } from "@/store/authStore";
import type {
  AccountRecord,
  VolunteerProfileRecord,
} from "./volunteerAccountRecords";
import { logRequestError } from "@/lib/api/logError";
import type { UpdateVolunteerProfileBody } from "@/features/profile/services/profileApi";

/** Save account identity, birth date, guardian and profile fields atomically
 * through the profile endpoint. Avatar uploads remain a separate action. */
/**
 * The part of a React Query mutation this hook uses.
 *
 * Structural rather than `UseMutationResult`, because the two mutations differ
 * in payload and in `TError`, and all that is needed here is `mutateAsync`.
 */
interface SaveMutation<TPayload, TResult> {
  mutateAsync: (payload: TPayload) => Promise<TResult>;
}

interface VolunteerAccountSubmitContext {
  t: (key: string, options?: Record<string, unknown>) => string;
  selectedLanguage: string;
  user: User | null;
  updateUser: (user: Partial<User>) => void;
  /** Writes the new avatar into the auth store so the header updates at once. */
  updateProfilePic: (url: string) => void;
  /** The saved volunteer profile record, read for the speaks-Arabic rule. */
  volunteerProfile: ApiResponse<VolunteerProfileRecord> | undefined;
  router: { push: (path: string) => void };
  /** The saved account record, to diff each field against. */
  accountData: ApiResponse<AccountRecord> | undefined;
  /** The gender master choices, to resolve the saved id back to a label. */
  genderData: ApiResponse<ChoiceItem[]> | undefined;
  genderOptions: ChoiceSelectOption[];
  setIsOnlyProfilePicChanged: (changed: boolean) => void;
  updateAccountMutation: SaveMutation<FormData, ApiResponse<AccountRecord>>;
  updateProfileMutation: SaveMutation<
    UpdateVolunteerProfileBody,
    ApiResponse<VolunteerProfileRecord>
  >;
  setComponentKey: (update: (key: number) => number) => void;
}

export function useVolunteerAccountSubmit(context: VolunteerAccountSubmitContext) {
  const {
    t,
    selectedLanguage,
    updateUser,
    volunteerProfile,
    router,
    accountData,
    genderData,
    genderOptions,
    setIsOnlyProfilePicChanged,
    updateProfileMutation,
    setComponentKey,
  } = context;

  return async (
    values: CombinedFormValues,
    helpers: FormikHelpers<CombinedFormValues>
  ) => {
    const { setFieldError, resetForm } = helpers;
    const errorReport = {
      language: selectedLanguage,
      setFieldError,
      fallback: t("COMMON.TOAST.PROFILE_UPDATE_FAILED"),
    };

    try {
      let hasAccountChanges = false;
      const accountFields: UpdateVolunteerProfileBody = {};

      if (values.phone_number !== accountData?.data?.phone_number) {
        accountFields.phone_number = values.phone_number;
        hasAccountChanges = true;
      }

      if (values.country_code !== accountData?.data?.country_code) {
        accountFields.country_code = values.country_code;
        hasAccountChanges = true;
      }

      if (values.first_name !== accountData?.data?.first_name) {
        accountFields.first_name = values.first_name.trim();
        hasAccountChanges = true;
      }

      if (values.last_name !== accountData?.data?.last_name) {
        accountFields.last_name = values.last_name.trim();
        hasAccountChanges = true;
      }

      const under18 = isUnderage(values.dob, volunteerProfile?.data?.birth_year ?? accountData?.data?.birth_year);

      const emergencyFields = [
        "emergency_contact_name",
        "emergency_contact_phone",
        "emergency_contact_country_code",
        "emergency_contact_civil_id",
        "emergency_contact_relationship",
      ] as const;

      emergencyFields.forEach((field) => {
        // No exact DOB: an unrelated edit must not erase legacy guardian data.
        if (!values.dob && !under18) return;
        const newValue = under18 ? (values[field] ?? "") : "";
        const currentValue =
          field === "emergency_contact_relationship"
            ? (accountData?.data?.emergency_contact_relationship_display?.id ??
              "")
            : (accountData?.data?.[field] ?? "");
        if (String(newValue) !== String(currentValue)) {
          accountFields[field] = String(newValue);
          hasAccountChanges = true;
        }
      });

      const socialMediaMap = new Map<string, string>();
      values.socialMedia?.forEach((sm) => {
        if (sm.platform && (sm.link || sm.link === "")) {
          socialMediaMap.set(sm.platform, sm.link);
        }
      });

      const socialMediaFields: Record<string, string> = {};
      socialMediaOptions.forEach((option) => {
        const link = socialMediaMap.get(option.value) ?? "";
        switch (option.value) {
          case "facebook":
            socialMediaFields.facebook_link = link;
            break;
          case "twitter":
            socialMediaFields.twitter_link = link;
            break;
          case "whatsapp":
            socialMediaFields.whatsapp_link = link;
            break;
          case "linkedin":
            socialMediaFields.linkedin_link = link;
            break;
          case "instagram":
            socialMediaFields.instagram_link = link;
            break;
          default:
            break;
        }
      });

      const residency = findNationalityResidency(values.nationality);
      const usesPassport = residency?.identifier === "passport_number";
      /* Typed against `VolunteerProfileUpdateRequest` rather than
         `Record<string, unknown>`, so a key the endpoint does not accept is a
         compile error instead of a field the backend drops in silence. The
         diff below still reads it through an index view — see the note there. */
      const profileData: UpdateVolunteerProfileBody = {
        ...accountFields,
        ...(under18 ? Object.fromEntries(emergencyFields.map(field => [field, values[field] ?? ""])) : {}),
        nickname: values.nickname,
        occupation: values.occupation,
        experience: values.experience_field,
        health_concerns: values.health_concerns || "no",
        interest_ids: values._interests,
        // Sent only once BE-95 accepts it — an unknown key 422s the save.
        ...(TRAINER_REQUEST_LIVE ? { show_real_name: values.show_real_name } : {}),
        ...(DO_NOT_DISTURB_FIELD_LIVE ? { do_not_disturb: values.do_not_disturb } : {}),
        gender: values.gender,
        nationality: residency?.nationality ?? "",
        residency_status: residency?.residency_status ?? "",
        civil_id: usesPassport ? "" : values.civil_id,
        passport_number: usesPassport ? values.passport_number : "",
        /*
         * BE-77. The key is added only when there is a real answer — an
         * absent key leaves the nullable column alone, and `hasProfileChanges`
         * below diffs every key it finds, so a permanently-`undefined` one
         * would report a change on every save. Clearing an answer back to
         * unanswered is therefore not offered, which is the safer default:
         * nothing silently erases a stated one. Sent for every nationality:
         * the question is mandatory for everyone (PDF p.8) and shown to a
         * Kuwaiti too, so gating it dropped a Kuwaiti's visible edit.
         */
        ...(speaksArabicToPayload(values.speaks_arabic) !== undefined
          ? { speaks_arabic: speaksArabicToPayload(values.speaks_arabic) }
          : {}),
        ...socialMediaFields,
        // Only send a real date when one is provided
        dob: values.dob ? formatDateToYYYYMMDD(values.dob) : null,
      };

      // API display objects and form IDs describe the same saved values.
      const savedProfile: Record<string, unknown> = {
        ...volunteerProfile?.data,
        gender: volunteerProfile?.data?.gender_display?.id ?? "",
        interest_ids: volunteerProfile?.data?.interest_display?.map(choice => choice.id).filter(id => id != null) ?? [],
      };
      const profileFields = profileData as Record<string, unknown>;
      const comparable = (key: string, value: unknown) => {
        if (key === "interest_ids" && Array.isArray(value)) return JSON.stringify(value.map(String).sort());
        if (key === "gender" || key === "emergency_contact_relationship") return String(value ?? "");
        return JSON.stringify(value ?? "");
      };
      const hasProfileChanges = Object.keys(profileFields).some(key =>
        comparable(key, profileFields[key]) !== comparable(key, savedProfile[key])
      );

      if (hasAccountChanges || hasProfileChanges) {
        let profileResponse;
        try {
          profileResponse =
            await updateProfileMutation.mutateAsync(profileData);
        } catch (profileErr) {
          reportAccountUpdateError({ ...errorReport, error: profileErr });
          return;
        }

        if (!assertAccountUpdateSucceeded(profileResponse, errorReport)) return;

        updateUser({ first_name: values.first_name.trim(), last_name: values.last_name.trim() });
        // Mirror a gender change into the cached user
        if (
          profileResponse?.data?.gender_display &&
          values.gender !== volunteerProfile?.data?.gender_display?.id
        ) {
          /* `Number`, not `parseInt`: `values.gender` already holds the
             numeric choice id, and `parseInt` only worked here because it
             coerces its argument to a string first. */
          const genderId = Number(values.gender);
          updateUser({
            gender_display: {
              /* `choice_type` is part of what the API sends for a
                 `*_display` object; kept so the cached copy matches. */
              choice_type: "gender",
              id: genderId,
              value_en:
                genderOptions.find((option) => option.value === genderId)
                  ?.label || "",
              value_ar:
                genderData?.data?.find((item) => item.id === genderId)
                  ?.value_ar || "",
            },
          });
        }
      }

      if (hasAccountChanges || hasProfileChanges) {
        toast.success(t("COMMON.TOAST.PROFILE_UPDATED_SUCCESSFULLY"));
        setComponentKey((prev) => prev + 1);
        resetForm();
        setIsOnlyProfilePicChanged(false);
        router.push("/volunteer-profile");
      } else {
        toast.info(t("COMMON.TOAST.NO_CHANGES"));
      }
    } catch (err) {
      logRequestError("Update failed:", err);
      reportAccountUpdateError({ ...errorReport, error: err });
    }
  };
}
