import React from "react";
import { useParams } from "react-router";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";

import { PlusIcon } from "@heroicons/react/20/solid";
import { yupResolver } from "@hookform/resolvers/yup";
import moment from "moment";
import { useForm } from "react-hook-form";
import { ClipLoader } from "react-spinners";
import { getSurveyByProjectIdAPI } from "Src/services/projectService";
import {
  getSurveyDetails,
  updateSurveyClientAPI,
} from "Src/services/surveyService";
import MkdSDK from "Utils/MkdSDK";
import { validateUuidv4 } from "Utils/utils";
import * as yup from "yup";

const THEME_OF_THE_ROUTINE_MAX_CHAR = 150;
const BASE_URL = "https://equalityrecords.com/";

const ClientSurveyTab = ({ setShowResendSurveyModal, survey_id }) => {
  const param = useParams();
  let sdk = new MkdSDK();

  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [surveySubmitStatus, setSurveySubmitStatus] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(false);
  const [projectId, setProjectId] = React.useState(null);
  const [submittedIdea, setSubmittedIdea] = React.useState([]);
  const [songlist, setSonglist] = React.useState("");
  const [color, setColor] = React.useState("");

  const [surveyLink, setSurveyLink] = React.useState("");
  const [ideas, setIdeas] = React.useState([
    {
      id: 1,
      value: "",
    },
    {
      id: 2,
      value: "",
    },
    {
      id: 3,
      value: "",
    },
    {
      id: 4,
      value: "",
    },
    {
      id: 5,
      value: "",
    },
  ]);
  const [companyName, setCompanyName] = React.useState("");
  const [themeOfTheRoutine, setThemeOfTheRoutine] = React.useState("");
  const [remainingCharCount, setRemainingCharCount] = React.useState(
    THEME_OF_THE_ROUTINE_MAX_CHAR
  );

  const schema = yup.object().shape({
    idea_1: yup.string().required("Idea 1 is required"),
    idea_2: yup.string().required("Idea 2 is required"),
    idea_3: yup.string().required("Idea 3 is required"),
    idea_4: yup.string().required("Idea 4 is required"),
    idea_5: yup.string().required("Idea 5 is required"),
    songlist: yup.string().required("Songlist is required"),
    color: yup.string().required("Color is required"),
    theme_of_the_routine: yup
      .string()
      .required("Theme of the Routine is required")
      .max(
        THEME_OF_THE_ROUTINE_MAX_CHAR,
        "Theme of the Routine should not be more than THEME_OF_THE_ROUTINE_MAX_CHAR characters"
      ),
  });

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

  const handleAddMoreIdea = () => {
    const newIdea = {
      id: ideas.length + 1,
      value: "",
      dbId: null,
    };
    setIdeas([...ideas, newIdea]);
  };

  //
  //   let ideasLength = Object.keys(ideasData).filter((key) =>
  //     key.includes('idea_')
  //   ).length;
  //   Object.entries(ideasData).forEach(([key, value], index) => {
  //
  //     if (key.startsWith('idea_')) {
  //       setIdeas((prevIdeas) => {
  //         // Check if an idea with the current index already exists in the array
  //         const ideaExists = submittedIdea.find(
  //           (idea) => idea.idea_key === `idea_${index}`
  //         );
  //
  //         if (!ideaExists) {
  //           // If the idea doesn't exist, add it to the array
  //
  //           // return [...prevIdeas, { id: index, value: value, dbId: null }];
  //         } else {
  //           // return [...prevIdeas];
  //           // If the idea exists, update its value
  //           // return prevIdeas.map((idea) =>
  //           //   idea.id === index ? { ...idea, value: value } : idea
  //           // );
  //         }
  //         return [...prevIdeas];
  //       });
  //     }
  //   });
  // };

  // React.useEffect(() => {
  //   const ideasData = watch();
  //   updateIdeasFromForm(ideasData);
  // }, [watch]);

  // const handleUpdateIdeas = () => {
  //
  //   updateIdeasFromForm();
  // };

  const onSubmit = async (_data) => {
    try {
      let ideasLength = Object.keys(_data).filter((key) =>
        key.includes("idea_")
      ).length;

      if (ideasLength < 5) {
        showToast(globalDispatch, "Please add minimum 5 ideas", 5000, "error");
        return;
      }

      let ideas = [];

      for (let i = 1; i <= ideasLength; i++) {
        ideas.push({
          id: i,
          value: _data[`idea_${i}`],
        });
      }
      ideas.forEach((idea) => {
        const match = submittedIdea.find(
          (submittedIde) =>
            parseInt(submittedIde.idea_key.substring("idea_".length)) ===
            idea.id
        );
        if (match) {
          idea.dbId = match.id;
        } else {
          idea.dbId = null;
        }
      });

      ideas = handleSingleQuoteFromIdeas(ideas);

      const payload = {
        status: 1,
        project_id: param?.id,
        theme_of_the_routine: _data.theme_of_the_routine,
        songlist: _data.songlist,
        color: _data.color,
        ideas,
      };

      let today = new Date();

      const payloade = {
        lock_date: moment(
          new Date(today.getTime() - 24 * 60 * 60 * 1000)
        ).format("YYYY-MM-DD"),
      };

      const result = await updateSurveyClientAPI(payload);

      const uri = `/v3/api/custom/equality_record/survey/update/lock_date/${survey_id}`;

      const res = await sdk.callRawAPI(uri, payloade, "PUT");

      if (!result.error) {
        showToast(globalDispatch, "Survey updated successfully", 5000);
        setSurveySubmitStatus(true);
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      setError("name", {
        type: "manual",
        message: error.message,
      });
    }
  };

  const handleThemeOfTheRoutineChange = (e) => {
    if (Number(e.target.value.length) > THEME_OF_THE_ROUTINE_MAX_CHAR) {
      setRemainingCharCount(0);
    } else {
      setRemainingCharCount(
        THEME_OF_THE_ROUTINE_MAX_CHAR - Number(e.target.value.length)
      );
      setThemeOfTheRoutine(e.target.value);
    }
  };

  const handleSingleQuoteFromIdeas = (ideas) => {
    const refinedIdeas = ideas.map((idea) => {
      return {
        id: idea.id,
        value: idea.value.replace(/'/g, "''"),
        dbId: idea.dbId,
      };
    });
    return refinedIdeas;
  };

  const getSurveyByProjectId = async (id) => {
    try {
      const result = await getSurveyByProjectIdAPI(id);

      if (!result.error) {
        setSurveyLink(BASE_URL + "survey/" + result.model.uuidv4);
        console.log(new Date(result.model.lock_date) > new Date());
        if (new Date(result.model.lock_date) > new Date()) {
          setSurveySubmitStatus(false);
        } else if (result.model.status === 1) {
          setSurveySubmitStatus(true);
        } else if (result.model.status !== 1) {
          setSurveySubmitStatus(false);
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  React.useEffect(() => {
    (async function () {
      setIsLoading(true);

      await getSurveyByProjectId(Number(param?.id));
      setIsLoading(false);
      const result = await getSurveyByProjectIdAPI(Number(param?.id));

      if (!result.error) {
        const url = new URL(BASE_URL + "survey/" + result.model.uuidv4);
        const uuidv4 = url.pathname.split("/survey/")[1];
        if (!uuidv4) {
          showToast(globalDispatch, "Invalid URL", 5000, "error");
        } else {
          const checkUuidv4 = validateUuidv4(uuidv4);
          if (!checkUuidv4) {
            showToast(globalDispatch, "Invalid URL", 5000, "error");
          } else {
            (async function () {
              const result = await getSurveyDetails({
                uuidv4,
              });
              if (!result.error) {
                if (result.model.status === 0) {
                  setProjectId(result.model.project_id);
                  setCompanyName(result.model.company_name);
                  if (result.model.ideas.length > 0) {
                    setThemeOfTheRoutine(result.model.theme_of_the_routine);
                    setSonglist(result.model.songlist);
                    setColor(result.model.color);
                    setSubmittedIdea(result.model.ideas);
                    setValue(
                      "theme_of_the_routine",
                      result.model.theme_of_the_routine
                    );
                    setValue("songlist", result.model.songlist);
                    setValue("color", result.model.color);
                    result.model.ideas.forEach((idea, index) => {
                      setIdeas((prev) => {
                        const newIdeas = [...prev];
                        // If the index exceeds the length of newIdeas, push new objects
                        while (index >= newIdeas.length) {
                          newIdeas.push({
                            id: index + 1,
                            value: idea.idea_value,
                          }); // Or initialize with default values
                        }
                        newIdeas[index].value = idea.idea_value.replace(
                          /<br>/g,
                          "\n"
                        );
                        return newIdeas;
                      });
                    });
                  }

                  setIsLoading(false);
                }
                if (new Date(result.model.lock_date) > new Date()) {
                  console.log(new Date(result.model.lock_date) > new Date());
                  setThemeOfTheRoutine(result.model.theme_of_the_routine);
                  setSubmittedIdea(result.model.ideas);
                  setValue(
                    "theme_of_the_routine",
                    result.model.theme_of_the_routine
                  );
                  setSonglist(result.model.songlist);
                  setColor(result.model.color);
                  setSurveySubmitStatus(false);
                  setCompanyName(result.model.company_name);
                  setIsLoading(false);
                } else if (result.model.status === 1) {
                  setThemeOfTheRoutine(result.model.theme_of_the_routine);
                  setValue(
                    "theme_of_the_routine",
                    result.model.theme_of_the_routine
                  );
                  setValue(
                    "theme_of_the_routine",
                    result.model.theme_of_the_routine
                  );
                  setValue("songlist", result.model.songlist);
                  setValue("color", result.model.color);
                  setCompanyName(result.model.company_name);
                  setSubmittedIdea(result.model.ideas);
                  setIsLoading(false);
                  setSurveySubmitStatus(true);
                }
              } else if (result.model.status !== 1) {
                showToast(globalDispatch, result.message, 5000, "error");
                setIsLoading(false);
              }
            })();
          }
        }
      }
    })();
  }, []);

  // React.useEffect(() => {
  //   if (ideas.length > 0) {
  //     setIdeas((prevIdeas) => {
  //       const newIdeas = [...prevIdeas];
  //       ideas.forEach((idea, index) => {
  //         // If the index exceeds the length of newIdeas, push new objects
  //         while (index >= newIdeas.length) {
  //           newIdeas.push({
  //             index,
  //             value: idea.idea_value, // Or initialize with default values
  //           });
  //         }
  //         newIdeas[index] = { id: idea.id, value: idea.idea_value };
  //       });
  //       return newIdeas;
  //     });
  //   }
  // }, [ideas]);

  React.useEffect(() => {
    (async function () {
      setIsLoading(true);

      await getSurveyByProjectId(Number(param?.id));
      setIsLoading(false);
      const result = await getSurveyByProjectIdAPI(Number(param?.id));

      if (!result.error) {
        const url = new URL(BASE_URL + "survey/" + result.model.uuidv4);
        const uuidv4 = url.pathname.split("/survey/")[1];
        if (!uuidv4) {
          showToast(globalDispatch, "Invalid URL", 5000, "error");
        } else {
          const checkUuidv4 = validateUuidv4(uuidv4);
          if (!checkUuidv4) {
            showToast(globalDispatch, "Invalid URL", 5000, "error");
          } else {
            (async function () {
              const result = await getSurveyDetails({
                uuidv4,
              });

              if (!result.error) {
                if (result.model.status === 0) {
                  setProjectId(result.model.project_id);
                  setCompanyName(result.model.company_name);
                  if (result.model.ideas.length > 0) {
                    setSubmittedIdea(result.model.ideas);
                    result.model.ideas.forEach((idea, index) => {
                      setIdeas((prev) => {
                        const newIdeas = [...prev];

                        if (newIdeas[index])
                          newIdeas[index].value = idea.idea_value;
                        return newIdeas;
                      });
                    });
                  }

                  setIsLoading(false);
                } else if (result.model.status === 1) {
                  if (result.model.ideas.length > 0) {
                    setThemeOfTheRoutine(result.model.theme_of_the_routine);
                    setSonglist(result.model.songlist);
                    setColor(result.model.color);
                    result.model.ideas.forEach((idea, index) => {
                      setIdeas((prev) => {
                        const newIdeas = [...prev];
                        // If the index exceeds the length of newIdeas, push new objects
                        while (index >= newIdeas.length) {
                          newIdeas.push({
                            id: index + 1,
                            value: idea.idea_value,
                          }); // Or initialize with default values
                        }
                        newIdeas[index].value = idea.idea_value.replace(
                          /<br>/g,
                          "\n"
                        );
                        return newIdeas;
                      });
                    });
                  }
                  setThemeOfTheRoutine(result.model.theme_of_the_routine);
                  setSubmittedIdea(result.model.ideas);
                  setSonglist(result.model.songlist);
                  setColor(result.model.color);
                  setIsLoading(false);
                }
              } else {
                showToast(globalDispatch, result.message, 5000, "error");
                setIsLoading(false);
              }
            })();
          }
        }
      }
    })();
  }, [surveySubmitStatus]);

  React.useEffect(() => {
    ideas.forEach((idea, index) => {
      setValue(`idea_${index + 1}`, idea.value);
    });
  }, [ideas]);

  const handleSonglistChange = (e) => {
    setSonglist(e.target.value);
  };

  const handleColorChange = (e) => {
    setColor(e.target.value);
  };

  return (
    <div className="mx-auto max-w-screen-2xl">
      {isLoading && (
        <div className="flex justify-center mt-10 w-full">
          <ClipLoader color="white" className="" size={30} />
        </div>
      )}

      {!surveySubmitStatus && !isLoading && (
        <div className="rounded border border-strokedark bg-boxdark">
          {/* Introduction Section */}

          <div className="p-6 border-b border-strokedark">
            <h2 className="text-3xl font-semibold text-white">Survey</h2>
            <h4 className="mb-4 text-xl font-semibold text-white">Hello!</h4>
            <p className="mb-4 text-base font-medium leading-relaxed text-bodydark">
              {companyName} is excited to produce your music this year! As you
              may or may not know, we've already started the creative process
              for your mix, and we want to customize and personalize your
              voiceovers and songs and give you the mix your team deserves. We
              truly want to tell your team's story!
            </p>

            <h5 className="mb-3 text-lg font-medium text-white">
              To help us make this happen for you, will you please submit this
              information:
            </h5>
            <ul className="mb-4 space-y-2 text-base font-medium list-disc list-inside text-bodydark">
              <li>Overall theme/style of your mix?</li>
              <li>
                Any phrases, voice overs ideas and the types of recording
                artists you want in the mix?
              </li>
              <li>Any background or history about your team?</li>
              <li>Do they have a team color?</li>
              <li>
                Any inside jokes, what the team says when they break at the end
                of practice...etc..
              </li>
              <li>New ideas you want us to incorporate</li>
            </ul>

            <p className="text-base font-medium text-bodydark">
              We can't wait to start on your mix and make your routine come to
              life!
            </p>
            <p className="mt-2 text-sm italic text-bodydark">
              *This information is due weeks/months before count sheets and
              videos. If the deadline is missed, we may have to adjust your
              production to a later date.
            </p>
          </div>

          {/* Form Section */}
          <form onSubmit={handleSubmit(onSubmit)} className="p-6">
            <div className="grid grid-cols-1 gap-6">
              {/* Theme Input */}
              <div className="w-full">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Theme of the Routine
                </label>
                <textarea
                  {...register("theme_of_the_routine")}
                  className="p-3 w-full text-white rounded border border-form-strokedark bg-form-input placeholder:text-gray-400 focus:border-primary focus:outline-none"
                  rows={4}
                  onChange={handleThemeOfTheRoutineChange}
                  value={themeOfTheRoutine}
                />
                {errors.theme_of_the_routine && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.theme_of_the_routine.message}
                  </p>
                )}
                <p className="mt-1 text-xs text-bodydark">
                  Remaining Characters:{" "}
                  {remainingCharCount > 0 ? remainingCharCount : 0}
                </p>
              </div>

              {/* Song List Input */}
              <div className="w-full">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Song List
                </label>
                <textarea
                  {...register("songlist")}
                  className="h-[128px] w-full rounded border border-form-strokedark bg-form-input p-3 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                  rows={4}
                  onChange={handleSonglistChange}
                  value={songlist}
                />
                {errors.songlist && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.songlist.message}
                  </p>
                )}
              </div>

              {/* Colors Input */}
              <div className="w-full">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Colors
                </label>
                <textarea
                  {...register("color")}
                  className="h-[128px] w-full rounded border border-form-strokedark bg-form-input p-3 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                  rows={4}
                  onChange={handleColorChange}
                  value={color}
                />
                {errors.color && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.color.message}
                  </p>
                )}
              </div>

              {/* Ideas Section */}
              <div className="w-full">
                <div className="flex justify-between items-center mb-4">
                  <label className="text-sm font-medium text-white">
                    Ideas{" "}
                    <span className="text-xs text-bodydark">
                      (Minimum of 5 ideas required)
                    </span>
                  </label>
                  <button
                    type="button"
                    onClick={handleAddMoreIdea}
                    className="inline-flex gap-2 items-center text-sm font-medium text-primary hover:text-opacity-80"
                  >
                    <PlusIcon className="w-4 h-4" />
                    Add Idea
                  </button>
                </div>

                <div className="space-y-4">
                  {ideas.map((idea, index) => (
                    <div key={index}>
                      <label className="mb-2.5 block text-xs font-medium text-bodydark">
                        Idea #{index + 1}
                      </label>
                      <textarea
                        {...register(`idea_${index + 1}`)}
                        className="h-[128px] w-full rounded border border-form-strokedark bg-form-input p-3 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none"
                        rows={4}
                      />
                      {errors[`idea_${index + 1}`] && (
                        <p className="mt-1 text-xs text-danger">
                          {errors[`idea_${index + 1}`].message}
                        </p>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* Submit Button */}
            <div className="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 Survey
              </button>
            </div>
          </form>
        </div>
      )}

      {surveySubmitStatus && !isLoading && (
        <div className="rounded border border-strokedark bg-boxdark">
          {/* Same structure as above but with readonly fields */}
          <div className="p-6 border-b border-strokedark">
            <h2 className="text-2xl font-semibold text-center text-white">
              Survey
            </h2>
            <div className="p-6">
              <h4 className="mb-4 text-xl font-semibold text-white">Hello!</h4>
              <p className="mb-4 text-base font-medium leading-relaxed text-bodydark">
                {companyName} is excited to produce your music this year! As you
                may or may not know, we've already started the creative process
                for your mix, and we want to customize and personalize your
                voiceovers and songs and give you the mix your team deserves. We
                truly want to tell your team's story!
              </p>

              <h5 className="mb-3 text-lg font-medium text-white">
                To help us make this happen for you, will you please submit this
                information:
              </h5>
              <ul className="mb-4 space-y-2 text-base font-medium list-disc list-inside text-bodydark">
                <li>Overall theme/style of your mix?</li>
                <li>
                  Any phrases, voice overs ideas and the types of recording
                  artists you want in the mix?
                </li>
                <li>Any background or history about your team?</li>
                <li>Do they have a team color?</li>
                <li>
                  Any inside jokes, what the team says when they break at the
                  end of practice...etc..
                </li>
                <li>New ideas you want us to incorporate</li>
              </ul>

              <p className="text-base font-medium text-bodydark">
                We can't wait to start on your mix and make your routine come to
                life!
              </p>
              <p className="mt-2 text-sm italic text-bodydark">
                *This information is due weeks/months before count sheets and
                videos. If the deadline is missed, we may have to adjust your
                production to a later date.
              </p>
            </div>
          </div>

          <div className="p-6">
            <div className="grid grid-cols-1 gap-6">
              {/* Theme Input (readonly) */}
              <div className="w-full">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Theme of the Routine
                </label>
                <div className="h-[128px] w-full rounded border border-form-strokedark bg-form-input p-3 text-white">
                  {themeOfTheRoutine}
                </div>
              </div>

              {/* Song List Input (readonly) */}
              <div className="w-full">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Song List
                </label>
                <div className="h-[128px] w-full rounded border border-form-strokedark bg-form-input p-3 text-white">
                  {songlist}
                </div>
              </div>

              {/* Colors Input (readonly) */}
              <div className="w-full">
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Colors
                </label>
                <div className="h-[128px] w-full rounded border border-form-strokedark bg-form-input p-3 text-white">
                  {color}
                </div>
              </div>

              {/* Ideas Section (readonly) */}
              <div className="w-full">
                <label className="block mb-4 text-sm font-medium text-white">
                  Ideas
                </label>
                <div className="space-y-4">
                  {submittedIdea.map((idea, index) => (
                    <div key={index}>
                      <label className="mb-2.5 block text-xs font-medium text-bodydark">
                        Idea #{index + 1}
                      </label>
                      <div className="h-[128px] w-full rounded border border-form-strokedark bg-form-input p-3 text-white">
                        {idea.idea_value.replace(/<br>/g, "\n")}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ClientSurveyTab;
