"use client";

import { useCallback, useState } from "react";
import type { FormikValues } from "formik";

/** One already-stored file, as the form tracks it alongside new uploads. */
export interface StoredImage {
  id: number;
  image: string;
}

/**
 * Which of a saved opportunity's files are kept, removed, or replaced.
 *
 * Shared by both publish forms — the rules are the same whether the record is
 * a volunteering opportunity or a development one, and they were written out
 * twice, identically.
 *
 * Four pieces of state that only make sense together:
 *   - `modifiedOpportunityImages` / `modifiedLicenseImage` — what the pickers
 *     display for files that are already on the server;
 *   - `existingImageIds` — the keep-set the payload sends, so the backend knows
 *     what *not* to delete;
 *   - `removedImageIds` — what to delete outright after a successful save.
 *
 * Formik cannot hold any of it: its value is a `File[]`, and a stored image is
 * a URL with an id, not a file. Removing one therefore has to update both — the
 * local record *and* the Formik value — which is the bug this gathers in one
 * place: dropping a thumbnail while leaving its id in the keep-set silently
 * resurrects the image on save.
 */
/** The stored-file bookkeeping, passed down as one prop. */
export type OpportunityMedia = ReturnType<typeof useOpportunityMedia>;

export function useOpportunityMedia() {
  const [modifiedOpportunityImages, setModifiedOpportunityImages] = useState<
    StoredImage[]
  >([]);
  const [modifiedLicenseImage, setModifiedLicenseImage] = useState<StoredImage[]>(
    []
  );
  const [existingImageIds, setExistingImageIds] = useState<number[]>([]);
  const [removedImageIds, setRemovedImageIds] = useState<number[]>([]);

  /**
   * Seed from the loaded record.
   *
   * Callers pass only announcement media, for editing or reposting. Completion
   * gallery images belong to the previous run and never seed the cover picker.
   */
  const seedFromOpportunity = useCallback(
    (images: StoredImage[], licenseImage: string | null | undefined) => {
      setModifiedOpportunityImages(images);
      setExistingImageIds(images.map((image) => image.id));
      setModifiedLicenseImage(licenseImage ? [{ id: 0, image: licenseImage }] : []);
    },
    []
  );

  const reset = useCallback(() => {
    setModifiedOpportunityImages([]);
    setExistingImageIds([]);
  }, []);

  /** Clears the delete queue once the server has acted on it. */
  const clearRemoved = useCallback(() => setRemovedImageIds([]), []);

  /**
   * Remove one file from a picker.
   *
   * `isExistingFile` separates the two cases that look identical on screen: a
   * thumbnail of something already saved (which has to leave the keep-set and
   * join the delete queue) and one of a file picked a moment ago (which only
   * has to leave the Formik array).
   */
  const removeFile = (
    index: number,
    isExistingFile: boolean,
    fieldName: string,
    setFieldValue: (field: string, value: unknown) => void,
    values: FormikValues
  ) => {
    if (isExistingFile) {
      if (fieldName === "opportunity_images") {
        const removedImageId = modifiedOpportunityImages[index]?.id;
        if (removedImageId != null) {
          setRemovedImageIds((previous) =>
            previous.includes(removedImageId)
              ? previous
              : [...previous, removedImageId]
          );
        }
        setModifiedOpportunityImages((previous) =>
          previous.filter((_, i) => i !== index)
        );
        setExistingImageIds((previous) =>
          previous.filter((imageId) => imageId !== removedImageId)
        );
        // Keep only the newly uploaded files in the Formik value (no URLs).
        const currentFiles = Array.isArray(values[fieldName])
          ? values[fieldName]
          : [];
        setFieldValue(
          fieldName,
          currentFiles.filter((file: unknown) => file instanceof File)
        );
      } else if (fieldName === "license_image") {
        setModifiedLicenseImage([]);
        setFieldValue("license_image", "");
        // Tell the backend to drop the stored image.
        setFieldValue("license_image_removed", true);
      }
      return;
    }

    if (fieldName === "license_image") {
      setFieldValue("license_image", "");
    } else if (fieldName === "opportunity_images") {
      const currentFiles = Array.isArray(values[fieldName])
        ? [...values[fieldName]]
        : [];
      currentFiles.splice(index, 1);
      setFieldValue(fieldName, currentFiles);
    }
  };

  return {
    modifiedOpportunityImages,
    modifiedLicenseImage,
    existingImageIds,
    removedImageIds,
    seedFromOpportunity,
    reset,
    clearRemoved,
    removeFile,
  };
}
