"use client";

import { ErrorMessage } from "formik";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/Button";
import CropModal from "./CropModal";
import UploadFileList from "./UploadFileList";
import { useUploadDocument, type UploadInputProps } from "./useUploadDocument";
import AssetIcon from "@/components/ui/AssetIcon";

const UploadDocument: React.FC<UploadInputProps> = (props) => {
  const {
    name,
    label,
    instructions = [],
    multiple = true,
    singleFileArray = false,
    accept,
    existingFiles = [],
    enableCropping = false,
    cropAspectRatio = 16 / 9,
    cropShape = "rect",
    cropWidth,
    cropHeight,
    cropDisplayMode,
  } = props;
  const { t } = useTranslation();
  const {
    field,
    fileInputRef,
    showCropModal,
    imageToCrop,
    currentEditKey,
    handleFileChange,
    handleCropComplete,
    handleCropCancel,
    removeFile,
    isImageFile,
    getPreviewUrl,
    showUploadButton,
    hasFiles,
    beginCropExisting,
    beginCropNew,
  } = useUploadDocument(props);

  return (
    <>
      <div className="border rounded-xl bg-[#29246D]/[0.03] text-center uplods">
        <div className="borderitm m-4 border-spacing-6 p-7">
          <div className="flex justify-center gap-1 items-center">
            <AssetIcon src="/assets/profile/uploadicn.svg" alt="" className="h-5 w-5" size={20} />
            <label className="text-[#1A1E25] text-lg font-semibold">
              {label}
            </label>
          </div>

          {instructions.length > 0 && (
            <p className="text-sm text-gray-500 mt-1">
              {instructions.map((inst, i) => (
                <span key={i} className="text-[#1E1E1E]/70 text-lg xs:text-sm">
                  • {inst}
                  <br />
                </span>
              ))}
            </p>
          )}

          {enableCropping && (
            <div className="text-sm text-primary-5 mt-2 p-2 rounded-lg">
              {/* <p>{t("COMMON.CROP_INFO")}</p> */}
              {/* {cropDisplayMode === "opportunity" && (
                <p className="mt-1 text-xs">{t("COMMON.CROP_FRAME_INFO")}</p>
              )} */}
              {/* Said before the picker opens, not after three files are
                  silently dropped. */}
              {/* {singleFileArray && (
                <p className="mt-1 text-xs font-semibold">
                  {t("COMMON.SINGLE_IMAGE_ONLY")}
                </p>
              )} */}
            </div>
          )}

          {showUploadButton && (
            <>
              {/*
                `singleFileArray` keeps the field's value an array — the forms
                submit `new_*_images_0`, so the shape must not change — while
                allowing exactly one entry. The OS picker must therefore not
                offer multi-select: `handleFileChange` already slices to the
                first file, so a user who shift-selects four would otherwise
                watch three vanish with no explanation.
              */}
              <input
                id={`${name}-input`}
                type="file"
                multiple={multiple && !singleFileArray}
                accept={accept}
                className="hidden"
                onChange={handleFileChange}
                ref={fileInputRef}
              />
              <div className="flex justify-center pt-4">
                <Button
                  type="button"
                  variant="secondarys"
                  size="medium"
                  onClick={() =>
                    document.getElementById(`${name}-input`)?.click()
                  }
                >
                  {t("COMMON.UPLOAD")}
                </Button>
              </div>
            </>
          )}

          {hasFiles && (
            <UploadFileList
              multiple={multiple}
              singleFileArray={singleFileArray}
              existingFiles={existingFiles}
              fieldValue={field.value}
              isImageFile={isImageFile}
              getPreviewUrl={getPreviewUrl}
              onEditExisting={beginCropExisting}
              onEditNew={beginCropNew}
              onRemove={removeFile}
            />
          )}

          <ErrorMessage
            name={name}
            component="div"
            className="text-red-500 text-sm mt-1"
          />
        </div>
      </div>

      {showCropModal && (
        <CropModal
          key={currentEditKey}
          imageSrc={imageToCrop}
          onCropComplete={handleCropComplete}
          onCancel={handleCropCancel}
          aspectRatio={cropAspectRatio}
          cropShape={cropShape}
          cropWidth={cropWidth}
          cropHeight={cropHeight}
          cropDisplayMode={cropDisplayMode}
        />
      )}
    </>
  );
};

export default UploadDocument;
export { UploadDocument };
