"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { checkUserRequest, getDropdownChoicesRequest } from "@/features/auth/services/authApi";
import { getAccountInfo, getOrganizerProfile, updateAccountInfo, updateOrganizerDocuments, updateOrganizerProfile } from "@/features/profile/services/profileApi";
import { sortOrgTypeOptions, type OrgTypeOption } from "@/data/orgTypes";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import { useOrganizerLogoUpload } from "./useOrganizerLogoUpload";
import { useNicknameAvailability } from "./useNicknameAvailability";
import { type CombinedOrganizerFormValues } from "./organizerAccountTypes";
import { useOrganizerAccountSubmit } from "./useOrganizerAccountSubmit";
import { buildOrganizerAccountValidation } from "./organizerAccountValidation";
import { toChoiceOptions, toChoiceTagOptions } from "@/lib/choices";
import type { ChoiceDisplay } from "@/lib/choices";
import { DEFAULT_DIAL_CODE } from "@/data/defaultCountry";

/**
 * Everything the organization account screen needs, assembled.
 *
 * Three records through three endpoints — account, profile and documents — asked
 * for as one form. `keptDocIds` is the piece that makes the document endpoint
 * work: it carries the ids of already-stored files to keep, so an upload that
 * mentions none of them would delete the lot.
 */
export function useOrganizerAccountForm() {
  const { t } = useTranslation();
  const router = useRouter();
  const user = useAuthStore((s) => s.user);
  const updateProfilePic = useAuthStore((s) => s.updateProfilePic);
  const authToken = user?.auth_token;
  const selectedLanguage = useLanguageStore((s) => s.language);

  const [componentKey, setComponentKey] = useState(0);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const [profilePic, setProfilePic] = useState<string | null>(null);
  const [isProfilePicUpdating, setIsProfilePicUpdating] = useState(false);
  const [isOnlyProfilePicChanged, setIsOnlyProfilePicChanged] = useState(false);

  // Username availability check states

  // States for image cropping
  const [showCropModal, setShowCropModal] = useState(false);
  const [imageToCrop, setImageToCrop] = useState("");
  const fileInputRef = useRef<HTMLInputElement>(null);

  const updateAccountMutation = useMutation({ mutationFn: updateAccountInfo });
  const updateProfileMutation = useMutation({
    mutationFn: updateOrganizerProfile,
  });
  const updateDocumentsMutation = useMutation({
    mutationFn: updateOrganizerDocuments,
  });
  const checkUserMutation = useMutation({ mutationFn: checkUserRequest });

  const isUpdatingAccount = updateAccountMutation.isPending;
  const isUpdatingProfile = updateProfileMutation.isPending;
  const isUpdatingDocuments = updateDocumentsMutation.isPending;

  const {
    data: accountData,
    isLoading: isAccountLoading,
    error: accountError,
    refetch: refetchAccountData,
  } = useQuery({
    queryKey: ["account-info"],
    queryFn: getAccountInfo,
    enabled: Boolean(authToken),
  });

  const {
    data: organizerProfile,
    isLoading: isProfileLoading,
    error: profileError,
    refetch: refetchOrganizerProfile,
  } = useQuery({
    queryKey: ["organizer-profile"],
    queryFn: getOrganizerProfile,
    enabled: Boolean(authToken),
    refetchOnMount: "always",
  });

  // Fetch org type options
  const { data: orgTypeData, isLoading: orgTypeLoading } = useQuery({
    queryKey: ["org-type-choices", selectedLanguage],
    queryFn: () => getDropdownChoicesRequest("org_type"),
    enabled: !!selectedLanguage,
  });

  // The sector field is cancelled (PDF p.9) and the API has no rule for it,
  // so it is neither fetched, held in the form, nor sent on save.

  const { data: tagsData, isLoading: tagsLoading } = useQuery({
    queryKey: ["user-interest-choices", selectedLanguage],
    queryFn: () => getDropdownChoicesRequest("user_interest"),
    enabled: !!selectedLanguage,
  });

  // Sorted into the client's order, same as the entities registration form.
  const orgTypeOptions: OrgTypeOption[] = sortOrgTypeOptions(
    toChoiceOptions(orgTypeData?.data, selectedLanguage, (item) =>
      String(item.id)
    )
  );

  const tagOptions =
    toChoiceTagOptions(tagsData?.data, selectedLanguage, (item) => item.id);

  useEffect(() => {
    window.scrollTo(0, 0);
    refetchAccountData();
    refetchOrganizerProfile();
  }, [componentKey, refetchAccountData, refetchOrganizerProfile]);

  /*
   * Follow the fetched account during render, not from an effect.
   *
   * `profilePic` is also written by the upload flow (optimistically, before the
   * save returns), so it is not purely derived — but it must re-sync when the
   * account is refetched. The effect version showed the previous avatar for one
   * frame after every refetch.
   */
  // Starts empty, not at `accountData`: when the account is already cached
  // (opening this page from the profile) the first render must sync too, or
  // the avatar stays on the gender fallback until something refetches.
  const [prevAccountData, setPrevAccountData] = useState<typeof accountData>(undefined);
  if (accountData !== prevAccountData) {
    setPrevAccountData(accountData);
    if (accountData?.data?.profile_pic) {
      setProfilePic(accountData.data.profile_pic);
    }
  }

  /*
   * The same pattern for the documents the organizer is keeping: real state —
   * the remove buttons write it — re-seeded whenever the profile is refetched.
   * Written the same way as `profilePic` above rather than from an effect, so
   * a refetch cannot paint one frame in which a document the server still has
   * is missing from the keep list.
   */
  const [prevOrganizerProfile, setPrevOrganizerProfile] =
    useState(organizerProfile);
  // A cached profile is already available on mount; seed its documents too.
  const [keptDocIds, setKeptDocIds] = useState<number[]>(() =>
    organizerProfile?.data?.documents?.map((document) => document.id) ?? []
  );
  if (organizerProfile !== prevOrganizerProfile) {
    setPrevOrganizerProfile(organizerProfile);
    if (organizerProfile?.data?.documents) {
      setKeptDocIds(
        organizerProfile.data.documents.map((d: { id: number }) => d.id)
      );
    }
  }

  const initialValues: CombinedOrganizerFormValues = {
    email: accountData?.data?.email || "",
    phone_number: accountData?.data?.phone_number || "",
    /* Kuwait by default when the account has no saved code, declared here
       rather than seeded by `CountryCodeSelect` from a mount effect. See
       `DEFAULT_DIAL_CODE`. */
    country_code: accountData?.data?.country_code || DEFAULT_DIAL_CODE,
    password: accountData?.data?.password || " ",
    documents: [],
    internal_license_files: [],
    internal_license_document_removed: false,
    company_name: organizerProfile?.data?.company_name || "",
    nickname: organizerProfile?.data?.nickname || "",
    license_number: organizerProfile?.data?.license_number || "",
    organizer_type:
      organizerProfile?.data?.organizer_type_display?.id?.toString() || "",
    _interests:
      organizerProfile?.data?.interest_display?.map(
        (interest: ChoiceDisplay) => Number(interest.id)
      ) || [],
    /* The resource always sends an array (`socialMediaList()` returns `[]`,
       never null), but `organizerProfile` itself is undefined until the fetch
       resolves — so the length is read through `??` rather than compared
       directly. One blank row is substituted so the form has something to
       render against. */
    socialMedia: organizerProfile?.data?.socialMedia?.length
      ? organizerProfile.data.socialMedia
      : [{ platform: "", link: "" }],
  };

  const { nicknameAvailability, checkNicknameAvailability } =
    useNicknameAvailability({ checkUserMutation, t });

  const validationSchema = buildOrganizerAccountValidation({
    t,
    initialNickname: initialValues.nickname,
    nicknameAvailable: nicknameAvailability.available,
    orgTypeOptions,
    keptDocIds,
  });

  const { handleFileSelection, handleCropComplete, handleCropCancel } =
    useOrganizerLogoUpload({
      t,
      setUploadError,
      setImageToCrop,
      setShowCropModal,
      setProfilePic,
      setIsProfilePicUpdating,
      setIsOnlyProfilePicChanged,
      updateAccountMutation,
      setComponentKey,
      router,
      updateProfilePic,
      fileInputRef,
    });

  const handleSubmit = useOrganizerAccountSubmit({
    t,
    selectedLanguage,
    router,
    accountData,
    organizerProfile,
    keptDocIds,
    setIsOnlyProfilePicChanged,
    updateAccountMutation,
    updateProfileMutation,
    updateDocumentsMutation,
    // Refetching happens through the `componentKey` effect above, which this
    // save bumps — so the two refetchers are not passed in here.
    setComponentKey,
  });

  return {
    t,
    user,
    authToken,
    router,
    selectedLanguage,
    componentKey,
    uploadError,
    profilePic,
    isProfilePicUpdating,
    isOnlyProfilePicChanged,
    showCropModal,
    setShowCropModal,
    imageToCrop,
    setImageToCrop,
    fileInputRef,
    keptDocIds,
    setKeptDocIds,
    isUpdatingAccount,
    isUpdatingProfile,
    isUpdatingDocuments,
    accountData,
    isAccountLoading,
    accountError,
    organizerProfile,
    isProfileLoading,
    profileError,
    orgTypeOptions,
    orgTypeLoading,
    tagOptions,
    tagsLoading,
    initialValues,
    validationSchema,
    nicknameAvailability,
    checkNicknameAvailability,
    handleFileSelection,
    handleCropComplete,
    handleCropCancel,
    handleSubmit,
    updateProfilePic,
  };
}
