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 { GlobalContext, showToast } from "../globalContext";
import { tokenExpireError } from "../authContext";
import { addUserAPI } from "Src/services/userService";
import CustomSelect from "Components/CustomSelect";
import CustomSelect2 from "Components/CustomSelect2";

const selectRole = [
  { name: "role", value: "member" },
  { name: "role", value: "manager" },
];

const AddAdminUserPage = () => {
  const schema = yup.object().shape({
    first_name: yup.string().required("First Name is required"),
    last_name: yup.string().required("Last Name is required"),
    email: yup.string().email().required("Email is required"),
    password: yup.string().required("Password is required"),
    role: yup.string().required("Role is required"),
    company_name: yup.string().required("Company Name is required"),
  });

  const { dispatch } = React.useContext(GlobalContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const navigate = useNavigate();
  const {
    register,
    handleSubmit,
    setError,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const onSubmit = async (data) => {
    try {
      const result = await addUserAPI({
        first_name: data.first_name,
        last_name: data.last_name,
        email: data.email,
        password: data.password,
        role: data.role,
        company_name: data.company_name,
      });
      if (!result.error) {
        showToast(dispatch, "User added successfully", 4000);
        navigate("/admin/users");
      } else {
        showToast(dispatch, result.message, 4000, "error");
      }
    } catch (error) {
      setError("email", {
        type: "manual",
        message: error.message,
      });
      tokenExpireError(dispatch, error.message);
    }
  };

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

  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">
        {/* Header Section */}
        <div className="border-b border-strokedark px-4 py-4 sm:px-6 2xl:px-9">
          <h3 className="text-xl font-medium text-white">Add User</h3>
        </div>

        {/* Form Section */}
        <div className="p-4 md:p-6 2xl:p-10">
          <form onSubmit={handleSubmit(onSubmit)}>
            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
              {/* First Name */}
              <div>
                <label className="mb-2.5 block text-sm font-medium text-white">
                  First Name
                </label>
                <input
                  type="text"
                  placeholder="First Name"
                  {...register("first_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 ${
                    errors.first_name?.message ? "border-danger" : ""
                  }`}
                  autoComplete="off"
                />
                {errors.first_name?.message && (
                  <p className="mt-1 text-sm text-danger">
                    {errors.first_name.message}
                  </p>
                )}
              </div>

              {/* Last Name */}
              <div>
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Last Name
                </label>
                <input
                  type="text"
                  placeholder="Last Name"
                  {...register("last_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 ${
                    errors.last_name?.message ? "border-danger" : ""
                  }`}
                  autoComplete="off"
                />
                {errors.last_name?.message && (
                  <p className="mt-1 text-sm text-danger">
                    {errors.last_name.message}
                  </p>
                )}
              </div>

              {/* Email */}
              <div>
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Email
                </label>
                <input
                  type="email"
                  placeholder="Email"
                  {...register("email")}
                  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 ${
                    errors.email?.message ? "border-danger" : ""
                  }`}
                  autoComplete="off"
                />
                {errors.email?.message && (
                  <p className="mt-1 text-sm text-danger">
                    {errors.email.message}
                  </p>
                )}
              </div>

              {/* Password */}
              <div>
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Password
                </label>
                <input
                  type="password"
                  placeholder="******************"
                  {...register("password")}
                  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 ${
                    errors.password?.message ? "border-danger" : ""
                  }`}
                  autoComplete="off"
                />
                {errors.password?.message && (
                  <p className="mt-1 text-sm text-danger">
                    {errors.password.message}
                  </p>
                )}
              </div>

              {/* Role */}
              <div>
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Role
                </label>
                <CustomSelect2
                  className="h-11 !w-full"
                  label="Select Role"
                  options={selectRole.map((option) => ({
                    value: option.value,
                    label: option.value,
                  }))}
                  register={register}
                  name="role"
                />
              </div>

              {/* Company Name */}
              <div>
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Company Name
                </label>
                <input
                  type="text"
                  placeholder="Company Name"
                  {...register("company_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 ${
                    errors.company_name?.message ? "border-danger" : ""
                  }`}
                  autoComplete="off"
                />
                {errors.company_name?.message && (
                  <p className="mt-1 text-sm text-danger">
                    {errors.company_name.message}
                  </p>
                )}
              </div>
            </div>

            {/* Form Actions */}
            <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-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>
    </div>
  );
};

export default AddAdminUserPage;
