import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  deleteEditAPI,
  getAllEditTypesListAPI,
} from "Src/services/editService";
import { updateProjectAPI } from "Src/services/projectService";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import React, { useEffect, useState } from "react";
import { ClipLoader } from "react-spinners";

const ReviseEdit = ({
  isOpen,
  producer_id = null,
  SameTeamNameEdit,
  setIsOpen2,
  setIsOpen3,
  setIsOpen1,
  setOpenEditView,
  producerName,
  setSelectedEditType,
  selectedEditType,
  setSelectedTeam,
  setReviseEdit,
}) => {
  const [SpecialList, setSpecialList] = useState([]);
  const [editPolicy, setEditPolicy] = useState("");
  const [loader, setLoader] = useState(false);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  console.log(producer_id, SpecialList, isOpen);

  const getSpecialList = async () => {
    setLoader(true);
    const res = producer_id
      ? await getAllEditTypesListAPI({ user_id: producer_id })
      : { list: [] };
    const list = res.list.filter((elem) => elem?.request_range === "Special");
    if (list.length <= 0) {
      setIsOpen3(true);
    }
    setSpecialList(list);
    setLoader(false);
  };

  React.useEffect(() => {
    if (producer_id) {
      (async function () {
        try {
          const result = await getUserDetailsByIdAPI(producer_id);

          if (!result?.error) {
            console.log(result.model);
            setEditPolicy(result.model.edit_policy_link);
          }
        } catch (error) {}
      })();
    }
  }, [producer_id]);

  useEffect(() => {
    producer_id && getSpecialList();

    setSelectedEditType(SameTeamNameEdit?.special_type);
  }, [producer_id]);

  console.log(SameTeamNameEdit);

  return (
    <div className="custom-overflow fixed inset-0 z-[52] flex h-full w-full items-center justify-center overflow-y-auto px-4 py-8 backdrop-blur-sm">
      <div className="shadow-default relative w-full max-w-[800px] rounded border border-strokedark bg-boxdark p-4 sm:p-8 dark:border-strokedark dark:bg-boxdark">
        <div className="flex items-center justify-between border-b border-strokedark pb-4 dark:border-strokedark">
          <h3 className="text-2xl font-semibold text-white dark:text-white">
            Modifications to Pending Edit
          </h3>
          <button
            onClick={() => {
              setSelectedTeam(null);
              setIsOpen2(false);
              setIsOpen1(false);
              setIsOpen3(false);
            }}
            className="text-white hover:text-white dark:text-gray-400 dark:hover:text-white"
          >
            <FontAwesomeIcon icon="close" className="h-5 w-5" />
          </button>
        </div>

        <div className="mt-6">
          <div className="mb-6 space-y-3">
            <div className="flex items-center gap-2">
              <span className="text-sm font-medium text-white">
                Edit Request:
              </span>
              <span className="text-sm text-white">
                {SameTeamNameEdit?.program_name} - {SameTeamNameEdit?.team_name}
              </span>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-sm font-medium text-white">
                Producer Name:
              </span>
              <span className="text-sm text-white">{producerName}</span>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-sm font-medium text-white">
                Edit Policy:
              </span>
              {editPolicy ? (
                <a
                  target="_blank"
                  className="text-sm text-primary underline hover:text-primary/90"
                  href={`${editPolicy}`}
                >
                  Edit_Policy.pdf
                </a>
              ) : (
                <span className="text-sm text-white">null</span>
              )}
            </div>
          </div>

          <div className="mb-6">
            <span className="text-sm font-medium text-white">
              Do you want to change edit type:
            </span>
            <div className="mt-3 flex flex-wrap gap-4">
              {loader ? (
                <ClipLoader size={15} color="white" />
              ) : (
                <>
                  {SpecialList.map((elem) => (
                    <div key={elem.id} className="flex items-center gap-2">
                      <input
                        type="radio"
                        checked={elem.id === parseInt(selectedEditType)}
                        onChange={(e) => {
                          setSelectedEditType(
                            e.target.checked ? elem.id : null
                          );
                        }}
                        className="h-4 w-4"
                        name="special"
                        value={elem.id}
                      />
                      <span className="text-sm text-white">
                        {elem.edit_type}
                      </span>
                      <span className="group relative">
                        <FontAwesomeIcon
                          icon="question-circle"
                          className="h-3 w-3 cursor-pointer text-white"
                        />
                        <p className="invisible absolute -top-5 z-[4] w-[200px] rounded bg-gray-100 p-3 text-xs text-gray-900 group-hover:visible">
                          {elem.note_keys}
                        </p>
                      </span>
                    </div>
                  ))}
                  <div className="flex items-center gap-2">
                    <input
                      type="radio"
                      checked={selectedEditType === ""}
                      onChange={(e) => {
                        setSelectedEditType(e.target.checked ? "" : null);
                      }}
                      className="h-4 w-4"
                      name="special"
                    />
                    <span className="text-sm text-white">None</span>
                  </div>
                </>
              )}
            </div>
          </div>

          <div className="mb-6 text-center">
            <p className="text-sm text-white">
              Would you like to revise the previous version of the edit or start
              new?
            </p>
            <p className="mt-2 text-xs italic text-warning">
              ⓘ Submitting a new or revised edit will reset the due date based
              on newly submitted date and edit type. Please review edit policy
              for further information.
              <br />
              <br />ⓘ Starting with blank count sheets will delete data from
              previous pending edit.
            </p>
          </div>

          <div className="mb-8 flex justify-center gap-4">
            <button
              onClick={() => {
                if (selectedEditType === null) {
                  showToast(
                    globalDispatch,
                    "Make a selection on edit Type",
                    5000,
                    "warning"
                  );
                } else {
                  console.log(SameTeamNameEdit?.eight_count);
                  setOpenEditView(
                    SameTeamNameEdit?.eight_count
                      ? parseInt(SameTeamNameEdit?.eight_count)
                      : 0
                  );
                  setReviseEdit(true);
                  setIsOpen2(false);
                  setIsOpen1(false);
                  setIsOpen3(false);
                }
              }}
              className="flex h-[56px] w-[146px] items-center justify-center rounded bg-primary px-6 py-2 text-xs font-medium text-white hover:bg-opacity-90"
            >
              <span className="text-[13px] leading-[15px]">
                Revise Previous Pending Version
              </span>
            </button>
            <button
              onClick={async () => {
                if (selectedEditType === null) {
                  showToast(
                    globalDispatch,
                    "Make a selection on edit Type",
                    5000,
                    "warning"
                  );
                } else {
                  setOpenEditView("Blank");
                  await deleteEditAPI(SameTeamNameEdit?.id);
                  await updateProjectAPI({
                    id: SameTeamNameEdit?.project_id,
                    discount: 0,
                    payment_status: 1,
                  });
                  setIsOpen2(false);
                  setIsOpen1(false);
                  setIsOpen3(false);
                }
              }}
              className="flex h-[56px] w-[146px] items-center justify-center rounded bg-primary px-6 py-2 text-xs font-medium text-white hover:bg-opacity-90"
            >
              <span className="text-[13px] leading-[15px]">
                Start With Blank 8-count Sheet
              </span>
            </button>
          </div>

          <div className="flex items-center justify-start">
            <button
              onClick={() => {
                setIsOpen1(true);
                setIsOpen3(false);
              }}
              className="flex items-center justify-center gap-2 rounded bg-primary px-6 py-2 font-medium text-white hover:bg-opacity-90"
            >
              <FontAwesomeIcon icon="arrow-left" className="text-xs" />
              <span>Previous</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ReviseEdit;
