import {
  cloneElement,
  useContext,
  useState,
  useEffect,
  isValidElement,
} from "react";
import type { HTMLAttributes, ReactElement, MouseEvent } from "react";
import { Btn } from "../../btn";
import { Locale } from "../../locale";
import type { IFilesUploaderItem } from "../config/types";
import { FilesUploaderCtx } from "../context/index";
import { getFileSizeInMb } from "../lib/index";

/**
 * Компонент вывода элемента списка загруженных файлов
 * @param file - файл
 * @returns
 * */
export const FilesUploaderItem = ({ file }: { file: Required<IFilesUploaderItem> | File; }): ReactElement => {

  const {
    getCN,
    slotFileItem,
    isDisabled,
    isLoading,
    onDeleteClick,
    onFileRender,
    setFilesMap,
  } = useContext(FilesUploaderCtx);

  const name = file?.name ?? <Locale code={"filesUploader.unknownFile"} />;
  const size = getFileSizeInMb(file?.size ?? 0).toFixed(2);
  const link = ("href" in file && typeof file?.href === "string" && file.href.length) ? file.href : null;

  const [ isFileLoading, setIsFileLoading ] = useState(isLoading);

  const onDelete = (e: MouseEvent) => {
    e.preventDefault();
    setIsFileLoading(true);
    onDeleteClick(file)
      .finally(() => {
        setIsFileLoading(false);
      });
  };

  useEffect(() => {
    if (typeof onFileRender === "function") {
      onFileRender({
        file,
        stateActions: {
          setFiles: setFilesMap,
          setIsLoading: setIsFileLoading,
        },
      });
    }
  }, []);

  return (
    <li className={getCN("listItem", { isDisabled })}>
      {(!!slotFileItem && isValidElement(slotFileItem)) ? cloneElement(slotFileItem, {
        ...(slotFileItem?.props ?? {}),
        isDisabled,
        file,
        onDeleteClick,
      } as HTMLAttributes<HTMLElement>) : (
        <div className={getCN("file", { isLink: !!link })}>
          <div className={getCN("fileData")}>
            {!!link ? <a download={true} href={link} className={getCN("fileName")} title={name}>{name}</a> : <div className={getCN("fileName")} title={name}>{name}</div>}
            <div className={getCN("fileSize")}>
              <span className={getCN("fileSizeValue")}>{size}</span>&nbsp;
              <span className={getCN("fileSizeMeasure")}>
                <Locale code={"filesUploader.megaByte"} />
              </span>
            </div>
          </div>
          <div className={getCN("fileActions")}>
            <Btn
              size={"small"}
              extraClasses={{ isOnlyIcon: true }}
              label={null}
              icon={"remove"}
              iconSize={"small"}
              isDisabled={isDisabled || isLoading || isFileLoading}
              onClick={onDelete}
            />
          </div>
        </div>
      )}
    </li>
  );
};
