import Spinner from "Components/Spinner";
import { AuthContext } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import { getTeamDetailsAPI } from "Src/services/clientProjectDetailsService";
import React from "react";
import { useParams } from "react-router";
import ClientEditMusicDetailsModal from "../ClientEditMusicDetails";

const ClientMusicDetailsTab = (props) => {
  const { viewModel } = props;
  const projectId = useParams();
  const { state: authState } = React.useContext(AuthContext);
  const [loader, setLoader] = React.useState(false);

  const [data, setData] = React.useState({
    notes: "",
    song_list: "",
    // competitions: "",
    colors: "",
    mascot: "",
    social_media: "",

    // theme: "",
  });
  const [isEditMusicDetailsModalOpen, setIsEditMusicDetailsModalOpen] =
    React.useState(false);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const getData = async () => {
    setLoader(true);
    try {
      const result = await getTeamDetailsAPI(projectId.id);
      setLoader(false);

      if (result?.model) {
        setData(result.model);
      }
    } catch (error) {
      setLoader(false);
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };
  React.useEffect(() => {
    getData();
  }, []);

  function isSameDay(date1, date2) {
    // Get the routine submission date and convert it to a Date object
    let routineDate = new Date(viewModel?.routine_submission_date);

    // Create a new Date object for the "next day" by adding 1 day to the routineDate
    let nextDayUTC = new Date(
      Date.UTC(
        routineDate.getUTCFullYear(),
        routineDate.getUTCMonth(),
        routineDate.getUTCDate() + 1
      )
    );

    // Set the time to midnight UTC
    nextDayUTC.setUTCHours(0, 0, 0, 0);
    let timezoneOffset = nextDayUTC.getTimezoneOffset() * 60000;

    // Apply the timezone offset to the next day to align it with the local time
    let nextDayLocal = new Date(nextDayUTC.getTime() + timezoneOffset);

    // Get the current time in local time
    let currentTimeLocal = new Date();

    // Log the dates for debugging
    console.log("Next Day (Local):", nextDayLocal);
    console.log("Current Local Time:", currentTimeLocal);

    // Compare the current local time with the next day (adjusted to local time)
    return currentTimeLocal > nextDayLocal;
  }

  const currentTimezoneOffset = new Date().getTimezoneOffset();
  console.log("Current Timezone Offset (in minutes):", currentTimezoneOffset);

  console.log(data?.notes?.replace((/\n/g, "<br>")));
  return (
    <>
      {isEditMusicDetailsModalOpen && (
        <ClientEditMusicDetailsModal
          setData={setData}
          data={data}
          getData={getData}
          setIsOpen={setIsEditMusicDetailsModalOpen}
          isOpen={isEditMusicDetailsModalOpen}
        />
      )}
      <div className="mb-4 w-full">
        {/* {isSameDay(new Date(), new Date(viewModel?.routine_submission_date)) &&
        authState?.role === "client" ? (
          <div className="p-3 mb-4 rounded border border-warning bg-warning/10">
            <p className="font-medium text-warning">
              Routine submission has been locked because it is past the
              submission deadline. If you need access, email your producer at{" "}
              <a
                target="_blank"
                rel="noreferrer"
                href={viewModel?.company_info.office_email}
                className="underline text-primary hover:text-primary/80"
              >
                {viewModel?.company_info.office_email}
              </a>
            </p>
          </div>
        ) : null} */}
        <button
          className="focus:ring-00 flex h-[40px] w-[100px] items-center justify-center rounded bg-primary  p-3 px-5 text-xl font-medium text-white focus-visible:outline-none sm:h-[56px] sm:w-[140px]"
          onClick={() => {
            if (
              isSameDay(
                new Date(),
                new Date(viewModel?.routine_submission_date)
              ) &&
              authState?.role === "client"
            ) {
              showToast(
                globalDispatch,
                "Email the producer office to unlock the team details",
                7000
              );
            } else {
              setIsEditMusicDetailsModalOpen(true);
            }
          }}
        >
          Edit
        </button>
        <br />

        {loader ? (
          <div className="fixed inset-0 z-[100] flex h-screen  w-full items-center justify-center bg-black/80 ">
            {" "}
            <Spinner />
          </div>
        ) : (
          <div className="mt-10 flex flex-col gap-4">
            <div className="flex items-start gap-4">
              <span className="text-lg font-bold">Notes:</span>
              <p
                dangerouslySetInnerHTML={{
                  __html: data?.notes?.replace(/\n/g, "<br> "),
                }}
              >
                {}
              </p>
            </div>
            <div className="flex items-start gap-4">
              <span className="whitespace-nowrap text-lg font-bold">
                Song List:
              </span>
              <p
                dangerouslySetInnerHTML={{
                  __html: data?.song_list?.replace(/\n/g, "<br> "),
                }}
              >
                {}
              </p>
            </div>
            {/* <div className="flex gap-4 items-center">
            <span className="text-lg font-bold">Competitions:</span>
            <div>{data?.competitions}</div>
          </div> */}
            <div className="flex items-center gap-4">
              <span className="text-lg font-bold">Colors:</span>
              <div>{data?.colors}</div>
            </div>
            <div className="flex items-center gap-4">
              <span className="text-lg font-bold">Mascot:</span>
              <div>{data?.mascot}</div>
            </div>
            {/* <div className="flex gap-4 items-center">
            <span className="text-lg font-bold">Theme:</span>
            <div>{data?.theme}</div>
          </div> */}
            <div className="">
              <span className="mb-2 text-lg font-bold">Social Media:</span>
              <div className="ml-6">
                <div className=" flex items-start gap-[4px] ">
                  <span className="text-lg font-bold">Twitter:</span>

                  <div>
                    {data.social_media ? (
                      <a
                        target="_blank"
                        rel="noreferrer"
                        className="whitespace-break-spaces break-all text-blue-600 underline"
                        href={JSON.parse(data.social_media)?.twitter || ""}
                      >
                        {JSON.parse(data.social_media)?.twitter || ""}
                      </a>
                    ) : (
                      ""
                    )}
                  </div>
                </div>
                <div className="flex items-start gap-1">
                  <span className="text-lg font-bold">Instagram:</span>
                  <div>
                    {data.social_media ? (
                      <a
                        target="_blank"
                        rel="noreferrer"
                        className="break-all text-blue-600 underline"
                        href={JSON.parse(data.social_media)?.instagram || ""}
                      >
                        {JSON.parse(data.social_media)?.instagram || ""}
                      </a>
                    ) : (
                      ""
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </>
  );
};

export default ClientMusicDetailsTab;
