import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { aclSchema } from "./validation.yup";
import { IFile } from "../interface";
import useRenameFile from "../hooks/useRenameFile";
import { configSrore } from "../configSrore";
import { PencilIcon, XIcon } from "../svg";

interface IProps {
  fileInfo: IFile;
  page: number;
  refetch: () => void;
}

interface IForm {
  newName: string;

}

const RenameFile = ({ fileInfo, page, refetch }: IProps) => {
  const [open, setOpen] = useState(false);
  const [extensionError, setExtensionError] = useState<string | null>(null);


  const renameHook = useRenameFile(
    configSrore?.resourceId,
    fileInfo.hash,
  );

  const form = useForm<IForm>({
    resolver: yupResolver(aclSchema),
  });

  const { register, handleSubmit, formState, reset, clearErrors } = form;
  const { errors } = formState;

  const handleClose = () => {
    setOpen(!open);
    reset();
  };

  const handleOpen = () => {
    setOpen(!open);
  };

  const handleReset = () => {
    reset();
    clearErrors();
  };

  const onSubmit = async (data: IForm) => {
    if (!data.newName.includes(".")) {
      setExtensionError("لطفا پسوند فایل را وارد کنید");
      return;
    }
    renameHook.mutate({
      page,
      ...data,
      callBack: () => {
        refetch();
        handleOpen();
        handleReset();
      },
    });
  };

  return (
    <div className="rename-file-dialog dialog-content">
      <button
        className="dialog-content__button btn p-0 bg-transparent hover:bg-transparent"
        onClick={handleClose}
        disabled={renameHook.isError}
      >
        <PencilIcon className="dialog-content__button-icon h-5 w-5 fill-info" />
      </button>
      <div
        role="button"
        tabIndex={0}
        className={`dialog-content__modal modal cursor-default  ${
          open ? "modal-open" : ""
        }`}
        onClick={() => {
          return setOpen(false);
        }}
      >
        <div
          onClick={(e) => {
            return e.stopPropagation();
          }}
          role="button"
          tabIndex={-1}
          className="modal-box p-0 overflow-hidden text-right cursor-default"
        >
          <div className="overflow-auto modal-box">
            <div className="flex flex-wrap items-center">
              <h3 className="modal-title">ویرایش نام فایل</h3>
              <button
                className="w-fit mr-auto"
                onClick={() => {
                  handleClose();
                }}
              >
                <XIcon className="stroke-base-200 w-4 h-4" />
              </button>
            </div>

            <form
              className="dialog-content__form mt-[30px] flex flex-col"
              onSubmit={handleSubmit(onSubmit)}
            >
              <label htmlFor="file-rename-id">نام جدید</label>
              <input
                id="file-rename-id"
                {...register("newName", {
                  value: `${fileInfo.name || ""}.${fileInfo.extension || ""}`,
                })}
                type="text"
                placeholder="نام جدید فایل را وارد کنید"
                className="dialog-content__Input input input-bordered w-full mt-[10px]"
                onChange={() => { return setExtensionError(null); }}
              />
              {errors?.newName || extensionError ? (
                <small className="dialog-content__errorText text-secondary text-sm w-full h-5 block mt-3">
                  {errors?.newName?.message || extensionError}
                </small>
              ) : null}

              <div className="dialog-content__action-part modal-action mt-[30px]">
                {renameHook.isLoading ? (
                  <div className="spinner" />
                ) : (
                  <>
                    <button
                      className="dialog-content__submit btn modal-btn-success"
                      type="submit"
                    >
                      ارسال
                    </button>

                    <button
                      className="dialog-content__btns btn modal-btn-cancel"
                      type="button"
                      onClick={handleClose}
                    >
                      انصراف
                    </button>
                  </>
                )}
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default RenameFile;
