"use client";

import { useRef } from "react";
import { ErrorMessage, useField } from "formik";
import { FaPlus } from "react-icons/fa";
import { useTranslation } from "react-i18next";

/**
 * The organisation licence/document types the server accepts
 * (`OrganizationIntake::documentRules()`: pdf, jpg, jpeg, png, webp, doc, docx,
 * 10 MB). Offered to the picker so a wrong type is not chosen in the first place.
 */
const DOCUMENT_ACCEPT = ".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx";

interface ExistingFile {
  id: number | string;
  name: string;
  /* `| null`: these come from `OrganizationDocumentResource`, where
     `document` is `getimg($row->document)` and so null for a row with no
     file. The preview link below is already guarded. */
  url?: string | null;
}

interface UploadInputProps {
  name: string;
  label: string;
  onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
  existingFiles?: ExistingFile[];
  accept?: string;
  multiple?: boolean;
  onRemoveExisting?: (id: number | string) => void;
}

const UploadInput: React.FC<UploadInputProps> = ({
  name,
  label,
  existingFiles,
  accept = DOCUMENT_ACCEPT,
  multiple = true,
  onRemoveExisting,
}) => {
  const { t } = useTranslation();
  const [field, , helpers] = useField<File[]>(name);
  /*
   * Read straight off the Formik field — there is no local copy any more.
   *
   * There used to be a `selectedFiles` state holding the same array, written
   * alongside every `helpers.setValue` and re-synced from an effect whenever the
   * Formik value emptied. Two sources of truth for one list: a Formik
   * `resetForm` cleared the field but left the local copy on screen until the
   * effect ran a frame later, and a `setFieldValue` from anywhere else was never
   * reflected at all.
   */
  const selectedFiles = field.value ?? [];
  const inputRef = useRef<HTMLInputElement>(null);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files) {
      const filesArray = Array.from(event.target.files);
      helpers.setValue(multiple ? [...selectedFiles, ...filesArray] : filesArray.slice(0, 1));
    }
    // Cleared so re-picking a file that was just removed still fires a change.
    event.target.value = "";
  };

  const handleRemoveFile = (index: number) => {
    helpers.setValue(selectedFiles.filter((_, i) => i !== index));
  };

  /**
   * The whole box opens the picker, not just the label and the plus icon.
   * Clicks that land on the label or the input (both of which already open it)
   * or on a file chip's link / remove button are left alone — otherwise
   * removing a file would immediately reopen the dialog.
   */
  const handleContainerClick = (event: React.MouseEvent<HTMLDivElement>) => {
    if ((event.target as HTMLElement).closest("a, button, label, input")) return;
    inputRef.current?.click();
  };

  const existingCount = existingFiles?.length ?? 0;
  const hasAnyFiles = existingCount > 0 || selectedFiles.length > 0;

  return (
    <>
      <div
        className="relative w-full border border-[#29246D1A] rounded-2xl p-3 bg-[#29246D08] flex flex-col gap-2 cursor-pointer focus-within:border-primary-5"
        onClick={handleContainerClick}
      >
        <label
          className="text-primary-5 cursor-pointer flex items-center justify-between gap-2"
          htmlFor={`${name}-input`}
        >
          <span>{label}</span>
          <FaPlus size={20} aria-hidden="true" />
        </label>
        {/* `sr-only` rather than `hidden`: keeps the input focusable, so the
            field is still reachable and openable from the keyboard. */}
        <input
          ref={inputRef}
          id={`${name}-input`}
          type="file"
          multiple={multiple}
          accept={accept}
          className="sr-only"
          onChange={handleFileChange}
        />
        {hasAnyFiles && (
          <div className="flex flex-wrap gap-2">
            {existingFiles?.map((file) => (
              <div
                key={file.id}
                className="flex items-center text-primary-5 px-2 py-1 rounded-md"
              >
                {file.url ? (
                  <a
                    href={file.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="mr-2 text-[#29246D] font-bold underline cursor-pointer"
                  >
                    {file.name}
                  </a>
                ) : (
                  <span className="mr-2 text-[#29246D] font-bold">{file.name}</span>
                )}
                {onRemoveExisting && (
                  <button
                    type="button"
                    onClick={() => onRemoveExisting(file.id)}
                    aria-label={`${t("COMMON.REMOVE_FILE")} ${file.name}`}
                    className="text-[#000000] ml-1"
                  >
                    &#x2715;
                  </button>
                )}
              </div>
            ))}
            {selectedFiles.map((file, index) => (
              <div
                key={index}
                className="flex items-center text-primary-5 px-2 py-1 rounded-md"
              >
                {/* The picked file's own name — it was a hard-coded English
                    «Certificate N», the same in the Arabic interface. */}
                <span className="mr-2 text-[#29246D] font-bold">
                  {file?.name || `${t("COMMON.CERTIFICATE")} ${existingCount + index + 1}`}
                </span>
                <button
                  type="button"
                  onClick={() => handleRemoveFile(index)}
                  aria-label={`${t("COMMON.REMOVE_FILE")} ${file?.name ?? ""}`.trim()}
                  className="text-[#000000] ml-1"
                >
                  &#x2715;
                </button>
              </div>
            ))}
          </div>
        )}
      </div>
      <ErrorMessage
        name={name}
        component="div"
        className="text-red-500 text-sm mt-1"
      />
    </>
  );
};

export default UploadInput;
export { UploadInput };
