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 { GlobalContext, showToast } from "@/context/Global";
import { useNavigate, useParams } from "react-router-dom";
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 EditSowPage = ({ activeId, setSidebar }) => {
  const { dispatch } = React.useContext(AuthContext);
  const schema = yup
    .object({
      name: yup.string(),
      transcripts: yup.string(),
      requirements: yup.string().nullable(),
      breakdown: yup.string().nullable(),
      presentation_code: yup.string().nullable(),
      has_folder: yup.string(),
      development_schedule: yup.string().nullable(),
      status: yup.string(),
    })
    .required();
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [fileObj, setFileObj] = React.useState({});
  const navigate = useNavigate();

  const [name, setName] = useState("");
  const [transcripts, setTranscripts] = useState("");
  const [requirements, setRequirements] = useState("");
  const [breakdown, setBreakdown] = useState("");
  const [presentation_code, setPresentationCode] = useState("");
  const [has_folder, setHasFolder] = useState("");
  const [development_schedule, setDevelopmentSchedule] = useState("");
  const [status, setStatus] = useState("");
  const [id, setId] = useState(0);
  const [isEditing, setIsEditing] = useState(false);

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

  const params = useParams();

  useEffect(
    function () {
      (async function () {
        try {
          sdk.setTable("sow");
          const result = await sdk.callRestAPI({ id: activeId }, "GET");
          if (!result.error) {
            setValue("name", result.model.name);
            setValue("transcripts", result.model.transcripts);
            setValue("requirements", result.model.requirements);
            setValue("breakdown", result.model.breakdown);
            setValue("presentation_code", result.model.presentation_code);
            setValue("has_folder", result.model.has_folder);
            setValue("development_schedule", result.model.development_schedule);
            setValue("status", result.model.status);

            setName(result.model.name);
            setTranscripts(result.model.transcripts);
            setRequirements(result.model.requirements);
            setBreakdown(result.model.breakdown);
            setPresentationCode(result.model.presentation_code);
            setHasFolder(result.model.has_folder);
            setDevelopmentSchedule(result.model.development_schedule);
            setStatus(result.model.status);
            setId(result.model.id);
          }
        } catch (error) {
          console.log("error", error);
          tokenExpireError(dispatch, error.message);
        }
      })();
    },
    [activeId]
  );

  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) => {
    setIsEditing(true);
    try {
      sdk.setTable("sow");
      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: activeId,

          name: _data.name,
          transcripts: _data.transcripts,
          requirements: _data.requirements,
          breakdown: _data.breakdown,
          presentation_code: _data.presentation_code,
          has_folder: _data.has_folder,
          development_schedule: _data.development_schedule,
          status: _data.status,
        },
        "PUT"
      );

      if (!result.error) {
        showToast(globalDispatch, "Updated");
        navigate("/admin/requirements");
      } 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,
      });
    }
    setIsEditing(false);
  };
  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "sow",
      },
    });
  }, []);

  return (
    <div className="relative mx-auto rounded">
      <div
        className={`sticky 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">Edit 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={isEditing}
          >
            {isEditing ? "Saving..." : "Save"}
          </button>
        </div>
      </div>
      <form
        className=" w-full max-w-lg p-4 text-left"
        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="transcripts"
          >
            Transcripts
          </label>
          <textarea
            placeholder="Transcripts"
            {...register("transcripts")}
            className={`focus:shadow-outline h-96 w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.transcripts?.message ? "border-red-500" : ""
              }`}
            row={15}
          ></textarea>
          <p className="text-xs italic text-red-500">
            {errors.transcripts?.message}
          </p>
        </div>

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="requirements"
          >
            Requirements
          </label>
          <textarea
            placeholder="Requirements"
            {...register("requirements")}
            className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none h-96${errors.requirements?.message ? "border-red-500" : ""
              }`}
            row={15}
          ></textarea>
          <p className="text-xs italic text-red-500">
            {errors.requirements?.message}
          </p>
        </div>

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="breakdown"
          >
            Breakdown
          </label>
          <textarea
            placeholder="Breakdown"
            {...register("breakdown")}
            className={`focus:shadow-outline h-96 w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.breakdown?.message ? "border-red-500" : ""
              }`}
            row={15}
          ></textarea>
          <p className="text-xs italic text-red-500">
            {errors.breakdown?.message}
          </p>
        </div>

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="presentation_code"
          >
            Presentation Code
          </label>
          <input
            placeholder="Presentation Code"
            {...register("presentation_code")}
            className={`focus:shadow-outline h-96 w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.presentation_code?.message ? "border-red-500" : ""
              }`}
          />
          <p className="text-xs italic text-red-500">
            {errors.presentation_code?.message}
          </p>
        </div>

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

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

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="development_schedule"
          >
            Development Schedule
          </label>
          <input
            placeholder="Development Schedule"
            {...register("development_schedule")}
            className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.development_schedule?.message ? "border-red-500" : ""
              }`}
          />
          <p className="text-xs italic text-red-500">
            {errors.development_schedule?.message}
          </p>
        </div>

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

          <select
            {...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.has_folder?.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="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
        >
          Submit
        </button> */}
      </form>
    </div>
  );
};

export default EditSowPage;
