import { yupResolver } from "@hookform/resolvers/yup";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  getSurveyDetails,
  updateSurveyClientAPI,
} from "Src/services/surveyService";
import React from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import * as yup from "yup";

import { PlusIcon } from "@heroicons/react/20/solid";
import { validateUuidv4 } from "Utils/utils";
import moment from "moment";
import { ClipLoader } from "react-spinners";

const THEME_OF_THE_ROUTINE_MAX_CHAR = 150;

const SurveyPage = () => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [isLoading, setIsLoading] = React.useState(false);

  const [songlist, setSonglist] = React.useState("");
  const [color, setColor] = React.useState("");
  const [projectId, setProjectId] = React.useState(null);
  const [submittedIdea, setSubmittedIdea] = 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 [teamName, setTeamName] = React.useState("");
  const [programName, setProgramName] = React.useState("");
  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 navigate = useNavigate();

  const handleAddMoreIdea = () => {
    try {
      // Get the actual current values from the form
      const currentValues = ideas.map((idea, index) => ({
        id: idea.id,
        value: document.querySelector(`.idea_${index + 1}`).value || "",
      }));

      // Create new idea object
      const newIdea = {
        id: currentValues.length + 1,
        value: "",
      };

      // Update with current values plus new idea
      const updatedIdeas = [...currentValues, newIdea];

      // Update state and form
      setIdeas(updatedIdeas);

      // Register the new field
      setValue(`idea_${updatedIdeas.length}`, "");
    } catch (error) {
      console.error("Error adding new idea:", error);
      showToast(globalDispatch, "Error adding new idea", 4000, "error");
    }
  };

  console.log(submittedIdea);

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

      console.log(ideas);

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

      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 submitted successfully", 5000);
        navigate("/");
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      setError("name", {
        type: "manual",
        message: error.message,
      });
    }
  };

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

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

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

  React.useEffect(() => {
    setIsLoading(true);
    const url = new URL(window.location.href);
    const uuidv4 = url.pathname.split("/survey/")[1];

    if (!uuidv4) {
      showToast(globalDispatch, "Invalid URL", 5000, "error");
      navigate("/");
    } else {
      const checkUuidv4 = validateUuidv4(uuidv4);
      if (!checkUuidv4) {
        showToast(globalDispatch, "Invalid URL", 5000, "error");
        navigate("/");
      } else {
        (async function () {
          const result = await getSurveyDetails({
            uuidv4,
          });
          if (!result.error) {
            console.log(result.model);
            if (
              result.model.status === 0 ||
              new Date(result.model.lock_date) > new Date()
            ) {
              setIsLoading(false);
              setSubmittedIdea(result.model.ideas);
              setProjectId(result.model.project_id);
              setCompanyName(result.model.company_name);
              setTeamName(result.model.team_name);
              setProgramName(result.model.program_name);
              if (result.model.ideas.length > 0) {
                console.log(result.model.ideas);
                setSubmittedIdea(result.model.ideas);
                setThemeOfTheRoutine(result.model.theme_of_the_routine);
                setSonglist(result.model.songlist);
                setColor(result.model.color);
                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);
            } else if (result.model.status === 1) {
              setIsLoading(false);
              showToast(
                globalDispatch,
                "Survey already submitted for this project",
                5000,
                "error"
              );
              navigate("/");
            }
          } else {
            showToast(globalDispatch, result.message, 5000, "error");
            setIsLoading(false);
            navigate("/");
          }
        })();
      }
    }
  }, []);

  console.log(ideas);

  React.useEffect(() => {
    const syncFormValues = () => {
      ideas.forEach((idea, index) => {
        const textarea = document.querySelector(`.idea_${index + 1}`);
        if (textarea && textarea.value) {
          setIdeas((prev) =>
            prev.map((prevIdea) =>
              prevIdea.id === idea.id
                ? { ...prevIdea, value: textarea.value }
                : prevIdea
            )
          );
        }
      });
    };

    // Sync on mount and when ideas change
    syncFormValues();
  }, []);

  console.log(themeOfTheRoutine);
  return (
    <>
      {isLoading ? (
        <div className="flex justify-center items-center h-screen bg-boxdark">
          <div className="flex h-[calc(100vh)] w-full items-center justify-center">
            <ClipLoader color="#fff" size={30} />
          </div>
        </div>
      ) : (
        <div className="p-4 mx-auto max-w-screen md:p-6 2xl:p-10">
          {/* Header */}
          <div className="flex flex-col justify-center items-center mb-6 w-full">
            <h2 className="text-3xl font-semibold text-white">
              {programName} - {teamName}
            </h2>
            <p className="mt-1 text-lg font-medium text-bodydark">
              Music Survey
            </p>
          </div>

          {/* Main Content */}
          <div className="rounded border border-strokedark bg-boxdark">
            {/* Introduction Section */}
            <div className="p-6 border-b border-strokedark">
              <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 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 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="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={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="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={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>
                  </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}`)}
                          defaultValue={idea.value}
                          onChange={(e) => {
                            const newValue = e.target.value;
                            setIdeas((prev) =>
                              prev.map((prevIdea) =>
                                prevIdea.id === idea.id
                                  ? { ...prevIdea, value: newValue }
                                  : prevIdea
                              )
                            );
                          }}
                          className={`w-full rounded border border-form-strokedark bg-form-input p-3 text-white placeholder:text-gray-400 focus:border-primary focus:outline-none idea_${
                            index + 1
                          }`}
                          rows={4}
                        />
                        {errors[`idea_${index + 1}`] && (
                          <p className="mt-1 text-xs text-danger">
                            {errors[`idea_${index + 1}`].message}
                          </p>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              </div>
              <div className="flex justify-end mt-3">
                <button
                  type="button"
                  onClick={handleAddMoreIdea}
                  className="inline-flex gap-2 items-center px-4 py-3 text-sm font-medium text-white bg-primary hover:text-opacity-80"
                >
                  <PlusIcon className="w-4 h-4" />
                  Add Idea
                </button>
              </div>
              <button
                type="submit"
                className="p-3 mt-6 w-full font-medium text-white rounded-md bg-primary"
              >
                Submit
              </button>
            </form>
          </div>
        </div>
      )}
    </>
  );
};

export default SurveyPage;
