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 { AuthContext, tokenExpireError } from "../authContext";
import { GlobalContext, showToast } from "../globalContext";
import { isPdf } from "Utils/utils";
import Checkbox from "Components/Checkbox";
import Spinner from "Components/Spinner";

import { addEmployeeAPI } from "Src/services/employeeService";
import { ClipLoader } from "react-spinners";
import { files } from "jszip";

const AddEmployeePage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const schema = yup.object().shape({
    name: yup.string().required("Name is required"),
    email: yup.string().email().required("Email is required"),
    gender: yup.string().required("Gender is required"),
    custom_gender: yup.string().when("gender", {
      is: "custom",
      then: yup.string().required("Please specify the gender"),
    }),
  });

  const [isLoading, setIsLoading] = React.useState(false);
  const [fileObj, setFileObj] = React.useState({});

  const [isWriterChecked, setIsWriterChecked] = React.useState(false);
  const [isArtistChecked, setIsArtistChecked] = React.useState(false);
  const [isEngineerChecked, setIsEngineerChecked] = React.useState(false);
  const [isProducerChecked, setIsProducerChecked] = React.useState(false);

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

  const previewImage = (field, target) => {
    let tempFileObj = fileObj;
    tempFileObj[field] = {
      file: target.files[0],
      tempURL: URL.createObjectURL(target.files[0]),
    };
    setFileObj({ ...tempFileObj });
  };

  const onSubmit = async (_data) => {
    if (
      !isWriterChecked &&
      !isArtistChecked &&
      !isEngineerChecked &&
      !isProducerChecked
    ) {
      showToast(
        globalDispatch,
        "Please select at least one user type",
        5000,
        "warning"
      );
      return;
    }

    if (isWriterChecked && !_data.writer_cost) {
      showToast(globalDispatch, "Please enter writer cost", 5000, "warning");
      return;
    }
    if (isArtistChecked && !_data.artist_cost) {
      showToast(globalDispatch, "Please enter artist cost", 5000, "warning");
      return;
    }
    if (isEngineerChecked && !_data.engineer_cost) {
      showToast(globalDispatch, "Please enter engineer cost", 5000, "warning");
      return;
    }
    if (isProducerChecked && !_data.producer_cost) {
      showToast(globalDispatch, "Please enter producer cost", 5000, "warning");
      return;
    }

    // if (!fileObj.w_nine) {
    //   showToast(globalDispatch, 'Please upload W-9 pdf', 5000, 'warning');
    //   return;
    // }

    let sdk = new MkdSDK();

    try {
      setIsLoading(true);

      for (let item in fileObj) {
        let formData = new FormData();
        formData.append("file", fileObj[item].file);
        let uploadResult = await sdk.uploadImage(formData);
        _data[item] = uploadResult.url;
      }

      if (Object.keys(fileObj).length === 0) {
        _data.w_nine = null;
      }

      const result = await addEmployeeAPI({
        name: _data.name,
        email: _data.email,
        gender: _data.gender === "custom" ? _data.custom_gender : _data.gender,
        is_writer: _data.is_writer,
        writer_cost: _data.writer_cost ? Number(_data.writer_cost) : null,
        is_artist: _data.is_artist,
        artist_cost: _data.artist_cost ? Number(_data.artist_cost) : null,
        is_engineer: _data.is_engineer,
        engineer_cost: _data.engineer_cost ? Number(_data.engineer_cost) : null,
        is_producer: _data.is_producer,
        producer_cost: _data.producer_cost ? Number(_data.producer_cost) : null,
        w_nine: _data.w_nine ?? null,
      });

      if (!result.error) {
        setIsLoading(false);
        showToast(globalDispatch, result.message, 3000);
        navigate(`/${authState.role}/employees`);
      } else {
        setIsLoading(false);
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
    } catch (error) {
      setIsLoading(false);
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleIsWriter = (e) => {
    const { checked } = e.target;
    if (checked) {
      setIsWriterChecked(true);
      setValue("is_writer", 1);
    } else {
      setIsWriterChecked(false);
      setValue("is_writer", 0);
    }
  };

  const handleIsArtist = (e) => {
    const { checked } = e.target;
    if (checked) {
      setIsArtistChecked(true);
      setValue("is_artist", 1);
    } else {
      setIsArtistChecked(false);
      setValue("is_artist", 0);
    }
  };

  const handleIsEngineer = (e) => {
    const { checked } = e.target;
    if (checked) {
      setIsEngineerChecked(true);
      setValue("is_engineer", 1);
    } else {
      setIsEngineerChecked(false);
      setValue("is_engineer", 0);
    }
  };

  const handleIsProducer = (e) => {
    const { checked } = e.target;
    if (checked) {
      setIsProducerChecked(true);
      setValue("is_producer", 1);
    } else {
      setIsProducerChecked(false);
      setValue("is_producer", 0);
    }
  };

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

  return (
    <>
      {isLoading ? (
        <div className="flex justify-center items-center h-screen">
          <ClipLoader color="#fff" size={30} />
        </div>
      ) : (
        <div className="p-4 h-full max-w-screen md:p-4 lg:p-6 xl:p-8">
          <div className="rounded border shadow-default 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">Add Employee</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">
                    Name
                  </label>
                  <input
                    placeholder="Name"
                    {...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>
                  <label className="mb-2.5 block font-medium text-white">
                    Email
                  </label>
                  <input
                    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 dark:focus:border-primary ${
                      errors.email?.message ? "border-danger" : ""
                    }`}
                  />
                  {errors.email?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.email.message}
                    </p>
                  )}
                </div>

                <div className="md:col-span-2">
                  <label className="mb-2.5 block font-medium text-white">
                    Gender
                  </label>
                  <div className="flex flex-col gap-3">
                    <div className="flex flex-wrap gap-4">
                      <div className="flex items-center">
                        <input
                          type="radio"
                          id="male"
                          {...register("gender")}
                          value="male"
                          className="mr-2"
                        />
                        <label htmlFor="male" className="text-white">
                          Male
                        </label>
                      </div>
                      <div className="flex items-center">
                        <input
                          type="radio"
                          id="female"
                          {...register("gender")}
                          value="female"
                          className="mr-2"
                        />
                        <label htmlFor="female" className="text-white">
                          Female
                        </label>
                      </div>
                      <div className="flex items-center">
                        <input
                          type="radio"
                          id="male_queen"
                          {...register("gender")}
                          value="male_queen"
                          className="mr-2"
                        />
                        <label htmlFor="male_queen" className="text-white">
                          Male Queen
                        </label>
                      </div>
                      <div className="flex items-center">
                        <input
                          type="radio"
                          id="custom"
                          {...register("gender")}
                          value="custom"
                          className="mr-2"
                        />
                        <label htmlFor="custom" className="text-white">
                          Custom
                        </label>
                      </div>
                    </div>

                    {watch("gender") === "custom" && (
                      <input
                        type="text"
                        placeholder="Specify Gender"
                        {...register("custom_gender")}
                        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.custom_gender?.message ? "border-danger" : ""
                        }`}
                      />
                    )}
                  </div>
                  {errors.gender?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.gender.message}
                    </p>
                  )}
                  {errors.custom_gender?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.custom_gender.message}
                    </p>
                  )}
                </div>

                <div className="flex flex-col gap-2">
                  <div className="flex gap-2 items-center">
                    <Checkbox
                      id="is_writer"
                      type="checkbox"
                      name="is_writer"
                      handleClick={handleIsWriter}
                      isChecked={isWriterChecked}
                    />
                    <label
                      htmlFor="is_writer"
                      className="font-medium text-white"
                    >
                      Writer
                    </label>
                  </div>
                  {isWriterChecked && (
                    <div className="flex flex-col gap-2">
                      <div>
                        <input
                          type="text"
                          placeholder="Writer Cost"
                          {...register("writer_cost")}
                          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.writer_cost?.message ? "border-danger" : ""
                          }`}
                        />
                        {errors.writer_cost?.message && (
                          <p className="mt-1 text-sm text-danger">
                            {errors.writer_cost.message}
                          </p>
                        )}
                      </div>
                    </div>
                  )}
                </div>

                <div className="flex flex-col gap-2">
                  <div className="flex gap-2 items-center">
                    <Checkbox
                      id="is_artist"
                      type="checkbox"
                      name="is_artist"
                      handleClick={handleIsArtist}
                      isChecked={isArtistChecked}
                    />
                    <label
                      htmlFor="is_artist"
                      className="font-medium text-white"
                    >
                      Artist
                    </label>
                  </div>
                  {isArtistChecked && (
                    <div className="flex flex-col gap-2">
                      <div>
                        <input
                          type="text"
                          placeholder="Artist Cost"
                          {...register("artist_cost")}
                          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.artist_cost?.message ? "border-danger" : ""
                          }`}
                        />
                        {errors.artist_cost?.message && (
                          <p className="mt-1 text-sm text-danger">
                            {errors.artist_cost.message}
                          </p>
                        )}
                      </div>
                    </div>
                  )}
                </div>

                <div className="flex flex-col gap-2">
                  <div className="flex gap-2 items-center">
                    <Checkbox
                      id="is_engineer"
                      type="checkbox"
                      name="is_engineer"
                      handleClick={handleIsEngineer}
                      isChecked={isEngineerChecked}
                    />
                    <label
                      htmlFor="is_engineer"
                      className="font-medium text-white"
                    >
                      Engineer
                    </label>
                  </div>
                  {isEngineerChecked && (
                    <div className="flex flex-col gap-2">
                      <div>
                        <input
                          type="text"
                          placeholder="Engineer Cost"
                          {...register("engineer_cost")}
                          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.engineer_cost?.message ? "border-danger" : ""
                          }`}
                        />
                        {errors.engineer_cost?.message && (
                          <p className="mt-1 text-sm text-danger">
                            {errors.engineer_cost.message}
                          </p>
                        )}
                      </div>
                    </div>
                  )}
                </div>

                <div className="flex flex-col gap-2">
                  <div className="flex gap-2 items-center">
                    <Checkbox
                      id="is_producer"
                      type="checkbox"
                      name="is_producer"
                      handleClick={handleIsProducer}
                      isChecked={isProducerChecked}
                    />
                    <label
                      htmlFor="is_producer"
                      className="font-medium text-white"
                    >
                      Producer
                    </label>
                  </div>
                  {isProducerChecked && (
                    <div className="flex flex-col gap-2">
                      <div>
                        <input
                          type="text"
                          placeholder="Producer Cost"
                          {...register("producer_cost")}
                          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.producer_cost?.message ? "border-danger" : ""
                          }`}
                        />
                        {errors.producer_cost?.message && (
                          <p className="mt-1 text-sm text-danger">
                            {errors.producer_cost.message}
                          </p>
                        )}
                      </div>
                    </div>
                  )}
                </div>

                <div className="md:col-span-2">
                  <label className="mb-2.5 block font-medium text-white">
                    W-9
                  </label>
                  {fileObj["w_nine"] && isPdf(fileObj["w_nine"]) && (
                    <embed
                      src={fileObj["w_nine"]["tempURL"]}
                      type="application/pdf"
                      className="mb-3 w-full h-48"
                    />
                  )}
                  <label
                    className="mb-2.5 inline-block cursor-pointer font-medium text-primary hover:text-opacity-80"
                    htmlFor="w_nine"
                  >
                    Upload PDF
                    <input
                      id="w_nine"
                      type="file"
                      accept="application/pdf"
                      {...register("w_nine", {
                        onChange: (e) => previewImage("w_nine", e.target),
                      })}
                      className="hidden"
                    />
                  </label>
                  {errors.w_nine?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.w_nine.message}
                    </p>
                  )}
                </div>
              </div>

              <div className="flex gap-4 items-center mt-6">
                <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>
      )}
    </>
  );
};

export default AddEmployeePage;
