"use client";

import { toast } from "sonner";
import { withCacheBust } from "@/lib/helpers";
import { getApiErrorMessage } from "@/lib/api/errors";
import { useLanguageStore } from "@/store/languageStore";
import type { ApiResponse } from "@/lib/api/types";
import type { SaveMutation } from "@/features/shared/saveMutation";
import type { AccountRecord } from "./volunteerAccountRecords";

/**
 * Picking, cropping and saving the profile photo.
 *
 * Saved on its own, not with the rest of the form: the avatar is the one field
 * whose result the user expects to see immediately, and it is a multipart upload
 * that has nothing to do with the two record endpoints. `isOnlyProfilePicChanged`
 * is what stops the subsequent Save from reporting "nothing changed".
 *
 * `withCacheBust` on the returned URL is required — the path does not change when
 * the image does, so the browser would keep showing the previous photo.
 */
interface ProfilePictureUploadContext {
  t: (key: string, options?: Record<string, unknown>) => string;
  setUploadError: (message: string | null) => void;
  setSelectedImage: (dataUrl: string | null) => void;
  setShowCropModal: (open: boolean) => void;
  setProfilePic: (url: string | null) => void;
  setIsProfilePicUpdating: (updating: boolean) => void;
  setIsOnlyProfilePicChanged: (changed: boolean) => void;
  setComponentKey: (update: (key: number) => number) => void;
  updateAccountMutation: SaveMutation<
    FormData,
    ApiResponse<AccountRecord>
  >;
  /** Writes the new avatar into the auth store so the header updates at once. */
  updateProfilePic: (url: string) => void;
  router: { push: (path: string) => void };
}

export function useProfilePictureUpload(context: ProfilePictureUploadContext) {
  const {
    t,
    setUploadError,
    setSelectedImage,
    setShowCropModal,
    setProfilePic,
    setIsProfilePicUpdating,
    setIsOnlyProfilePicChanged,
    setComponentKey,
    updateAccountMutation,
    updateProfilePic,
    router,
  } = context;

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files.length > 0) {
      const file = event.target.files[0];
      // Create a URL for the image to be used in the cropper
      setSelectedImage(URL.createObjectURL(file));
      setShowCropModal(true);
    }
  };

  // Handle crop completion
  const handleCropComplete = async (croppedFile: File) => {
    try {
      setIsProfilePicUpdating(true);
      setIsOnlyProfilePicChanged(true);

      const formData = new FormData();
      formData.append("profile_pic", croppedFile);

      const response = await updateAccountMutation.mutateAsync(formData);
      setUploadError(null);
      setComponentKey((prev) => prev + 1);
      toast.success(t("COMMON.TOAST.PROFILE_PIC_UPDATE_SUCCESSFULLY"));

      // The API overwrites the picture at the same URL, so the saved one only
      // shows up after a refresh unless the URL is cache-busted.
      const imageUrl = URL.createObjectURL(croppedFile);
      setProfilePic(imageUrl);
      updateProfilePic(
        response?.data?.profile_pic
          ? withCacheBust(response.data.profile_pic)
          : imageUrl
      );

      // Close crop modal
      setShowCropModal(false);
      setSelectedImage(null);

      router.push("/volunteer-profile");
    } catch (error) {
      /* The server's reason (wrong type, over 10 MB, …) rather than a generic
         line, and as a toast too: the crop dialog stays open on failure and
         covers the inline error under the avatar. */
      const message = getApiErrorMessage(
        error,
        useLanguageStore.getState().language,
        t("COMMON.TOAST.PROFILE_PIC_UPDATE_FAILED")
      );
      setUploadError(message);
      toast.error(message);
    } finally {
      setIsProfilePicUpdating(false);
    }
  };

  // Debounced nickname availability check

  return { handleFileChange, handleCropComplete };
}
