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 AddProjectPage = ({ setSidebar }) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  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 } = React.useContext(GlobalContext);
  const [isUpdating, setIsUpdating] = React.useState(false);

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

  const onSubmit = async (_data) => {
    let sdk = new MkdSDK();
    setIsUpdating(true);
    try {
      sdk.setTable("project");

      const result = await sdk.callRestAPI(
        {
          name: _data.name,
          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,
        },
        "POST"
      );
      if (!result.error) {
        showToast(globalDispatch, "Added");
        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) {
      setError("name", {
        type: "manual",
        message: error.message,
      });
      tokenExpireError(dispatch, error.message);
    }
    setIsUpdating(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">Add 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={isUpdating}
          >
            {isUpdating ? "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="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 ${
              errors.slug?.message ? "border-red-500" : ""
            }`}
          />
          <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 ${
              errors.secret?.message ? "border-red-500" : ""
            }`}
          />
          <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 ${
              errors.api_domain?.message ? "border-red-500" : ""
            }`}
          />
          <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 ${
              errors.api_domain_id?.message ? "border-red-500" : ""
            }`}
          />
          <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 ${
              errors.frontend_domain?.message ? "border-red-500" : ""
            }`}
          />
          <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 ${
              errors.frontend_domain_id?.message ? "border-red-500" : ""
            }`}
          />
          <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 ${
              errors.wireframe_id?.message ? "border-red-500" : ""
            }`}
          />
          <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 ${
              errors.api_deploy_status?.message ? "border-red-500" : ""
            }`}
          />
          <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 ${
              errors.frontend_deploy_status?.message ? "border-red-500" : ""
            }`}
          />
          <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 ${
              errors.configuration?.message ? "border-red-500" : ""
            }`}
            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 ${
              errors.validations?.message ? "border-red-500" : ""
            }`}
            row={15}
          ></textarea>
          <p className="text-xs italic text-red-500">
            {errors.validations?.message}
          </p>
        </div>
      </form>
    </div>
  );
};

export default AddProjectPage;
