"use client";

import { useTranslation } from "react-i18next";
import { useField, type FormikErrors } from "formik";
import { useRef, useState } from "react";
import { loadImageWithCORS } from "./cropImage";

/**
 * A picked file, tagged with the key of its *uncropped* bytes.
 *
 * `originalImagesMap` keeps the bytes as they were picked so a second crop
 * starts from the original rather than compounding on the first crop's output.
 * `File` has nowhere to hang that key, so it is set as an own property — which
 * is a real pattern, not a cast to silence the checker, and is written down
 * here so both the writer and the two readers agree on the name.
 */
export interface KeyedFile extends File {
  __originalKey?: string;
}

/**
 * Formik's `setFieldValue`, for a component that is reused across forms with
 * unrelated value shapes.
 *
 * `unknown` for the value: this component writes a `File`, a `File[]` or
 * `null` depending on its props, and the field it writes to is named by a
 * string the caller supplies — there is no form type here to check it against.
 * Callers pass `FormikProps<TheirValues>["setFieldValue"]` straight in.
 */
export type SetFieldValueFn = (
  field: string,
  value: unknown,
  shouldValidate?: boolean
) => Promise<void | FormikErrors<unknown>>;

export interface UploadInputProps {
  className?: string;
  name: string;
  label: string;
  instructions?: string[];
  onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
  setFieldValue?: SetFieldValueFn;
  multiple?: boolean;
  singleFileArray?: boolean;
  accept?: string;
  existingFiles?: Array<{ id: number; image: string }>;
  onRemove?: (index: number, isExistingFile: boolean) => void;
  enableCropping?: boolean;
  cropAspectRatio?: number;
  cropShape?: "rect" | "round";
  cropWidth?: number;
  cropHeight?: number;
  cropDisplayMode?: "opportunity" | "license" | "profile";
}

/**
 * The uploader's behaviour: picking files, the crop queue, and removal.
 *
 * `pendingCropFilesRef` and `croppedBatchFilesRef` are refs rather than state
 * on purpose — a multi-file selection crops one image at a time, and the queue
 * has to survive each crop's re-render without driving one.
 */
export function useUploadDocument({
  name,
  onChange,
  setFieldValue,
  multiple = true,
  singleFileArray = false,
  existingFiles = [],
  onRemove,
  enableCropping = false,
}: UploadInputProps) {
  const { t } = useTranslation();
  const [field] = useField(name);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [showCropModal, setShowCropModal] = useState(false);
  const [imageToCrop, setImageToCrop] = useState<string>("");
  const [editingIndex, setEditingIndex] = useState<number | null>(null);
  const [editingIsExisting, setEditingIsExisting] = useState<boolean>(false);
  const [originalImagesMap, setOriginalImagesMap] = useState<Map<string, string>>(new Map());
  const [currentEditKey, setCurrentEditKey] = useState<string>("");
  const pendingCropFilesRef = useRef<File[]>([]);
  const croppedBatchFilesRef = useRef<File[]>([]);

  const closeCropModal = () => {
    setShowCropModal(false);
    setImageToCrop("");
    setCurrentEditKey("");
    setEditingIndex(null);
    setEditingIsExisting(false);
  };

  const openCropModalForFile = (file: File) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const originalData = e.target?.result as string;
      const uniqueKey = `${Date.now()}_${file.lastModified}_${file.name}`;
      setOriginalImagesMap((prev) =>
        new Map(prev).set(uniqueKey, originalData)
      );
      setImageToCrop(originalData);
      setCurrentEditKey(uniqueKey);
      setShowCropModal(true);
      setEditingIndex(null);
      setEditingIsExisting(false);
    };
    reader.readAsDataURL(file);
  };

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

    if (onChange) onChange(event);

    if (fileInputRef.current && event.target.files) {
      const newFiles = Array.from(event.target.files);
      const selectedFiles =
        multiple && !singleFileArray ? newFiles : newFiles.slice(0, 1);

      if (
        enableCropping &&
        selectedFiles.length > 0 &&
        selectedFiles.every((file) => file.type.startsWith("image/"))
      ) {
        croppedBatchFilesRef.current = [];
        pendingCropFilesRef.current = selectedFiles.slice(1);
        openCropModalForFile(selectedFiles[0]);
      } else {
        if (setFieldValue) {
          if (singleFileArray) setFieldValue(name, newFiles.slice(0, 1));
          else if (multiple) {
            const current = Array.isArray(field.value) ? field.value : [];
            setFieldValue(name, [...current, ...newFiles]);
          } else {
            setFieldValue(name, newFiles[0] || null);
          }
        }
      }

      fileInputRef.current.value = "";
    }
  };

  const handleCropComplete = (croppedImage: File) => {
    (croppedImage as KeyedFile).__originalKey = currentEditKey;

    if (editingIndex === null) {
      const croppedFiles = [...croppedBatchFilesRef.current, croppedImage];
      const [nextFile, ...remainingFiles] = pendingCropFilesRef.current;

      if (nextFile) {
        croppedBatchFilesRef.current = croppedFiles;
        pendingCropFilesRef.current = remainingFiles;
        closeCropModal();
        openCropModalForFile(nextFile);
        return;
      }

      if (setFieldValue) {
        if (singleFileArray) {
          setFieldValue(name, croppedFiles.slice(0, 1));
        } else if (multiple) {
          const current = Array.isArray(field.value) ? field.value : [];
          setFieldValue(name, [...current, ...croppedFiles]);
        } else {
          setFieldValue(name, croppedFiles[0] || null);
        }
      }

      croppedBatchFilesRef.current = [];
      pendingCropFilesRef.current = [];
      closeCropModal();
      return;
    }

    if (setFieldValue) {
      if (editingIsExisting) {
        if (onRemove) onRemove(editingIndex, true);
        if (multiple || singleFileArray) {
          const current = Array.isArray(field.value) ? field.value : [];
          setFieldValue(name, [...current, croppedImage]);
        } else {
          setFieldValue(name, croppedImage);
        }
      } else {
        if (multiple || singleFileArray) {
          const current = Array.isArray(field.value) ? field.value : [];
          const updated = current.map((f: unknown, i: number) =>
            i === editingIndex ? croppedImage : f
          );
          setFieldValue(name, updated);
        } else {
          setFieldValue(name, croppedImage);
        }
      }
    }
    closeCropModal();
  };

  const handleCropCancel = () => {
    pendingCropFilesRef.current = [];
    croppedBatchFilesRef.current = [];
    closeCropModal();
    if (fileInputRef.current) fileInputRef.current.value = "";
  };

  const removeFile = (indexToRemove?: number, isExistingFile?: boolean) => {
    if (!setFieldValue) return;
    if (isExistingFile && indexToRemove !== undefined && onRemove) onRemove(indexToRemove, true);
    else if (multiple && Array.isArray(field.value)) {
      setFieldValue(
        name,
        field.value.filter((_: unknown, i: number) => i !== indexToRemove)
      );
    } else {
      setFieldValue(name, null);
    }
    if (fileInputRef.current) fileInputRef.current.value = "";
  };

  const isImageFile = (file: unknown) => {
    if (!file) return false;
    if (typeof file === "string") return file.match(/\.(jpg|jpeg|png)$|data:image|http/) !== null;
    return file instanceof File && file.type.startsWith("image");
  };

  const getPreviewUrl = (file: File | string) => typeof file === "string" ? file : URL.createObjectURL(file);

  const showUploadButton = (multiple && !singleFileArray) ||
    ((!multiple || singleFileArray) && existingFiles.length === 0 &&
      (!field.value || (Array.isArray(field.value) && field.value.length === 0)));

  const hasFiles = existingFiles.length > 0 ||
    (field.value && (multiple || singleFileArray ? Array.isArray(field.value) && field.value.length > 0 : !!field.value));


  /*
   * Opening the cropper on an image that is already saved. It has to be
   * re-fetched through `loadImageWithCORS` first: the <img> is showing a URL on
   * the API's origin, and a canvas cannot read those pixels back without a
   * CORS-clean copy.
   */
  const beginCropExisting = async (file: { id: number; image: string }, idx: number) => {
    try {
      console.debug('Existing image clicked, loading:', file.image);
      const dataUrl = await loadImageWithCORS(file.image);
      const key = `existing_${file.id}_${Date.now()}`;
      setOriginalImagesMap(prev => new Map(prev).set(key, dataUrl));
      setImageToCrop(dataUrl);
      setCurrentEditKey(key);
      setShowCropModal(true);
      setEditingIndex(idx);
      setEditingIsExisting(true);
    } catch (err) {
      /* Not an API failure — this is an image load/decode error, so the
         message comes off `Error` rather than a response body. */
      console.error('Failed to load existing image for cropping:', file.image, err);
      alert(t("COMMON.IMAGE_EDIT_LOAD_FAILED"));
    }
  };

  /*
   * Re-cropping a file the user just picked. `__originalKey` points at the
   * uncropped bytes kept in `originalImagesMap`, so a second crop starts from
   * the original rather than compounding on the first crop's output.
   */
  const beginCropNew = (file: File, idx: number) => {
    const key = (file as KeyedFile).__originalKey;
    const orig = key ? originalImagesMap.get(key) : null;
    setImageToCrop(orig || getPreviewUrl(file));
    setCurrentEditKey(key || `${Date.now()}_${file.name}`);
    setShowCropModal(true);
    setEditingIndex(idx);
    setEditingIsExisting(false);
  };

  return {
    field,
    fileInputRef,
    showCropModal,
    imageToCrop,
    currentEditKey,
    handleFileChange,
    handleCropComplete,
    handleCropCancel,
    removeFile,
    isImageFile,
    getPreviewUrl,
    showUploadButton,
    hasFiles,
    beginCropExisting,
    beginCropNew,
  };
}
