import { yupResolver } from "@hookform/resolvers/yup";
import React from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { getAllMembersForManager } from "Src/services/managerServices";
import { addMixSeasonAPI } from "Src/services/mixSeasonService";
import * as yup from "yup";
import { AuthContext, tokenExpireError } from "../../authContext";
import { GlobalContext, showToast } from "../../globalContext";
import CustomSelect2 from "Components/CustomSelect2";

const AddMixSeasonPageManager = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [members, setMembers] = React.useState([]);
  const [selectedMemberId, setSelectedMemberId] = React.useState("");

  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 retrieveAllUsers = async () => {
    try {
      const result = await getAllMembersForManager(
        localStorage.getItem("user")
      );

      if (!result.error) {
        if (result.list.length > 0) {
          let list = result.list;

          list = list.map((row) => {
            row.user_name = row.first_name + " " + row.last_name;
            return row;
          });
          list = list.sort((a, b) => {
            return a.user_name.localeCompare(b.user_name);
          });

          setMembers(list);
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const onSubmit = async (_data) => {
    try {
      const result = await addMixSeasonAPI({
        name: _data.name,
        status: Number(_data.status),
        user_id: Number(selectedMemberId),
      });
      if (!result.error) {
        showToast(globalDispatch, "Mix Season added Successfully");
        navigate(`/${authState.role}/mix-seasons`);
      } 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);
    }
  };

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

    (async function () {
      await retrieveAllUsers();
    })();
  }, []);

  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-form-strokedark bg-boxdark dark:border-form-strokedark dark:bg-boxdark">
        <div className="sm:px-6.5 border-b border-form-strokedark px-4 py-4 dark:border-form-strokedark">
          <h3 className="text-xl font-medium text-white">Add 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">
            <div>
              <label className="mb-2.5 block font-medium text-white">
                Producers
              </label>
              <CustomSelect2
                label="Producers"
                className="w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-5 py-3 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"
                value={selectedMemberId}
                onChange={(value) => {
                  setSelectedMemberId(value);
                }}
              >
                <option value="">--Select Member--</option>
                {members &&
                  members.length > 0 &&
                  members.map((row, i) => (
                    <option key={i} value={row.id}>
                      {row.user_name}
                    </option>
                  ))}
              </CustomSelect2>
            </div>

            <div>
              <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-form-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>
              <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-form-strokedark bg-form-input px-5 py-3 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"
            >
              Submit
            </button>
            <button
              type="button"
              onClick={() => navigate(-1)}
              className="inline-flex items-center justify-center rounded-md border border-form-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 AddMixSeasonPageManager;
