import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { yupResolver } from "@hookform/resolvers/yup";
import React from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { ClipLoader } from "react-spinners";
import { addMixTypeAPI } from "Src/services/mixTypeServices";
import * as yup from "yup";
import { AuthContext, tokenExpireError } from "../authContext";
import { GlobalContext, showToast } from "../globalContext";
import MkdSDK from "../utils/MkdSDK";
import CustomSelect from "Components/CustomSelect";
import CustomSelect2 from "Components/CustomSelect2";

const COLORS = [
  {
    id: 1,
    color: "#6CC551",
    name: "Green",
  },
  {
    id: 2,
    color: "#197BBD",
    name: "Blue",
  },
  {
    id: 3,
    color: "#F3A738",
    name: "Gold",
  },
  {
    id: 4,
    color: "#C0C0C0",
    name: "Gray",
  },
  {
    id: 5,
    color: "#8A2BE2",
    name: "Purple",
  },
  {
    id: 6,
    color: "#FF91AF",
    name: "Pink",
  },
  {
    id: 7,
    color: "#00FFFF",
    name: "Cyan",
  },
  {
    id: 8,
    color: "#B31B1B",
    name: "Red",
  },
  {
    id: 9,
    color: "#FF7F50",
    name: "Coral",
  },
];

const AddMixTypePage = () => {
  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"),
    color: yup.string().required("Color is required"),
    price: yup.string().required("Price is required"),
    // sub_projects: yup.string().required('Sub-projects are required'),
  });

  const [isLoading, setIsLoading] = React.useState(false);
  const [isVoiceOverChecked, setIsVoiceOverChecked] = React.useState(false);
  const [isSongChecked, setIsSongChecked] = React.useState(false);
  const [isTrackingChecked, setIsTrackingChecked] = React.useState(false);
  const [subProjects, setSubProjects] = React.useState([]);
  // [
  // {
  //   type: 'voiceover',
  //   eight_count: 0,
  //   quantity: 0,
  // },
  // {
  //   type: 'song',
  //   eight_count: 0,
  //   quantity: 0,
  // },
  // {
  //   type: 'tracking',
  //   eight_count: 0,
  //   quantity: 0,
  // },
  // ];

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

  const onSubmit = async (_data) => {
    // if (isVoiceOverChecked && !_data.voiceover) {
    //   showToast(globalDispatch, 'Voiceover value is required', 4000, 'error');
    //   return;
    // }
    // if (isSongChecked && !_data.song) {
    //   showToast(globalDispatch, 'Song value is required', 4000, 'error');
    //   return;
    // }
    // if (isTrackingChecked && !_data.tracking) {
    //   showToast(globalDispatch, 'Tracking value is required', 4000, 'error');
    //   return;
    // }

    // if (!isVoiceOverChecked && !isSongChecked) {
    //   showToast(
    //     globalDispatch,
    //     'At least one of voiceover or song should be checked',
    //     4000,
    //     'error'
    //   );
    //   return;
    // }

    // if (isVoiceOverChecked && Number(_data.voiceover) <= 0) {
    //   showToast(
    //     globalDispatch,
    //     'Voiceover value cannot be negative or zero',
    //     4000,
    //     'error'
    //   );
    //   return;
    // }

    // if (isSongChecked && Number(_data.song) <= 0) {
    //   showToast(
    //     globalDispatch,
    //     'Song value cannot be negative or zero',
    //     4000,
    //     'error'
    //   );
    //   return;
    // }

    // if (isTrackingChecked && Number(_data.tracking) <= 0) {
    //   showToast(
    //     globalDispatch,
    //     'Tracking value cannot be negative or zero',
    //     4000,
    //     'error'
    //   );
    //   return;
    // }

    // check if subprojects are added
    if (subProjects.length === 0) {
      showToast(
        globalDispatch,
        "At least one sub-project is required",
        4000,
        "error"
      );
      setError("sub_projects", {
        type: "manual",
        message: "At least one sub-project is required",
      });
      setIsLoading(false);
      return;
    }

    let sdk = new MkdSDK();

    try {
      setIsLoading(true);
      sdk.setTable("mix_type");

      // make sure voiceover, song and tracking have at least 1 quantity if they are present
      let voiceOvers = subProjects.filter((row) => row.type === "voiceover");
      let songs = subProjects.filter((row) => row.type === "song");
      let trackings = subProjects.filter((row) => row.type === "tracking");

      if (voiceOvers.length > 0) {
        let voiceOverQuantity = voiceOvers.reduce(
          (acc, row) => acc + row.quantity,
          0
        );
        if (voiceOverQuantity === 0) {
          showToast(
            globalDispatch,
            "Voiceover quantity cannot be zero",
            4000,
            "error"
          );
          setIsLoading(false);
          return;
        }
      }

      if (songs.length > 0) {
        let songQuantity = songs.reduce((acc, row) => acc + row.quantity, 0);
        if (songQuantity === 0) {
          showToast(
            globalDispatch,
            "Song quantity cannot be zero",
            4000,
            "error"
          );
          setIsLoading(false);
          return;
        }
      }

      if (trackings.length > 0) {
        let trackingQuantity = trackings.reduce(
          (acc, row) => acc + row.quantity,
          0
        );
        if (trackingQuantity === 0) {
          showToast(
            globalDispatch,
            "Tracking quantity cannot be zero",
            4000,
            "error"
          );
          setIsLoading(false);
          return;
        }
      }

      let localSubProjects = [];
      if (voiceOvers.length > 0) {
        localSubProjects = localSubProjects.concat(voiceOvers);
      }
      if (songs.length > 0) {
        localSubProjects = localSubProjects.concat(songs);
      }
      if (trackings.length > 0) {
        localSubProjects = localSubProjects.concat(trackings);
      }

      const payload = {
        name: _data.name,
        // is_voiceover: isVoiceOverChecked ? 1 : 0,
        // voiceover: !isVoiceOverChecked ? 0 : Number(_data.voiceover),
        // is_song: isSongChecked ? 1 : 0,
        // song: !isSongChecked ? 0 : Number(_data.song),
        // is_tracking: isTrackingChecked ? 1 : 0,
        // tracking: !isTrackingChecked ? 0 : Number(_data.tracking),
        color: _data.color,
        price: Number(_data.price),
        sub_projects: JSON.stringify(localSubProjects),
      };

      const result = await addMixTypeAPI(payload, "POST");
      if (!result.error) {
        setIsLoading(false);
        showToast(globalDispatch, "Package added successfully");
        navigate(`/${authState.role}/mix-types`);
      } else {
        setIsLoading(false);
        showToast(globalDispatch, result.message, 4000, "error");
      }
    } catch (error) {
      setIsLoading(false);
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleIsVoiceOver = (e) => {
    const { checked } = e.target;
    if (checked) {
      setIsVoiceOverChecked(true);
      setValue("is_voiceover", 1);
    } else {
      setIsVoiceOverChecked(false);
      setValue("is_voiceover", 0);
    }
  };

  const handleIsSong = (e) => {
    const { checked } = e.target;
    if (checked) {
      setIsSongChecked(true);
      setValue("is_song", 1);
    } else {
      setIsSongChecked(false);
      setValue("is_song", 0);
    }
  };

  const handleIsTracking = (e) => {
    const { checked } = e.target;
    if (checked) {
      setIsTrackingChecked(true);
      setValue("is_tracking", 1);
    } else {
      setIsTrackingChecked(false);
      setValue("is_tracking", 0);
    }
  };

  const handleOnClickAddVoiceover = () => {
    // onClick add voiceover will add a row to additional info

    setSubProjects([
      ...subProjects,
      {
        type: "voiceover",
        eight_count: 0,
        quantity: 1,
      },
    ]);
  };

  const handleOnClickAddSong = () => {
    // onClick add song will add a row to additional info

    setSubProjects([
      ...subProjects,
      {
        type: "song",
        eight_count: 0,
        quantity: 1,
      },
    ]);
  };

  const handleOnClickAddTracking = () => {
    // onClick add tracking will add a row to additional info

    setSubProjects([
      ...subProjects,
      {
        type: "tracking",
        eight_count: 0,
        quantity: 1,
      },
    ]);
  };

  const handleDeleteSubProject = (index) => {
    // onClick delete will remove the row from additional info
    const newAdditionalInfo = subProjects.filter((_, i) => i !== index);
    setSubProjects(newAdditionalInfo);
  };

  const handleOnChangeQuantity = (e, index) => {
    const { value } = e.target;
    const newSubProjects = subProjects.map((row, i) => {
      if (i === index) {
        return {
          ...row,
          quantity: Number(value),
        };
      }
      return row;
    });
    setSubProjects(newSubProjects);
  };

  const handleOnChangeEightCount = (e, index) => {
    const { value } = e.target;
    const newSubProjects = subProjects.map((row, i) => {
      if (i === index) {
        return {
          ...row,
          eight_count: Number(value),
        };
      }
      return row;
    });
    setSubProjects(newSubProjects);
  };

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

  return (
    <>
      {isLoading ? (
        <div className="flex h-screen items-center justify-center">
          <ClipLoader color="#fff" size={30} />
        </div>
      ) : (
        <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">Add Mix Type</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-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">
                    Color
                  </label>
                  <CustomSelect2
                    className="h-11 !w-full"
                    label="Select Color"
                    options={COLORS.map((row) => ({
                      value: row.color,
                      label: row.name,
                    }))}
                    register={register}
                    name="color"
                  />
                </div>

                {errors.color?.message && (
                  <p className="mt-1 text-sm text-danger">
                    {errors.color.message}
                  </p>
                )}

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

              <div className="mt-6">
                <label className="mb-2.5 block font-medium text-white">
                  Sub-projects
                </label>
                <div className="flex flex-wrap gap-3">
                  <button
                    type="button"
                    onClick={handleOnClickAddVoiceover}
                    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"
                  >
                    <FontAwesomeIcon icon="plus" className="mr-2" />
                    Add Voiceover
                  </button>
                  <button
                    type="button"
                    onClick={handleOnClickAddSong}
                    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"
                  >
                    <FontAwesomeIcon icon="plus" className="mr-2" />
                    Add Song
                  </button>
                  <button
                    type="button"
                    onClick={handleOnClickAddTracking}
                    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"
                  >
                    <FontAwesomeIcon icon="plus" className="mr-2" />
                    Add Tracking
                  </button>
                </div>

                <div className="shadow-default mt-4 rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
                  <div className="max-h-96 overflow-auto">
                    <table className="w-full table-auto">
                      <thead className="sticky top-0 bg-meta-4">
                        <tr className="border-b border-strokedark dark:border-strokedark">
                          <th className="px-4 py-4 font-medium text-white dark:text-white">
                            Quantity
                          </th>
                          <th className="px-4 py-4 font-medium text-white dark:text-white">
                            # of 8 counts
                          </th>
                          <th className="px-4 py-4 font-medium text-white dark:text-white">
                            Type
                          </th>
                          <th className="px-4 py-4 font-medium text-white dark:text-white">
                            Actions
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        {subProjects.length > 0 ? (
                          subProjects.map((row, index) => (
                            <tr
                              key={index}
                              className="border-b border-strokedark dark:border-strokedark"
                            >
                              <td className="px-4 py-5">
                                <input
                                  type="number"
                                  placeholder="Quantity"
                                  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"
                                  min={1}
                                  defaultValue={1}
                                  onChange={(e) =>
                                    handleOnChangeQuantity(e, index)
                                  }
                                />
                              </td>
                              <td className="px-4 py-5">
                                <input
                                  type="number"
                                  placeholder="# of 8 counts"
                                  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"
                                  min={0}
                                  defaultValue={0}
                                  onChange={(e) =>
                                    handleOnChangeEightCount(e, index)
                                  }
                                />
                              </td>
                              <td className="px-4 py-5 text-white">
                                {row.type}
                              </td>
                              <td className="px-4 py-5">
                                <button
                                  onClick={() => handleDeleteSubProject(index)}
                                  className="hover:text-danger"
                                >
                                  <FontAwesomeIcon icon="trash" />
                                </button>
                              </td>
                            </tr>
                          ))
                        ) : (
                          <tr>
                            <td
                              colSpan="4"
                              className="px-4 py-5 text-center text-white"
                            >
                              No data found
                            </td>
                          </tr>
                        )}
                      </tbody>
                    </table>
                  </div>
                </div>
                {errors.sub_projects?.message && (
                  <p className="mt-1 text-sm text-danger">
                    {errors.sub_projects.message}
                  </p>
                )}
              </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-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 AddMixTypePage;
