"use client";

/*
 * The raw `<img>`s came over verbatim from `UploadDocument`: the previews point
 * at `blob:` URLs and API-origin URLs that `next/image` is configured not to
 * optimise anyway. They are left reported rather than suppressed.
 */
import { useTranslation } from "react-i18next";
import CoverImage from "@/components/ui/CoverImage";

/**
 * The thumbnails under the upload button: images already saved, then files just
 * picked. Clicking a thumbnail re-opens the cropper; the ✕ removes it.
 *
 * Takes two callbacks rather than the parent's six setters, because "which
 * image is being cropped" is the parent's state to own.
 */
export default function UploadFileList({
  multiple,
  singleFileArray,
  existingFiles,
  fieldValue,
  isImageFile,
  getPreviewUrl,
  onEditExisting,
  onEditNew,
  onRemove,
}: {
  multiple?: boolean;
  singleFileArray?: boolean;
  existingFiles: Array<{ id: number; image: string }>;
  /* Formik's value for this field: one File, several, or nothing yet. */
  fieldValue: File | File[] | null | undefined;
  /* Takes either a picked File or an existing image's URL. */
  isImageFile: (file: File | string) => boolean;
  getPreviewUrl: (file: File | string) => string;
  onEditExisting: (file: { id: number; image: string }, index: number) => void;
  onEditNew: (file: File, index: number) => void;
  onRemove: (indexToRemove?: number, isExistingFile?: boolean) => void;
}) {
  const { t } = useTranslation();

  return (
    <div className="mt-4">
      <h4 className="text-sm font-medium text-[#1A1E25] mb-2">
        {t("COMMON.UPLOADED")} {multiple && !singleFileArray ? t("COMMON.FILES") : t("COMMON.FILE")}:
      </h4>
      <div className="grid grid-cols-1 sm:grid-cols-4 gap-4 max-h-40 overflow-y-auto">
        {existingFiles.map((file, idx) => (
          <div key={`existing-${file.id}`} className="rounded-lg p-2 flex flex-col items-center">
            <div className="w-20 h-20 relative">
              {isImageFile(file.image) ? (
                /* The click opens the crop dialog, so it belongs on a
                    button: on the bare <img> it was mouse-only, while the
                    remove control beside it was already keyboard-reachable.

                    `relative` is on the button so the filled image anchors to
                    it rather than to the 80x80 wrapper above — the same box,
                    but the image stays inside the control it belongs to. */
                <button type="button" aria-label={t("COMMON.EDIT_TEXT")}
                  className="relative w-full h-full rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-5"
                  onClick={() => onEditExisting(file, idx)}>
                  <CoverImage src={file.image} alt="" className="object-cover rounded cursor-pointer" sizes="80px" />
                </button>
              ) : (
                <div className="bg-gray-200 w-full h-full rounded flex items-center justify-center"><span className="text-xs text-gray-500">{t("COMMON.FILE")}</span></div>
              )}
              <button type="button" onClick={() => onRemove(idx, true)} aria-label={t("COMMON.REMOVE_FILE")} className="absolute -top-2 -right-5 text-red-500 text-lg">✕</button>
            </div>
            <span className="text-xs text-[#1E1E1E]/70 mt-2 w-full min-w-0 whitespace-normal text-center [overflow-wrap:anywhere]">{file.image.split("/").pop()}</span>
          </div>
        ))}

        {(multiple || singleFileArray) && Array.isArray(fieldValue) && fieldValue.map((file: File, idx: number) => (
          <div key={`new-${idx}`} className="rounded-lg p-2 flex flex-col items-center">
            <div className="w-20 h-20 relative">
              {isImageFile(file) ? (
                <button type="button" aria-label={`${t("COMMON.EDIT_TEXT")} ${file.name}`}
                  className="relative w-full h-full rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-5"
                  onClick={() => onEditNew(file, idx)}>
                  <CoverImage src={getPreviewUrl(file)} alt="" className="object-cover rounded cursor-pointer" sizes="80px" />
                </button>
              ) : (
                <div className="bg-gray-200 w-full h-full rounded flex items-center justify-center"><span className="text-xs">{t("COMMON.FILE")}</span></div>
              )}
              <button type="button" onClick={() => onRemove(idx)} aria-label={`${t("COMMON.REMOVE_FILE")} ${file.name}`} className="absolute -top-2 -right-5 text-red-500 text-lg">✕</button>
            </div>
            <span className="text-xs text-[#1E1E1E]/70 mt-2 w-full min-w-0 whitespace-normal text-center [overflow-wrap:anywhere]">{file.name}</span>
          </div>
        ))}

        {!multiple && fieldValue && !Array.isArray(fieldValue) && (
          <div className="rounded-lg p-2 flex flex-col items-center">
            <div className="w-20 h-20 relative">
              {isImageFile(fieldValue) ? (
                <button type="button" aria-label={`${t("COMMON.EDIT_TEXT")} ${(fieldValue as File).name}`}
                  className="relative w-full h-full rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-5"
                  onClick={() => onEditNew(fieldValue as File, 0)}>
                  <CoverImage src={getPreviewUrl(fieldValue)} alt="" className="object-cover rounded cursor-pointer" sizes="80px" />
                </button>
              ) : (
                <div className="bg-gray-200 w-full h-full rounded flex items-center justify-center"><span className="text-xs">{t("COMMON.FILE")}</span></div>
              )}
              <button type="button" onClick={() => onRemove()} aria-label={`${t("COMMON.REMOVE_FILE")} ${(fieldValue as File).name}`} className="absolute -top-2 -right-5 text-red-500 text-lg">✕</button>
            </div>
            <span className="text-xs text-[#1E1E1E]/70 mt-2 w-full min-w-0 whitespace-normal text-center [overflow-wrap:anywhere]">{(fieldValue as File).name}</span>
          </div>
        )}
      </div>
    </div>
  );
}
