"use client";

import React, { useRef, useState } from "react";
import { useTranslation } from "react-i18next";

import { Button } from "@/components/ui/Button";
import AssetIcon from "@/components/ui/AssetIcon";
import CoverImage from "@/components/ui/CoverImage";
import { useObjectUrls } from "@/components/ui/useObjectUrls";

interface UploadImageWithSaveProps {
  label: string;
  instructions?: string[];
  multiple?: boolean;
  accept?: string;
  value: File[];
  onChange: (files: File[]) => void;
  onRemove: (index: number) => void;
  /** Return the upload's promise and Save stays disabled until it settles. */
  onSave: () => void | Promise<unknown>;
  /**
   * Rejects a picked file before it joins the list; `invalidMessage` is then
   * shown under the box. Without it, a file of any type or size was queued and
   * only the server's 422 said otherwise.
   */
  isFileAllowed?: (file: File) => boolean;
  invalidMessage?: string;
}

export default function UploadImageWithSave({
  label,
  instructions = [],
  multiple = true,
  accept,
  value,
  onChange,
  onRemove,
  onSave,
  isFileAllowed,
  invalidMessage,
}: UploadImageWithSaveProps) {
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { t } = useTranslation();
  const previewUrls = useObjectUrls(value);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    event.preventDefault();
    event.stopPropagation();
    if (event.target.files) {
      const picked = Array.from(event.target.files);
      const allowed = isFileAllowed ? picked.filter(isFileAllowed) : picked;
      setError(allowed.length < picked.length ? invalidMessage ?? null : null);
      if (allowed.length > 0) onChange([...value, ...allowed]);
    }
    if (fileInputRef.current) fileInputRef.current.value = "";
  };

  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/uploadic.svg" 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((instruction, index) => (
              <span className="text-[#1E1E1E]/70 text-lg xs:text-sm" key={index}>
                • {instruction}
                <br />
              </span>
            ))}
          </p>
        )}
        <div className="flex justify-center pt-4 gap-4 items-center">
          <input
            id="upload-image-input"
            type="file"
            multiple={multiple}
            accept={accept}
            className="hidden"
            onChange={handleFileChange}
            ref={fileInputRef}
          />
          <Button
            type="button"
            variant="secondarys"
            size="medium"
            onClick={(event) => {
              event.preventDefault();
              fileInputRef.current?.click();
            }}
          >
            {t("COMMON.UPLOAD")}
          </Button>
          {value.length > 0 && (
            <Button
              type="button"
              variant="primary"
              size="medium"
              onClick={() => {
                if (saving) return;
                const pending = onSave();
                if (pending instanceof Promise) {
                  setSaving(true);
                  const done = () => setSaving(false);
                  pending.then(done, done);
                }
              }}
              loading={saving}
              className="ml-2"
            >
              {t("COMMON.SAVE")}
            </Button>
          )}
        </div>
        {error && (
          <p role="alert" className="mt-3 text-sm text-red-500">
            {error}
          </p>
        )}
        {value.length > 0 && (
          <div className="mt-4">
            <h4 className="text-sm font-medium text-[#1A1E25] mb-2">
              {t("COMMON.UPLOADED_FILES")}:
            </h4>
            <div className="grid grid-cols-1 sm:grid-cols-4 gap-4 max-h-40 overflow-y-auto">
              {value.map((file, index) => (
                <div
                  key={`${file.name}-${index}`}
                  className="rounded-lg p-2 flex flex-col items-center justify-center"
                >
                  <div className="w-20 h-20 relative flex items-center justify-center">
                    {previewUrls[index] && (
                      // The 80x80 wrapper above is already `relative`, so the
                      // filled image reserves that box without the thumbnail's
                      // own bytes deciding it.
                      <CoverImage
                        src={previewUrls[index]}
                        alt={file.name}
                        className="object-cover rounded"
                        sizes="80px"
                      />
                    )}
                    <button
                      type="button"
                      onClick={() => onRemove(index)}
                      aria-label={`${t("COMMON.REMOVE_FILE")} ${file.name}`}
                      className="absolute -top-2 -right-5 rtl:-left-5 rtl:right-auto text-red-500 hover:text-red-700 text-lg"
                    >
                      ✕
                    </button>
                  </div>
                  <span className="text-xs text-[#1E1E1E]/70 mt-2 truncate w-20">
                    {file.name}
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
