import React from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import MkdSDK from "@/utils/MkdSDK";
import { useNavigate } from "react-router-dom";
import { tokenExpireError } from "@/context/Auth";
import { GlobalContext, showToast } from "@/context/Global";
import "react-quill/dist/quill.snow.css";

const AddSowPage = ({
  setSidebar,
  onSowCreated,
  action = "navigate",
  wireframe,
}) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const schema = yup
    .object({
      name: yup.string(),
      transcripts: yup.string(),
    })
    .required();

  const { dispatch } = React.useContext(GlobalContext);
  const [fileObj, setFileObj] = React.useState({});
  const [isUpdating, setIsUpdating] = React.useState(false);

  const navigate = useNavigate();
  const {
    register,
    handleSubmit,
    setError,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const previewImage = (field, target) => {
    let tempFileObj = fileObj;
    tempFileObj[field] = {
      file: target.files[0],
      tempURL: URL.createObjectURL(target.files[0]),
      fileName: target.files[0].name,
    };
    setFileObj({ ...tempFileObj });
  };

  const onSubmit = async (_data) => {
    let sdk = new MkdSDK();
    setIsUpdating(true);
    try {
      for (let item in fileObj) {
        let formData = new FormData();
        formData.append("file", fileObj[item].file);
        let uploadResult = await sdk.uploadImage(formData);
        _data[item] = uploadResult.url;
      }

      sdk.setTable("sow");
      const result = await sdk.callRestAPI(
        {
          name: _data.name,
          pdf_file: _data.pdf_file,
        },
        "POST"
      );
      if (!result.error) {
        showToast(globalDispatch, "Added");
        switch (action) {
          case "navigate":
            return navigate("/admin/requirements");
          case "close":
            if (onSowCreated) {
              onSowCreated(result?.data);
            }
            break;
        }
      } else {
        if (result.validation) {
          const keys = Object.keys(result.validation);
          for (let i = 0; i < keys.length; i++) {
            const field = keys[i];
            setError(field, {
              type: "manual",
              message: result.validation[field],
            });
          }
        }
      }
    } catch (error) {
      setError("name", {
        type: "manual",
        message: error.message,
      });
      tokenExpireError(dispatch, error.message);
    }
    setIsUpdating(false);
  };

  React.useEffect(() => {
    setValue("name", wireframe?.name);
  }, []);

  // React.useEffect(() => {
  //   globalDispatch({
  //     type: "SETPATH",
  //     payload: {
  //       path: action === "navigate" ? "sow" : "wireframe",
  //     },
  //   });
  // }, []);

  return (
    <div className="mx-auto  rounded">
      <div
        className={`flex items-center justify-between gap-4 border-b border-b-[#E0E0E0] p-3`}
      >
        <div className="flex items-center gap-3">
          <svg
            onClick={() => setSidebar(false)}
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            viewBox="0 0 24 24"
            fill="none"
          >
            <path
              d="M14.3322 5.83203L19.8751 11.3749C20.2656 11.7654 20.2656 12.3986 19.8751 12.7891L14.3322 18.332M19.3322 12.082H3.83218"
              stroke="#A8A8A8"
              stroke-width="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
          <span className="text-lg font-semibold">Add SOW</span>
        </div>
        <div className="flex items-center gap-4">
          <button
            className="flex items-center rounded-md border border-[#C6C6C6] px-3 py-2 shadow-sm hover:bg-[#f4f4f4]"
            onClick={() => setSidebar(false)}
          >
            Cancel
          </button>
          <button
            className="flex items-center rounded-md bg-[#4F46E5] px-3 py-2 text-white shadow-sm"
            onClick={async () => {
              await handleSubmit(onSubmit)();
              setSidebar(false);
            }}
            disabled={isUpdating}
          >
            {isUpdating ? "Saving..." : "Save"}
          </button>
        </div>
      </div>
      <form
        className=" w-full max-w-lg p-4 text-left"
        onSubmit={handleSubmit(onSubmit)}
      >
        <div className="mb-6">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="name"
          >
            Name
          </label>
          <input
            placeholder="Name"
            {...register("name")}
            className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${
              errors.name?.message ? "border-red-500" : ""
            }`}
          />
          <p className="text-xs italic text-red-500">{errors.name?.message}</p>
        </div>

        <div
          className={`relative flex min-h-[30vh] min-w-[100%] max-w-fit flex-col items-center justify-center gap-2 rounded-lg border border-[#a8a8a8] bg-[#f4f4f4] p-5`}
        >
          <div>
            <button className="my-auto flex max-w-[100px] cursor-pointer items-center justify-center self-end whitespace-nowrap rounded-md bg-[#4F46E5] px-5 py-2 text-white shadow-sm">
              <span>
                PDF &nbsp;
                {fileObj.pdf_file ? "Uploaded" : "Upload"}
              </span>
              <input
                className="absolute left-0 h-full w-full opacity-0"
                type="file"
                accept=".pdf"
                onChange={(e) => previewImage("pdf_file", e.target)}
              />
            </button>
          </div>
          <p className="text-medium text-sm text-[#525252]">
            {fileObj.pdf_file
              ? fileObj.pdf_file.fileName
              : "Select a PDF Requirement"}
          </p>
        </div>
      </form>
    </div>
  );
};

export default AddSowPage;
