import ClientEightCountTab from "Components/Client/ClientViewProjectDetails/ClientEightCountTab";
import VideoSection from "Components/Client/ClientViewProjectDetails/VideoSection";
import MusicSection from "Components/Client/musicSection";
import ConfirmModal from "Components/Modal/ConfirmModal";
import DuoConfirmModal from "Components/Modal/DuoConfirmModal";
import moment from "moment";
import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  UpdateEditAPI,
  getAllEditAPI,
  viewEditDetails,
} from "Src/services/editService";
import { sendEmailAPIV3 } from "Src/services/emailService";
import {
  getProjectDetailsAPI,
  getSurveyByProjectIdAPI,
  updateProjectAPI,
} from "Src/services/projectService";
import { getSurveyDetails } from "Src/services/surveyService";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import { removeKeysWhenValueIsNull, validateUuidv4 } from "Utils/utils";

const MemberEditViewPage = () => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [notes, setNotes] = useState("");
  const [submittedIdeas, setSubmittedIdeas] = React.useState([]);
  const [viewModel, setViewModel] = React.useState({});
  const [edit_complete, set_edit_complete] = useState(false);
  const [surveyLink, setSurveyLink] = React.useState("");
  const [viewModelEdit, setViewModelEdit] = React.useState({});
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const [loader, setLoader] = useState(false);
  const BASE_URL = "https://equalityrecords.com/";
  const params = useParams();
  const projectID = params?.project_id;
  const isOpen = "view-mode";
  const [showRealDeleteEditModal, setShowRealDeleteEditModal] =
    React.useState(false);
  const [video_ids, setVideo_ids] = useState([]);
  const [music_ids, setMusic_ids] = useState([]);
  const [showDeleteEditModal, setShowDeleteEditModal] = React.useState(false);
  const [userEmail, setUserEmail] = useState("");
  const [CompanyName, setCompanyName] = useState("");
  const [triggerSave, setTriggerSave] = useState("");
  const [hasVideoDownloads, setHasVideoDownloads] = React.useState(false);
  const [hasMusicDownloads, setHasMusicDownloads] = React.useState(false);

  const handleRealDeleteEditModalClose = () => {
    setShowRealDeleteEditModal(false);
  };

  const openSecondDelete = () => {
    setShowRealDeleteEditModal(false);

    setTimeout(() => {
      setShowDeleteEditModal(true);
    }, 500);
  };

  useEffect(() => {
    viewModelEdit?.user_id && getUserDetails(viewModelEdit?.user_id);
  }, [viewModelEdit]);

  const getUserDetails = async (userId) => {
    try {
      const result = await getUserDetailsByIdAPI(userId);
      if (!result.error) {
        setUserEmail(result.model?.email);
        setCompanyName(result.model.company_name);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getPendingEdits = async () => {
    const res = await getAllEditAPI({
      producer_id: localStorage.getItem("user"),
      page: 1,
      limit: 50000,

      edit_status: 2,
    });

    globalDispatch({
      type: "SET_CURRENT_PENDING_LENGTH",
      payload: { pendingLength: res?.list?.length || 0 },
    });
  };
  const navigate = useNavigate();

  console.log(video_ids);

  const handleConfirmEdit = async (id) => {
    console.log(id);
    setTriggerSave(!triggerSave);

    let emailSubject = `Your music edit for ${viewModelEdit?.team_name} is ready for download!`;

    let body = `Hello ${viewModelEdit?.program_name},
        <br><br> <p>Your edit for ${
          viewModelEdit?.team_name
        } is ready for download. Please login to myEQ to download the latest version of
your music.</p>
               <a href="https://equalityrecords.com/client/login" style="text-decoration: none;">
            <button style="display: inline-block; padding: 8px 20px; background-color: #007bff; color: #ffffff; border: none; border-radius: 4px; cursor: pointer;">Login</button>
        </a>
        
        <br><br>Thank you,<br> ${localStorage.getItem("companyName")}.<br>`;
    let payloade = {
      from: "myeq@equalityrecords.com",
      to: userEmail,
      subject: emailSubject,
      body: body,
    };

    try {
      const payload = removeKeysWhenValueIsNull({
        video_ids:
          video_ids.length > 0 ? JSON.stringify(video_ids) : JSON.stringify([]),
        music_ids:
          music_ids.length > 0 ? JSON.stringify(music_ids) : JSON.stringify([]),
        edit_status: 1,
        completed_date: moment(new Date()).format("YYYY-MM-DD"),
      });

      // console.log(video);
      await UpdateEditAPI(payload, id);

      const result = await sendEmailAPIV3(payloade);
      await updateProjectAPI({
        id: projectID,
        discount: 0,
        payment_status: 1,
      });
      await getPendingEdits();
      setShowDeleteEditModal(false);
      navigate("/member/edits");
      // await getData();
      showToast(globalDispatch, `Edit Approved`, 5000);
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
      throw error;
    }
  };

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

      if (!result.error) {
        setSurveyLink(BASE_URL + "survey/" + result.model.uuidv4);
      } else {
        showToast(globalDispatch, result?.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getEditDetails = async () => {
    const res = await viewEditDetails(params.id);
    if (!res.error) {
      setVideo_ids(JSON.parse(res?.model?.video_ids) || []);
      set_edit_complete(res.model.edit_status === 1 ? true : false);
      setViewModelEdit(res.model);
    }
  };

  console.log(viewModel, "djjdjjdjdj");
  const getProjectDetails = async (id) => {
    try {
      const result = await getProjectDetailsAPI(Number(id));
      console.log(result);
      if (!result.error) {
        console.log("bdbdbdb");
        console.log(result.model);
        setViewModel(result.model);
        // setProjectTotal(result.model?.total);
        // setProgramName(result.model.program_name);
        // setTeamName(result.model.team_name);
        // setThemeOfTheRoutine(result.model?.theme_of_the_routine);
      } else {
        showToast(globalDispatch, result?.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  useEffect(() => {
    getEditDetails();
  }, []);

  useEffect(() => {
    (async function () {
      setLoader(true);

      await getSurveyByProjectId(projectID);
      await getProjectDetails(projectID);
      const result = await getSurveyByProjectIdAPI(Number(projectID));

      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) {
                  setSubmittedIdeas([]);
                } else if (result.model.status === 1) {
                  setSubmittedIdeas(result.model.ideas);
                }
              } else {
              }
            })();
          }
        }
      }
      setLoader(false);
    })();
  }, []);

  useEffect(() => {
    const interval = setInterval(() => {
      if (window.downloadManager?.downloads) {
        // Check for video downloads
        const activeVideoDownloads = Array.from(
          window.downloadManager.downloads.values()
        ).some(
          (download) =>
            download.type === "video" && download.status === "downloading"
        );

        // Check for music downloads
        const activeMusicDownloads = Array.from(
          window.downloadManager.downloads.values()
        ).some(
          (download) =>
            download.type === "music" && download.status === "downloading"
        );

        setHasVideoDownloads(activeVideoDownloads);
        setHasMusicDownloads(activeMusicDownloads);
      }
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  console.log(viewModelEdit);

  return (
    <>
      {showRealDeleteEditModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to complete this edit?`}
          setModalClose={handleRealDeleteEditModalClose}
          setFormYes={openSecondDelete}
        />
      ) : null}
      {showDeleteEditModal ? (
        <DuoConfirmModal
          confirmText={`Are you sure you want to complete this edit? This action cannot be undone.`}
          setModalClose={setShowDeleteEditModal}
          setFormYes={() => {
            handleConfirmEdit(params?.id);
          }}
        />
      ) : null}

      <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 pt-10 dark:border-strokedark dark:bg-boxdark">
          {/* Header Section */}
          <div className="sm:px-6.5 border-b border-strokedark px-4 py-4 dark:border-strokedark">
            <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
              <div>
                <div className="flex items-center gap-1">
                  <h3 className="text-xl font-medium text-white">
                    Edit Request for
                  </h3>
                  <p className="text-xl font-medium text-white">
                    {viewModelEdit?.program_name || "N/A"}
                  </p>
                  <span>-</span>
                  <span
                    onClick={() => {
                      localStorage.setItem("projectClientId", "");
                      localStorage.setItem("projectTeamName", "");
                      localStorage.setItem("projectMixTypeId", "");
                      localStorage.setItem("projectMixDateStart", "");
                      localStorage.setItem("projectMixDateEnd", "");
                      localStorage.setItem("projectPageSize", "");
                      navigate(`/member/view-project/${projectID}`);
                    }}
                    className="cursor-pointer text-xl text-primary hover:text-opacity-90"
                  >
                    {viewModelEdit?.team_name || "N/A"}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <span>Producer Name</span>
                  <span>{viewModelEdit?.producer}</span>
                </div>
              </div>
              <div className="flex flex-wrap items-center gap-3">
                <button
                  onClick={() => navigate(-1)}
                  className="inline-flex items-center justify-center rounded-md border border-strokedark bg-meta-4 px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                >
                  Back
                </button>
              </div>
            </div>
          </div>

          {/* Content Section */}
          <div className="p-4 md:p-6 2xl:p-10">
            <div className="mb-8">
              <div className="space-y-4">
                {/* Project Info */}

                {/* Producer Notes */}
                <div className="mb-10">
                  <span className="text-sm text-white">Notes for Producer</span>
                  <div
                    className="ml-auto mt-2 flex w-[70%] border-b border-strokedark pb-4 text-base text-white  dark:border-strokedark"
                    dangerouslySetInnerHTML={{
                      __html:
                        viewModelEdit?.producer_notes?.replace(
                          /\n/g,
                          "<br> "
                        ) || "N/A",
                    }}
                  />
                </div>

                {/* Video & Music Sections */}
                <div className="space-y-6">
                  <div className="rounded border border-strokedark  bg-boxdark p-4">
                    <VideoSection
                      video_ids={video_ids}
                      setVideo_ids={setVideo_ids}
                      viewModel={viewModel}
                      projectID={projectID}
                      edit_complete={false}
                      hasDownloads={hasVideoDownloads}
                    />
                  </div>

                  <ClientEightCountTab
                    triggerSave={triggerSave}
                    action={isOpen}
                    edit_complete={edit_complete}
                    edit_eight_count_id={viewModelEdit?.eight_count}
                    surveyLink={surveyLink}
                    viewModel={viewModel}
                    projectID={projectID}
                    submittedIdeas={submittedIdeas}
                  />

                  <div className="rounded border border-strokedark bg-boxdark p-4">
                    <MusicSection
                      music_ids={music_ids}
                      setMusic_ids={setMusic_ids}
                      viewModel={viewModel}
                      projectID={projectID}
                      edit_complete={false}
                      hasDownloads={hasMusicDownloads}
                    />
                  </div>
                </div>
              </div>
            </div>

            {/* Submit Button */}
            {viewModelEdit.edit_status === 2 && (
              <div className="flex justify-center">
                <button
                  onClick={() => setShowRealDeleteEditModal(true)}
                  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>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default MemberEditViewPage;
