import { yupResolver } from "@hookform/resolvers/yup";
import React, { useEffect } from "react";
import { useForm } from "react-hook-form";
import { useNavigate, useParams } from "react-router-dom";
import { updateMixSeasonAPI } from "Src/services/mixSeasonService";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import * as yup from "yup";
import { AuthContext, tokenExpireError } from "../authContext";
import { GlobalContext, showToast } from "../globalContext";
import MkdSDK from "../utils/MkdSDK";
import CustomSelect2 from "Components/CustomSelect2";

let sdk = new MkdSDK();

const EditMixSeasonPage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [user, setUser] = React.useState("");
  const [userId, setUserId] = React.useState(null);

  const schema = yup.object().shape({
    name: yup.string().required("Season is required"),
    status: yup.string().required("Status is required"),
  });

  const navigate = useNavigate();

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

  const params = useParams();

  useEffect(function () {
    (async function () {
      try {
        sdk.setTable("mix_season");
        const result = await sdk.callRestAPI({ id: Number(params?.id) }, "GET");
        if (!result.error) {
          setValue("name", result.model.name);
          setValue("status", result.model.status);
          setUserId(result.model.user_id);
        }
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, []);

  const onSubmit = async (_data) => {
    try {
      sdk.setTable("mix_season");
      const result = await updateMixSeasonAPI({
        id: Number(params?.id),
        name: _data.name,
        status: Number(_data.status),
      });

      if (!result.error) {
        showToast(globalDispatch, "Mix Season updated Successfully");
        navigate(`/${authState.role}/mix-seasons`);
      } else {
        showToast(globalDispatch, "Mix Season update failed", 5000, "error");
        return;
      }
    } catch (error) {
      setError("name", {
        type: "manual",
        message: error.message,
      });
    }
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "mix-seasons",
      },
    });
  }, []);

  React.useEffect(() => {
    if (userId) {
      (async function () {
        try {
          const result = await getUserDetailsByIdAPI(userId);

          if (!result?.error) {
            setUser(result.model.first_name + " " + result.model.last_name);
          }
        } catch (error) {}
      })();
    }
  }, [userId]);

  return (
    <div className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8">
      <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
        <div className="sm:px-6.5 border-b border-strokedark px-4 py-4 dark:border-strokedark">
          <h3 className="text-xl font-medium text-white">Edit Mix Season</h3>
        </div>

        <form className="p-4 md:p-6 2xl:p-10" onSubmit={handleSubmit(onSubmit)}>
          <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
            {(authState?.role === "admin" || authState?.role === "manager") && (
              <div className="md:col-span-2">
                <label className="mb-2.5 block font-medium text-white">
                  Producer
                </label>
                <input
                  placeholder="Member"
                  value={user}
                  readOnly
                  className="w-full rounded border-[1.5px] border-strokedark bg-form-input px-5 py-3 font-medium text-white outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary"
                />
              </div>
            )}

            <div className="md:col-span-2">
              <label className="mb-2.5 block font-medium text-white">
                Season
              </label>
              <input
                placeholder="Season"
                {...register("name")}
                className={`w-full rounded border-[1.5px] border-strokedark bg-form-input px-5 py-3 font-medium text-white outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary ${
                  errors.name?.message ? "border-danger" : ""
                }`}
              />
              {errors.name?.message && (
                <p className="mt-1 text-sm text-danger">
                  {errors.name.message}
                </p>
              )}
            </div>

            <div className="md:col-span-2">
              <label className="mb-2.5 block font-medium text-white">
                Status
              </label>
              <CustomSelect2
                label="Status"
                register={register}
                name="status"
                className={`w-full rounded border-[1.5px] border-strokedark bg-form-input px-5 py-3 font-medium text-white outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary ${
                  errors.status?.message ? "border-danger" : ""
                }`}
              >
                <option value="1">Active</option>
                <option value="0">Inactive</option>
              </CustomSelect2>
              {errors.status?.message && (
                <p className="mt-1 text-sm text-danger">
                  {errors.status.message}
                </p>
              )}
            </div>
          </div>

          <div className="mt-6 flex items-center gap-4">
            <button
              type="submit"
              className="inline-flex items-center justify-center rounded-md bg-primary px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
            >
              Update
            </button>
            <button
              type="button"
              onClick={() => navigate(-1)}
              className="inline-flex items-center justify-center rounded-md border border-strokedark bg-meta-7 px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
            >
              Cancel
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default EditMixSeasonPage;
