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

const AddMixSeasonPageAdmin = () => {
  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 {
      let filter = {
        role: "member",
      };
      const result = await retrieveAllUserAPI(1, 10000, filter);
      if (!result.error) {
        if (result.list.length > 0) {
          let list = result.list;
          // concat first_name and last_name into user_name
          // then sort by ascending order of user_name
          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="mx-auto rounded p-5 shadow-md">
      <h4 className="mb-4 text-2xl font-medium text-white">Add Mix Season</h4>
      <form className="w-full max-w-lg" onSubmit={handleSubmit(onSubmit)}>
        <div className="mb-4">
          <label
            className="mb-2 block text-sm font-bold text-gray-100"
            htmlFor=""
          >
            Producers
          </label>
          <CustomSelect2
            label="Producers"
            className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-black shadow focus:outline-none`}
            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 className="mb-4">
          <label
            className="mb-2 block text-sm font-bold text-gray-100"
            htmlFor="name"
          >
            Season
          </label>
          <input
            placeholder="Season"
            {...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-100"
            htmlFor="status"
          >
            Status
          </label>
          <CustomSelect2
            register={register}
            name="status"
            label="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.status?.message ? "border-red-500" : ""
            }`}
          >
            <option value="1">Active</option>
            <option value="0">Inactive</option>
          </CustomSelect2>
          <p className="text-xs italic text-red-500">
            {errors.status?.message}
          </p>
        </div>

        <button
          type="submit"
          className="focus:shadow-outline rounded bg-primary px-4 py-2 font-bold text-white hover:bg-primary/90 focus:outline-none"
        >
          Submit
        </button>
        <button
          type="button"
          onClick={() => navigate(-1)}
          className="focus:shadow-outline ml-2 rounded bg-red-500 px-4 py-2 font-bold text-white hover:bg-red-700 focus:outline-none"
        >
          Cancel
        </button>
      </form>
    </div>
  );
};

export default AddMixSeasonPageAdmin;
