import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { GlobalContext, showToast } from "Src/globalContext";
import { sendEmailAPIV3 } from "Src/services/emailService";
import { getSurveyByProjectIdAPI } from "Src/services/projectService";
import { getSurveyDetails } from "Src/services/surveyService";
import MkdSDK from "Utils/MkdSDK";
import { validateUuidv4 } from "Utils/utils";
import moment from "moment";
import React from "react";
import { useParams } from "react-router";
import { ClipLoader } from "react-spinners";
import { SingleDatePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

const ChooseDateToReLockSurvey = ({
  setModalClose,
  id,
  viewModel,
  surveyLink,
}) => {
  const [date, setDate] = React.useState("");
  const [loader, setLoader] = React.useState(true);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [focusedInput, setFocusedInput] = React.useState(null);

  let sdk = new MkdSDK();
  const BASE_URL = "https://equalityrecords.com/";
  const params = useParams();
  const [loading, setLoading] = React.useState(false);
  // const [lockDate, setLockDate] = React.useState('');
  //
  React.useEffect(() => {
    (async function () {
      try {
        setLoader(true);
        const result = await getSurveyByProjectIdAPI(Number(params?.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) {
                  setDate(result.model?.lock_date);
                  // if (result.model.status === 0) {
                  //   setSubmittedIdeas([]);
                  // } else if (result.model.status === 1) {
                  //   setSubmittedIdeas(result.model.ideas);
                  // }
                } else {
                }
              })();
            }
          }
        }
        setLoader(false);
      } catch (error) {
        setLoader(false);
      }
    })();
  }, []);

  const handleSubmit = async () => {
    const currentDate = new Date();

    // Subtract one day
    const yesterday = new Date(currentDate);
    yesterday.setDate(currentDate.getDate() - 1);
    const selectedDate = new Date(date); // Convert selected date to Date object
    console.log(yesterday, selectedDate);
    if (selectedDate < yesterday) {
      // Date is less than current date
      // Show toast or make a POST request
      // Example: Show toast message
      showToast(
        globalDispatch,
        "Selected date cannot be less than current date",
        5000,
        "warning"
      );

      return; // Exit the function early
    }

    // Date is greater than or equal to current date

    const payload = {
      lock_date: moment(selectedDate)
        .utc(selectedDate)
        .add(1, "days")
        .local()
        .format("YYYY-MM-DD"),
    };

    try {
      setLoading(true);
      const uri = `/v3/api/custom/equality_record/survey/update/lock_date/${id}`;
      const res = await sdk.callRawAPI(uri, payload, "PUT");

      const payloade = {
        from: "myeq@equalityrecords.com",
        to: viewModel.program_owner_email,
        subject: `Survey Now Unlocked for ${viewModel?.team_name}: Share Your Vision for ${viewModel?.mix_season_name}'s Music Season! `,
        body: `
              <p>Hello <b>${viewModel?.program_name}</b> !</p>
              <p>Great news! The survey link for ${
                viewModel?.mix_season_name
              }'s music season collaboration for <b>${
          viewModel?.team_name
        }</b> is now unlocked and ready for your input. We appreciate your patience as we worked to refine our process.</p>
              <p>Please take this opportunity to provide us with as much detail as possible regarding the theme and vision for your project. Your insights are invaluable in shaping the musical experience we'll create together.</p>
              <p>The survey will remain open until ${moment
                .utc(selectedDate)
                .local()
                .format(
                  "MM-DD-YYYY"
                )}, giving you ample time to make any modifications or additions.</p>
               <a href="${surveyLink}" 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>

              <p>ENJOY!</p>
              <p>All the best,</p>
              <p>${viewModel.company_info.company_name} </p>
        `,
      };

      await sendEmailAPIV3(payloade);
      setLoading(false);
      if (!res.error) {
        showToast(
          globalDispatch,
          "Survey lock date has been set",
          5000,
          "success"
        );
      }
    } catch (error) {
      setLoading(false);

      return error;
    }

    setModalClose(false);
  };

  return (
    <div className="fixed inset-0 z-10 overflow-y-auto">
      <div className="flex min-h-screen items-center justify-center px-4 pb-20 pt-4 text-center sm:block sm:p-0">
        <div className="fixed inset-0 transition-opacity" aria-hidden="true">
          <div className="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <span
          className="hidden sm:inline-block sm:h-screen sm:align-middle"
          aria-hidden="true"
        >
          &#8203;
        </span>
        <div
          className="inline-block transform overflow-hidden rounded-lg bg-gray-800 text-left align-bottom shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg sm:align-middle"
          role="dialog"
          aria-modal="true"
          aria-labelledby="modal-headline"
        >
          <form>
            <div className="flex w-full justify-between border-b-2 border-gray-500 bg-slate-950 px-6 py-4">
              <h3
                className="text-2xl font-medium leading-6 text-gray-100"
                id="modal-headline"
              >
                Choose a date to relock the survey
              </h3>
              <span
                className="absolute right-3 top-4 cursor-pointer"
                onClick={() => setModalClose(false)}
              >
                <FontAwesomeIcon
                  icon="fa-solid fa-circle-xmark"
                  width={32}
                  height={32}
                  color="#fff"
                />
              </span>
            </div>

            {!loader ? (
              <div className="video-player flex max-h-[400px] w-full max-w-full justify-center p-4">
                <SingleDatePicker
                  id="lock_date"
                  date={date ? moment(date) : null}
                  onDateChange={(date) => {
                    setDate(date ? date.format("YYYY-MM-DD") : "");
                  }}
                  focused={focusedInput}
                  onFocusChange={({ focused }) => setFocusedInput(focused)}
                  numberOfMonths={1}
                  isOutsideRange={() => false}
                  displayFormat="MM-DD-YYYY"
                  placeholder="Select Lock Date"
                  readOnly={true}
                  customInputIcon={null}
                  noBorder={true}
                  block
                />
              </div>
            ) : (
              <ClipLoader size={15} color="white" />
            )}

            <div className="flex w-full justify-end border-t-2 border-gray-500 bg-slate-950 px-6 py-4">
              <div
                onClick={handleSubmit}
                className="ml-3 inline-flex w-auto cursor-pointer justify-center rounded-md border border-transparent bg-blue-600 px-4 py-2 text-base font-medium text-white shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 sm:text-sm"
              >
                {loading ? (
                  <ClipLoader size={9} color="white" />
                ) : (
                  <span> Submit</span>
                )}
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default ChooseDateToReLockSurvey;
