import React, { useEffect, useState } 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 TreeSDK from "@/utils/TreeSDK";
import { useNavigate, useParams } from "react-router-dom";
import { GlobalContext, showToast } from "@/context/Global";
import { AuthContext, tokenExpireError } from "@/context/Auth";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import { isImage, empty, isVideo, isPdf } from "@/utils/utils";

let sdk = new MkdSDK();

const EditWireframePage = () => {
  const { dispatch } = React.useContext(AuthContext);
  const schema = yup
    .object({
      name: yup.string(),
      config: yup.string(),
      sow_id: yup.string(),
      status: yup.string(),
    })
    .required();
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [fileObj, setFileObj] = React.useState({});
  const navigate = useNavigate();

  const [name, setName] = useState("");
  const [config, setConfig] = useState("");
  const [sow_id, setSowId] = useState(0);
  const [status, setStatus] = useState(0);
  const [sows, setSows] = useState([]);
  const [id, setId] = useState(0);
  const {
    register,
    handleSubmit,
    setError,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const params = useParams();

  useEffect(function () {
    (async function () {
      try {
        sdk.setTable("wireframe");
        const result = await sdk.callRestAPI({ id: Number(params?.id) }, "GET");
        if (!result.error) {
          setValue("name", result.model.name);
          setValue("config", result.model.config);
          setValue("sow_id", result.model.sow_id);
          setValue("status", result.model.status);

          setName(result.model.name);
          setConfig(result.model.config);
          setSowId(result.model.sow_id);
          setStatus(result.model.status);
          setId(result.model.id);
        }
      } catch (error) {
        console.log("error", error);
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, []);

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

  const onSubmit = async (_data) => {
    try {
      sdk.setTable("wireframe");
      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;
      }
      const result = await sdk.callRestAPI(
        {
          id: id,

          name: _data.name,
          config: _data.config,
          sow_id: _data.sow_id,
          status: _data.status,
        },
        "PUT"
      );

      if (!result.error) {
        showToast(globalDispatch, "Updated");
        navigate("/admin/build");
      } 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) {
      console.log("Error", error);
      setError("name", {
        type: "manual",
        message: error.message,
      });
    }
  };
  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "wireframe",
      },
    });
  }, []);

  React.useEffect(() => {
    (async () => {
      new TreeSDK()
        .getList("sow")
        .then((res) => setSows(res.list))
        .catch((err) => console.log(err));
    })();
  }, []);

  return (
    <div className=" mx-auto rounded   p-5 shadow-md">
      <h4 className="text-2xl font-medium">Edit Wireframe</h4>
      <form className=" w-full max-w-lg" onSubmit={handleSubmit(onSubmit)}>
        <div className="mb-4  ">
          <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="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="config"
          >
            Config
          </label>
          <textarea
            placeholder="Config"
            {...register("config")}
            className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.config?.message ? "border-red-500" : ""
              }`}
            row={15}
          ></textarea>
          <p className="text-xs italic text-red-500">
            {errors.config?.message}
          </p>
        </div>

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="sow_id"
          >
            Sow
          </label>
          <select
            placeholder="Sow"
            {...register("sow_id")}
            className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.sow_id?.message ? "border-red-500" : ""
              }`}
          >
            {sows.map((sow) => (
              <option key={sow.id} value={sow.id}>
                {sow.name}
              </option>
            ))}
          </select>

          <p className="text-xs italic text-red-500">
            {errors.sow_id?.message}
          </p>
        </div>

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="status"
          >
            Status
          </label>

          <select
            placeholder="Status"
            {...register("status")}
            className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.status?.message ? "border-red-500" : ""
              }`}
          >
            <option value={0}>Pending</option>
            <option value={1}>Complete</option>
          </select>
          <p className="text-xs italic text-red-500">
            {errors.status?.message}
          </p>
        </div>

        <button
          type="submit"
          className="focus:shadow-outline rounded bg-blue-500 px-4 py-2 font-bold text-white hover:bg-blue-700 focus:outline-none"
        >
          Submit
        </button>
      </form>
    </div>
  );
};

export default EditWireframePage;
