"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 organization's logo.
 *
 * Saved on its own, like the volunteer avatar, and for the same reason: it is the
 * one field whose result is expected immediately and it is a multipart upload
 * unrelated to the three record endpoints. `withCacheBust` is required — the URL
 * does not change when the image does.
 */
export function useOrganizerLogoUpload(context: {
  t: (key: string, options?: Record<string, unknown>) => string;
  setUploadError: (message: string | null) => void;
  setImageToCrop: (dataUrl: string) => void;
  setShowCropModal: (open: boolean) => void;
  setProfilePic: (url: string | null) => void;
  setIsProfilePicUpdating: (updating: boolean) => void;
  setIsOnlyProfilePicChanged: (changed: boolean) => void;
  updateAccountMutation: SaveMutation<
    FormData,
    ApiResponse<AccountRecord>
  >;
  setComponentKey: (update: (key: number) => number) => void;
  router: { push: (path: string) => void };
  updateProfilePic: (url: string) => void;
  fileInputRef: React.RefObject<HTMLInputElement | null>;
}) {
  const {
    t,
    setUploadError,
    setImageToCrop,
    setShowCropModal,
    setProfilePic,
    setIsProfilePicUpdating,
    setIsOnlyProfilePicChanged,
    updateAccountMutation,
    setComponentKey,
    router,
    updateProfilePic,
    fileInputRef,
  } = context;



  const handleFileSelection = (event: React.ChangeEvent<HTMLInputElement>) => {
    event.preventDefault();
    event.stopPropagation();

    if (
      fileInputRef.current &&
      event.target.files &&
      event.target.files.length > 0
    ) {
      const file = event.target.files[0];

      if (file.type.startsWith("image/")) {
        const reader = new FileReader();
        reader.onload = (e) => {
          if (e.target && typeof e.target.result === "string") {
            setImageToCrop(e.target.result);
            setShowCropModal(true);
          }
        };
        reader.readAsDataURL(file);
      }

      // Reset the file input
      fileInputRef.current.value = "";
    }
  };

  const handleCropComplete = async (croppedImage: File) => {
    try {
      setIsProfilePicUpdating(true);
      setIsOnlyProfilePicChanged(true);
      const formData = new FormData();
      formData.append("profile_pic", croppedImage);

      const response = await updateAccountMutation.mutateAsync(formData);
      setUploadError(null);
      setComponentKey((prev) => prev + 1);

      // 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(croppedImage);
      setProfilePic(imageUrl);
      updateProfilePic(
        response?.data?.profile_pic
          ? withCacheBust(response.data.profile_pic)
          : imageUrl
      );

      // Close the crop modal
      setShowCropModal(false);
      setImageToCrop("");

      toast.success(t("COMMON.TOAST.PROFILE_PIC_UPDATE_SUCCESSFULLY"));

      router.push("/entities-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);
    }
  };

  const handleCropCancel = () => {
    // Close the modal and reset image — nothing is saved on cancel
    setShowCropModal(false);
    setImageToCrop("");

    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  // Debounced nickname availability check

  return { handleFileSelection, handleCropComplete, handleCropCancel };
}
