import React, { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { useNavigate, useParams } from "react-router-dom";
import { GlobalContext, showToast } from "@/context/Global";
import { AuthContext, tokenExpireError } from "@/context/Auth";
import { isImage, empty, isVideo, isPdf } from "@/utils/utils";
import * as yup from "yup";
import MkdSDK from "@/utils/MkdSDK";
import BaasSDK from "@/utils/BaasSDK";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";

let sdk = new MkdSDK();
let baasSdk = new BaasSDK();

const EditProjectPage = ({ activeId, setSidebar }) => {
  const { dispatch } = React.useContext(AuthContext);
  const schema = yup
    .object({
      name: yup.string(),
      slug: yup.string(),
      secret: yup.string(),
      api_domain: yup.string(),
      api_domain_id: yup.string(),
      frontend_domain: yup.string(),
      frontend_domain_id: yup.string(),
      wireframe_id: yup.string(),
      api_deploy_status: yup.string(),
      frontend_deploy_status: yup.string(),
      configuration: yup.string(),
      validations: yup.string(),
    })
    .required();
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [fileObj, setFileObj] = React.useState({});
  const navigate = useNavigate();

  const [name, setName] = useState("");
  const [slug, setSlug] = useState("");
  const [secret, setSecret] = useState("");
  const [api_domain, setApiDomain] = useState(0);
  const [api_domain_id, setApiDomainId] = useState(0);
  const [frontend_domain, setFrontendDomain] = useState(0);
  const [frontend_domain_id, setFrontendDomainId] = useState(0);
  const [wireframe_id, setWireframeId] = useState(0);
  const [api_deploy_status, setApiDeployStatus] = useState(0);
  const [frontend_deploy_status, setFrontendDeployStatus] = useState(0);
  const [configuration, setConfiguration] = useState("");
  const [validations, setValidations] = 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 {
          baasSdk.setTable("projects");
          const result = await baasSdk.callRestAPI({ id: activeId }, "GET");
          if (!result.error) {
            setValue("name", result.model.name);
            setValue("hostname", result.model.hostname);
            setValue("slug", result.model.slug);
            setValue("secret", result.model.secret);
            setValue("api_domain", result.model.api_domain);
            setValue("api_domain_id", result.model.api_domain_id);
            setValue("frontend_domain", result.model.frontend_domain);
            setValue("frontend_domain_id", result.model.frontend_domain_id);
            setValue("wireframe_id", result.model.wireframe_id);
            setValue("api_deploy_status", result.model.api_deploy_status);
            setValue(
              "frontend_deploy_status",
              result.model.frontend_deploy_status
            );
            setValue("configuration", result.model.configuration);
            setValue("validations", result.model.validations);

            setName(result.model.name);
            setHostname(result.model.hostname);
            setSlug(result.model.slug);
            setSecret(result.model.secret);
            setApiDomain(result.model.api_domain);
            setApiDomainId(result.model.api_domain_id);
            setFrontendDomain(result.model.frontend_domain);
            setFrontendDomainId(result.model.frontend_domain_id);
            setWireframeId(result.model.wireframe_id);
            setApiDeployStatus(result.model.api_deploy_status);
            setFrontendDeployStatus(result.model.frontend_deploy_status);
            setConfiguration(result.model.configuration);
            setValidations(result.model.validations);
            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 {
      baasSdk.setTable("projects");
      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 baasSdk.callRestAPI(
        {
          id: activeId,
          name: _data.name,
          hostname: _data.hostname,
          // slug: _data.slug,
          // secret: _data.secret,
          // api_domain: _data.api_domain,
          // api_domain_id: _data.api_domain_id,
          // frontend_domain: _data.frontend_domain,
          // frontend_domain_id: _data.frontend_domain_id,
          // wireframe_id: _data.wireframe_id,
          // api_deploy_status: _data.api_deploy_status,
          // frontend_deploy_status: _data.frontend_deploy_status,
          // configuration: _data.configuration,
          // validations: _data.validations,
        },
        "PUT"
      );

      if (!result.error) {
        showToast(globalDispatch, "Updated");
        navigate("/admin/project");
      } 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: "project",
      },
    });
  }, []);

  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">Edit Project</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="name"
          >
            Hostname
          </label>
          <input
            placeholder="Hostname"
            {...register("hostname")}
            className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.hostname?.message ? "border-red-500" : ""
              }`}
          />
          <p className="text-xs italic text-red-500">
            {errors.hostname?.message}
          </p>
        </div>

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

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

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="api_domain"
          >
            Api Domain
          </label>
          <input
            type="number"
            placeholder="Api Domain"
            {...register("api_domain")}
            className={` focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none disabled:border-slate-200 disabled:bg-slate-50 disabled:text-slate-500 disabled:shadow-none ${errors.api_domain?.message ? "border-red-500" : ""
              }`}
            disabled
            aria-disabled
          />
          <p className="text-xs italic text-red-500">
            {errors.api_domain?.message}
          </p>
        </div>

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="api_domain_id"
          >
            Api Domain Id
          </label>
          <input
            type="number"
            placeholder="Api Domain Id"
            {...register("api_domain_id")}
            className={` focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none disabled:border-slate-200 disabled:bg-slate-50 disabled:text-slate-500 disabled:shadow-none ${errors.api_domain_id?.message ? "border-red-500" : ""
              }`}
            disabled
            aria-disabled
          />
          <p className="text-xs italic text-red-500">
            {errors.api_domain_id?.message}
          </p>
        </div>

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="frontend_domain"
          >
            Frontend Domain
          </label>
          <input
            type="number"
            placeholder="Frontend Domain"
            {...register("frontend_domain")}
            className={` focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none disabled:border-slate-200 disabled:bg-slate-50 disabled:text-slate-500 disabled:shadow-none ${errors.frontend_domain?.message ? "border-red-500" : ""
              }`}
            disabled
            aria-disabled
          />
          <p className="text-xs italic text-red-500">
            {errors.frontend_domain?.message}
          </p>
        </div>

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="frontend_domain_id"
          >
            Frontend Domain Id
          </label>
          <input
            type="number"
            placeholder="Frontend Domain Id"
            {...register("frontend_domain_id")}
            className={` focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none disabled:border-slate-200 disabled:bg-slate-50 disabled:text-slate-500 disabled:shadow-none ${errors.frontend_domain_id?.message ? "border-red-500" : ""
              }`}
            disabled
            aria-disabled
          />
          <p className="text-xs italic text-red-500">
            {errors.frontend_domain_id?.message}
          </p>
        </div>

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="wireframe_id"
          >
            Wireframe Id
          </label>
          <input
            type="number"
            placeholder="Wireframe Id"
            {...register("wireframe_id")}
            className={` focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none disabled:border-slate-200 disabled:bg-slate-50 disabled:text-slate-500 disabled:shadow-none ${errors.wireframe_id?.message ? "border-red-500" : ""
              }`}
            disabled
            aria-disabled
          />
          <p className="text-xs italic text-red-500">
            {errors.wireframe_id?.message}
          </p>
        </div>

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="api_deploy_status"
          >
            Api Deploy Status
          </label>
          <input
            type="number"
            placeholder="Api Deploy Status"
            {...register("api_deploy_status")}
            className={` focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none disabled:border-slate-200 disabled:bg-slate-50 disabled:text-slate-500 disabled:shadow-none ${errors.api_deploy_status?.message ? "border-red-500" : ""
              }`}
            disabled
            aria-disabled
          />
          <p className="text-xs italic text-red-500">
            {errors.api_deploy_status?.message}
          </p>
        </div>

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="frontend_deploy_status"
          >
            Frontend Deploy Status
          </label>
          <input
            type="number"
            placeholder="Frontend Deploy Status"
            {...register("frontend_deploy_status")}
            className={` focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none disabled:border-slate-200 disabled:bg-slate-50 disabled:text-slate-500 disabled:shadow-none ${errors.frontend_deploy_status?.message ? "border-red-500" : ""
              }`}
            disabled
            aria-disabled
          />
          <p className="text-xs italic text-red-500">
            {errors.frontend_deploy_status?.message}
          </p>
        </div>

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

        <div className="mb-4  ">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="validations"
          >
            Validations
          </label>
          <textarea
            placeholder="Validations"
            {...register("validations")}
            className={`focus:shadow-outline  w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none disabled:border-slate-200 disabled:bg-slate-50 disabled:text-slate-500 disabled:shadow-none ${errors.validations?.message ? "border-red-500" : ""
              }`}
            disabled
            aria-disabled
            row={15}
          ></textarea>
          <p className="text-xs italic text-red-500">
            {errors.validations?.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 EditProjectPage;
