import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { yupResolver } from "@hookform/resolvers/yup";
import React from "react";
import { useForm } from "react-hook-form";
import { useNavigate, useParams } from "react-router-dom";
import { ClipLoader } from "react-spinners";
import { updateMixTypeAPI } 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 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",
  },
];

let sdk = new MkdSDK();

const EditMixTypePage = () => {
  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"),
  });

  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([]);
  const [id, setId] = React.useState(0);

  // [
  // {
  //   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 params = useParams();

  React.useEffect(function () {
    (async function () {
      try {
        setIsLoading(true);
        sdk.setTable("mix_type");
        const result = await sdk.callRestAPI({ id: Number(params?.id) }, "GET");
        if (!result.error) {
          setValue("name", result.model.name);
          setValue("is_voiceover", result.model.is_voiceover);
          setValue("is_song", result.model.is_song);
          setValue("is_tracking", result.model.is_tracking);
          // setValue('voiceover', result.model.voiceover);
          // setValue('song', result.model.song);
          // setValue('tracking', result.model.tracking);
          setValue("color", result.model.color);
          setValue("price", result.model.price);

          //
          //   'result.model.sub_projects',
          //   JSON.parse(result.model.sub_projects)
          // );

          setSubProjects(JSON.parse(result.model.sub_projects));

          setId(result.model.id);

          // setIsVoiceOverChecked(result.model.is_voiceover === 1 ? true : false);
          // setIsSongChecked(result.model.is_song === 1 ? true : false);
          // setIsTrackingChecked(result.model.is_tracking === 1 ? true : false);
        }
        setIsLoading(false);
      } catch (error) {
        setIsLoading(false);

        tokenExpireError(dispatch, error.message);
      }
    })();
  }, []);

  const onSubmit = async (_data) => {
    // if (isVoiceOverChecked && !_data.voiceover) {
    //   showToast(globalDispatch, 'Voiceover count is required', 4000, 'error');
    //   return;
    // }
    // if (isSongChecked && !_data.song) {
    //   showToast(globalDispatch, 'Song count is required', 4000, 'error');
    //   return;
    // }
    // if (isTrackingChecked && !_data.tracking) {
    //   showToast(globalDispatch, 'Tracking count 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 count cannot be negative or zero',
    //     4000,
    //     'error'
    //   );
    //   return;
    // }

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

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

    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;
    }

    if (Number(_data.price) < 0) {
      showToast(globalDispatch, "Price cannot be negative", 4000, "error");
      return;
    }

    try {
      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 = {
        id: id,
        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 updateMixTypeAPI(payload, "PUT");

      if (!result.error) {
        setIsLoading(false);
        showToast(globalDispatch, "Package updated successfully");
        navigate(`/${authState.role}/mix-types`);
      } else {
        setIsLoading(false);
        showToast(globalDispatch, "Package update failed", 5000, "error");
        return;
      }
    } 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">Edit 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 className="md:col-span-2">
                  <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 className="md:col-span-2">
                  <label className="mb-2.5 block font-medium text-white">
                    Color
                  </label>
                  <CustomSelect2
                    register={register}
                    name="color"
                    label="Color"
                    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.color?.message ? "border-danger" : ""
                    }`}
                  >
                    <option value="">--Select--</option>
                    {COLORS.map((row, index) => (
                      <option
                        key={index}
                        value={row.color}
                        style={{ backgroundColor: row.color }}
                      >
                        {row.name}
                      </option>
                    ))}
                  </CustomSelect2>
                  {errors.color?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.color.message}
                    </p>
                  )}
                </div>

                <div className="md:col-span-2">
                  <div className="flex flex-row justify-between gap-2">
                    <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-x-auto">
                      <table className="w-full table-auto">
                        <thead>
                          <tr className="border-b border-strokedark bg-meta-4 dark:border-strokedark dark:bg-meta-4">
                            <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"
                                    min={1}
                                    defaultValue={row.quantity}
                                    onChange={(e) =>
                                      handleOnChangeQuantity(e, index)
                                    }
                                    className="w-full rounded border-[1.5px] border-strokedark bg-form-input px-5 py-3 font-medium 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"
                                  />
                                </td>
                                <td className="px-4 py-5">
                                  <input
                                    type="number"
                                    min={0}
                                    defaultValue={row.eight_count}
                                    onChange={(e) =>
                                      handleOnChangeEightCount(e, index)
                                    }
                                    className="w-full rounded border-[1.5px] border-strokedark bg-form-input px-5 py-3 font-medium 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"
                                  />
                                </td>
                                <td className="px-4 py-5 text-white dark: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 dark:text-white"
                              >
                                No data found
                              </td>
                            </tr>
                          )}
                        </tbody>
                      </table>
                    </div>
                  </div>
                </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"
                >
                  Update
                </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 EditMixTypePage;
