"use client";

import { toast } from "sonner";
import { socialMediaOptions } from "@/data/Constants";
import type { FormikHelpers } from "formik";
import {
  assertAccountUpdateSucceeded,
  reportAccountUpdateError,
} from "@/features/profile/accountFormErrors";
import { type CombinedOrganizerFormValues } from "./organizerAccountTypes";
import type { ApiResponse } from "@/lib/api/types";
import type { SaveMutation } from "@/features/shared/saveMutation";
import type { AccountRecord } from "./volunteerAccountRecords";
import type { OrganizerProfileRecord } from "./organizerAccountRecords";
import { logRequestError } from "@/lib/api/logError";
import type {
  OrganizationDocumentRecord,
  UpdateOrganizerProfileBody,
} from "@/features/profile/services/profileApi";

/**
 * Saving an organization's account.
 *
 * **Three** endpoints, not one: the account, the organizer profile, and the
 * supporting documents — which are a separate multipart call carrying the ids of
 * the documents to keep alongside any new files. A single "Save" fans out to all
 * three and has to cope with any of them failing alone.
 */
export function useOrganizerAccountSubmit(context: {
  t: (key: string, options?: Record<string, unknown>) => string;
  selectedLanguage: string;
  router: { push: (path: string) => void };
  accountData: ApiResponse<AccountRecord> | undefined;
  organizerProfile: ApiResponse<OrganizerProfileRecord> | undefined;
  keptDocIds: number[];
  setIsOnlyProfilePicChanged: (changed: boolean) => void;
  updateAccountMutation: SaveMutation<FormData, ApiResponse<AccountRecord>>;
  updateProfileMutation: SaveMutation<
    UpdateOrganizerProfileBody,
    ApiResponse<OrganizerProfileRecord>
  >;
  /**
   * Multipart: new files plus the ids of the documents to keep.
   *
   * Answers with the **document collection**, not the profile — the mismatch
   * was invisible while the wrapper's response was untyped.
   */
  updateDocumentsMutation: SaveMutation<
    FormData,
    ApiResponse<OrganizationDocumentRecord[]>
  >;
  setComponentKey: (update: (key: number) => number) => void;
}) {
  const {
    t,
    selectedLanguage,
    router,
    accountData,
    organizerProfile,
    keptDocIds,
    setIsOnlyProfilePicChanged,
    updateAccountMutation,
    updateProfileMutation,
    updateDocumentsMutation,
    setComponentKey,
  } = context;

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

    try {
      let hasAccountChanges = false;
      const accountFormData = new FormData();

      // Account info changes
      if (values.phone_number !== accountData?.data?.phone_number) {
        accountFormData.append("phone_number", values.phone_number);
        hasAccountChanges = true;
      }

      if (values.country_code !== accountData?.data?.country_code) {
        accountFormData.append("country_code", values.country_code);
        hasAccountChanges = true;
      }

      // Organizer profile changes
      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;
        }
      });

      /* Typed against `OrganizationProfileController::update()`'s validator;
         see `UpdateOrganizerProfileBody`, including the note that a changed
         `organizer_type` sends the account back for admin review. */
      const profileData: UpdateOrganizerProfileBody = {
        company_name: values.company_name,
        nickname: values.nickname,
        organizer_type: values.organizer_type,
        interest_ids: values._interests,
        license_number: values.license_number,
        ...(values.internal_license_files?.[0] ? { internal_license_document: values.internal_license_files[0] } : {}),
        ...(values.internal_license_document_removed ? { internal_license_document_removed: true } : {}),
        ...socialMediaFields,
      };

      /* The diff walks `profileData`'s keys, which are payload names rather
         than a fixed set, so the saved record is read through an index view of
         itself — the same pattern as the volunteer submit. */
      const savedProfile = organizerProfile?.data as
        | Record<string, unknown>
        | undefined;
      const profileFields = profileData as Record<string, unknown>;
      const hasProfileChanges = Object.keys(profileFields).some((key) => {
        if (key === "internal_license_document" || key === "internal_license_document_removed") return true;
        if (key === "organizer_type") {
          return (
            String(profileData.organizer_type ?? "") !==
            String(organizerProfile?.data?.organizer_type_display?.id ?? "")
          );
        }
        return (
          JSON.stringify(profileFields[key]) !==
          JSON.stringify(savedProfile?.[key] ?? "")
        );
      });

      const hasNewDocuments = values.documents && values.documents.length > 0;

      const originalDocIds: number[] =
        organizerProfile?.data?.documents?.map((d: { id: number }) => d.id) ??
        [];
      const hasExistingDocRemoved = keptDocIds.length < originalDocIds.length;

      // Submit changes
      if (hasAccountChanges) {
        const accountResponse =
          await updateAccountMutation.mutateAsync(accountFormData);
        if (!assertAccountUpdateSucceeded(accountResponse, errorReport)) return;
      }

      if (hasProfileChanges) {
        const profileResponse =
          await updateProfileMutation.mutateAsync(profileData);
        if (!assertAccountUpdateSucceeded(profileResponse, errorReport)) return;
      }

      if (hasNewDocuments || hasExistingDocRemoved) {
        const docsFormData = new FormData();
        keptDocIds.forEach((id) =>
          docsFormData.append("existing_ids[]", String(id))
        );
        for (const doc of values.documents) {
          docsFormData.append("new_documents[]", doc);
        }
        const documentsResponse =
          await updateDocumentsMutation.mutateAsync(docsFormData);
        if (!assertAccountUpdateSucceeded(documentsResponse, errorReport))
          return;
      }

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