import EditView from "Components/Client/EditView";
import RequestEdit1 from "Components/Client/RequestEdit1";
import RequestEdit2 from "Components/Client/RequestEdit2";
import RequestEdit3 from "Components/Client/RequestEdit3";
import ReviseEdit from "Components/Client/reviseEdit";
import ConfirmationView from "Components/ConfirmationView";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import { getProjectDetailsClientAPI } from "Src/services/clientProjectDetailsService";
import { getAllProjectsClientAPI } from "Src/services/clientService";
import {
  getAllEditAPI,
  getAllEditTypesListAPI,
} from "Src/services/editService";
import { getSurveyByProjectIdAPI } from "Src/services/projectService";
import { getSurveyDetails } from "Src/services/surveyService";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import { validateUuidv4 } from "Utils/utils";
import moment from "moment";
import React, { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router";
import { ClipLoader } from "react-spinners";

const ClientEditsPage = () => {
  const { dispatch: globalDispatch, state } = React.useContext(GlobalContext);
  const [openEditStep1, setOpenEditStep1] = useState(false);
  const [openEditStep2, setOpenEditStep2] = useState(false);
  console.log(openEditStep2, "dhdh");
  const [reviseEdit, setReviseEdit] = useState(false);
  const [openEditStep3, setOpenEditStep3] = useState(false);
  const [openEditStep4, setOpenEditStep4] = useState(false);
  const [openEditView, setOpenEditView] = useState("");
  const [pageCount, setPageCount] = React.useState(0);
  const [dataTotal, setDataTotal] = React.useState(0);
  const [currentPage, setPage] = React.useState(0);
  const [canPreviousPage, setCanPreviousPage] = React.useState(false);
  const [canNextPage, setCanNextPage] = React.useState(false);
  const pageSizeFromLocalStorage = localStorage.getItem("clientPageSizeEdit");
  const [loader2, setLoader2] = React.useState(false);
  const [pageSize, setPageSize] = React.useState(
    pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : 30 // Default pageSize
  );

  const [selectedTeam, setSelectedTeam] = useState(null);
  const [userDetails, setUserDetails] = useState(null);
  const [selectedEditType, setSelectedEditType] = useState(null);
  const [pendingView, setPendingView] = useState(true);
  const [completedView, setCompletedView] = useState(false);
  const [confirmationPage, setConfirmationPage] = useState(false);
  const navigate = useNavigate("");
  const [submittedIdeas, setSubmittedIdeas] = React.useState([]);
  const [viewModel, setViewModel] = React.useState({});
  const [surveyLink, setSurveyLink] = React.useState("");
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const [loader, setLoader] = useState(false);
  const [selectedTeamLoader, setSelectedTeamLoader] = useState(false);
  const [teamList, setTeamList] = useState([]);
  const [editList, setEditList] = useState([]);
  const [editData, setEditData] = useState({});
  const [TypeLists, setTypeLists] = useState([]);
  const [filterEditType, setFilterEditType] = useState("");
  const [SameTeamNameEdit, setSameTeamNameEdit] = useState({});
  const location = useLocation();

  const params = new URLSearchParams(location.search);

  const projectID = params.get("params");

  const BASE_URL = "https://equalityrecords.com/";
  console.log(viewModel);

  const getProjectDetails = async (id) => {
    try {
      const result = await getProjectDetailsClientAPI(Number(id));
      if (!result.error) {
        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);
    }
  };

  const getTypeList = async () => {
    try {
      const res = await getAllEditTypesListAPI();
      setTypeLists(res.list);
    } catch (error) {}
  };

  useEffect(() => {
    (async function () {
      await getAllProjects();
    })();
  }, []);

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

  useEffect(() => {
    (async function () {
      if (projectID) {
        setLoader(true);
        const team = teamList.find((elem) => elem.value == projectID);
        setSelectedTeam(team);
        const res = await getPending(team?.value);

        if (res && teamList.length > 0) {
          setOpenEditStep4(true);
          setLoader(false);
        } else if (!res && teamList.length > 0) {
          setOpenEditStep2(true);
          setLoader(false);
        }
      }
    })();
  }, [teamList]);

  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 getAllProjects = async () => {
    try {
      setLoader(true);
      const result = await getAllProjectsClientAPI();

      if (!result.error) {
        if (result.list.length > 0) {
          let teamNames = [];
          let teamNamesForSelect = [];
          if (result.list.length > 0) {
            const paidList = result.list.filter(
              (elem) => elem?.payment_status === 4 || elem?.payment_status === 1
            );

            paidList.forEach((row) => {
              teamNames.push(row.team_name);
              teamNamesForSelect.push({
                value: row.id,
                label: row.team_name,
                user_id: row.user_id,
                program: row.program_name,
              });
            });
          }
          // keep the unique team names
          teamNames = [...new Set(teamNames)];
          // sort by alphabetical order
          teamNames.sort();
          teamNamesForSelect.sort((a, b) => {
            return a.label.localeCompare(b.label);
          });
          setTeamList(teamNamesForSelect);
          setLoader(false);
        }
      }
    } catch (error) {
      setLoader(false);
      tokenExpireError(dispatch, error.message);
    }
  };

  function updatePageSize(limit) {
    (async function () {
      setPageSize(limit);
      await getData(1, limit);
    })();
    localStorage.setItem("clientPageSizeclientPageSize", limit);
  }

  function previousPage() {
    (async function () {
      // await getData(currentPage - 1 > 0 ? currentPage - 1 : 0, pageSize);
      await getData(
        currentPage - 1,
        pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : pageSize
      );
    })();
  }

  function nextPage() {
    (async function () {
      // await getData(
      //   currentPage + 1 <= pageCount ? currentPage + 1 : 0,
      //   pageSize
      // );
      await getData(
        currentPage + 1,
        pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : pageSize
      );
    })();
  }

  const getPending = async (valueID) => {
    try {
      const res = await getAllEditAPI({
        user_id: localStorage.getItem("user"),
        page: 1,
        limit: 10000,

        edit_status: 2,
      });
      const { list, total, limit, num_pages, page } = res;

      const sameProject =
        list.find((elem) => elem.project_id === valueID) || null;

      if (sameProject) {
        setSameTeamNameEdit(sameProject);
        return true;
      } else {
        return false;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  async function getData(
    pageNum,
    limitNum,
    filter = completedView ? { edit_status: 1 } : { edit_status: 2 }
  ) {
    setLoader2(true);
    try {
      const res = await getAllEditAPI({
        user_id: localStorage.getItem("user"),
        page: pageNum,
        limit: limitNum,
        ...filter,
      });

      const { list, total, limit, num_pages, page } = res;

      let sortedList1 = [];

      if (completedView) {
        sortedList1 = list.sort((a, b) => {
          return new Date(b?.completed_date) - new Date(a?.completed_date);
        });
      } else {
        sortedList1 = list.sort((a, b) => {
          return new Date(a?.due_date) - new Date(b?.due_date);
        });
      }

      if (filterEditType) {
        const newlist = list.filter((elem) => {
          return elem.edit_type_name == filterEditType;
        });

        const sortedList = newlist.sort((a, b) => {
          return new Date(a?.due_date) - new Date(b?.due_date);
        });

        setEditList(sortedList);
      } else {
        setEditList(sortedList1);
      }

      setPage(page);
      setPageCount(num_pages);

      setDataTotal(total);
      setCanPreviousPage(page > 1);
      setCanNextPage(page + 1 <= num_pages);
      setLoader2(false);
    } catch (error) {
      setLoader2(false);
      tokenExpireError(dispatch, error.message);
    }
  }

  useEffect(() => {
    (async function () {
      if (selectedTeam) {
        if (selectedTeam?.user_id) {
          const res = await getUserDetailsByIdAPI(selectedTeam.user_id);

          setUserDetails(res?.model);
        }

        await getSurveyByProjectId(selectedTeam.value);
        await getProjectDetails(selectedTeam.value);
        const result = await getSurveyByProjectIdAPI(
          Number(selectedTeam.value)
        );

        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 {
                }
              })();
            }
          }
        }
      }
    })();
  }, [selectedTeam, openEditStep4, teamList]);

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "edits",
      },
    });

    getData(currentPage, pageSize);
  }, [completedView, pendingView, filterEditType, confirmationPage]);

  const defaultTypes = [
    { name: "All", value: "" },
    { name: "Minor 1", value: "Minor 1" },
    { name: "Major 1", value: "Major 1" },
    { name: "Minor 2", value: "Minor 2" },

    { name: "Major 2", value: "Major 2" },
  ];

  function convertDateFormat(dateString) {
    // Split the date string into year, month, and day

    if (dateString) {
      var parts = dateString?.split("-");

      // Rearrange the parts into the desired format
      var formattedDate =
        parts[1].padStart(2, "0") +
        "-" +
        parts[2].padStart(2, "0") +
        "-" +
        parts[0];

      return formattedDate;
    }
  }
  console.log(openEditView);
  return (
    <div
      className="p-4 h-full max-w-screen md:p-4 lg:p-6 xl:p-8"
      id="mainContainer"
    >
      {/* Modals */}
      {openEditStep1 && (
        <RequestEdit1
          setIsOpen={setOpenEditStep1}
          isOpen={openEditStep1}
          setSelectedTeam={setSelectedTeam}
          selectedTeam={selectedTeam}
          setUserDetails={setUserDetails}
          setOpenEditStep2={setOpenEditStep2}
          teamList={teamList}
          getPending={getPending}
          setIsOpen2={setOpenEditStep2}
          setIsOpen4={setOpenEditStep4}
        />
      )}
      {openEditStep2 && (
        <RequestEdit2
          setSelectedEditType={setSelectedEditType}
          selectedEditType={selectedEditType}
          isOpen={openEditStep2}
          setIsOpen1={setOpenEditStep1}
          setSelectedTeam={setSelectedTeam}
          setIsOpen2={setOpenEditStep2}
          producer_id={userDetails?.id}
          setIsOpen3={setOpenEditStep3}
        />
      )}
      {openEditStep4 && (
        <ReviseEdit
          setReviseEdit={setReviseEdit}
          setSelectedTeam={setSelectedTeam}
          setSelectedEditType={setSelectedEditType}
          selectedEditType={selectedEditType}
          producer_id={userDetails?.id}
          SameTeamNameEdit={SameTeamNameEdit}
          setIsOpen1={setOpenEditStep1}
          setIsOpen3={setOpenEditStep4}
          setIsOpen2={setOpenEditStep2}
          isOpen={openEditStep4}
          producerName={
            userDetails
              ? userDetails?.first_name + " " + userDetails?.last_name
              : ""
          }
          setOpenEditView={setOpenEditView}
        />
      )}
      {openEditStep3 && (
        <RequestEdit3
          setIsOpen1={setOpenEditStep1}
          setSelectedTeam={setSelectedTeam}
          edit_policy={userDetails?.edit_policy_link}
          setIsOpen3={setOpenEditStep3}
          setIsOpen2={setOpenEditStep2}
          isOpen={openEditStep3}
          producer_id={userDetails?.id}
          producerName={userDetails?.first_name + " " + userDetails?.last_name}
          setOpenEditView={setOpenEditView}
        />
      )}
      {(openEditView?.toString()?.length > 0 &&
        openEditView &&
        !confirmationPage) ||
      (reviseEdit && !confirmationPage) ? (
        <EditView
          setReviseEdit={setReviseEdit}
          reviseEdit={reviseEdit}
          setSelectedTeam={setSelectedTeam}
          SameTeamNameEdit={SameTeamNameEdit}
          producerName={userDetails?.first_name + " " + userDetails.last_name}
          producer_id={userDetails?.id}
          selectedTeam={selectedTeam}
          loader={loader}
          selectedEditType={selectedEditType}
          surveyLink={surveyLink}
          viewModel={viewModel}
          submittedIdeas={submittedIdeas}
          setIsOpen={setOpenEditView}
          isOpen={openEditView}
          projectID={selectedTeam?.value}
          setConfirmationPage={setConfirmationPage}
          setEditData={setEditData}
        />
      ) : null}
      {confirmationPage && (
        <ConfirmationView
          editData={editData}
          setIsOpen={setConfirmationPage}
          isOpen={confirmationPage}
          setisOpenRequestEdit={setOpenEditStep1}
          setOpenEditView={setOpenEditView}
        />
      )}
      {(!openEditView || openEditView?.toString()?.length < 0) &&
      !confirmationPage ? (
        !loader ? (
          <>
            <div className="rounded border shadow-default border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
              {/* Header Section */}
              <div className="sm:px-6.5 border-b border-strokedark px-4 py-4 2xl:px-9 dark:border-strokedark">
                <div className="flex justify-between items-center">
                  <div className="flex gap-4 items-center">
                    <h4 className="text-2xl font-semibold text-white dark:text-white">
                      Edits
                    </h4>
                    <div className="flex gap-2 items-center">
                      <button
                        onClick={() => {
                          setPendingView(true);
                          setCompletedView(false);
                        }}
                        className={`rounded-md px-3 py-1 text-sm font-medium ${
                          pendingView
                            ? "text-white bg-primary"
                            : "text-white hover:bg-meta-4"
                        }`}
                      >
                        Pending
                      </button>
                      <button
                        onClick={() => {
                          setCompletedView(true);
                          setPendingView(false);
                        }}
                        className={`rounded-md px-3 py-1 text-sm font-medium ${
                          completedView
                            ? "text-white bg-primary"
                            : "text-white hover:bg-meta-4"
                        }`}
                      >
                        Completed
                      </button>
                    </div>
                  </div>
                  <button
                    onClick={() => setOpenEditStep1(true)}
                    className="inline-flex gap-1 justify-center items-center px-4 py-2 text-sm font-medium text-white rounded-md bg-primary hover:bg-opacity-90"
                  >
                    Request Edit +
                  </button>
                </div>
              </div>

              {/* Table Content Section */}
              <div className="min-h-[200px] p-4 md:p-6 2xl:p-10 ">
                <div className="overflow-x-auto w-full custom-overflow">
                  <table className="w-full table-auto">
                    <thead className="bg-meta-4">
                      <tr>
                        <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                          Program/Team
                        </th>
                        <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                          Team Name
                        </th>
                        <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                          Producer
                        </th>
                        <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                          Edit Type
                        </th>
                        <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase whitespace-nowrap text-bodydark1">
                          Request Date
                        </th>
                        <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                          Due Date
                        </th>
                      </tr>
                    </thead>
                    {!loader2 ? (
                      <tbody className="cursor-pointer text-bodydark1">
                        {editList.map((elem) => (
                          <tr
                            key={elem.id}
                            onClick={() =>
                              navigate(
                                `/client/view-edit/${elem.id}/${elem.project_id}`
                              )
                            }
                            className="border-b border-strokedark hover:bg-primary/5 dark:border-strokedark"
                          >
                            <td className="px-4 py-4 pl-6 text-white whitespace-nowrap 2xl:pl-9">
                              <span>{elem.program_name}</span>
                            </td>
                            <td className="px-4 py-4 whitespace-nowrap">
                              <span>{elem.team_name}</span>
                            </td>
                            <td className="px-4 py-4 whitespace-nowrap">
                              <span>{elem.producer}</span>
                            </td>
                            <td className="px-4 py-4 whitespace-nowrap">
                              <span>{elem.edit_type_name}</span>
                            </td>
                            <td className="px-4 py-4 whitespace-nowrap">
                              <span>
                                {moment(
                                  elem?.request_date,
                                  "YYYY-MM-DD"
                                ).format("MM-DD-YYYY")}
                              </span>
                            </td>
                            <td className="px-4 py-4 whitespace-nowrap">
                              <span>{convertDateFormat(elem.due_date)}</span>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    ) : loader2 ? (
                      <tbody>
                        <tr>
                          <td colSpan="6" className="text-center">
                            <span className="trans relative top-[30px] m-4 animate-pulse whitespace-nowrap p-4 pb-8 text-xl font-semibold text-white ease-out">
                              <ClipLoader
                                color="#fff"
                                size={20}
                                className="mr-3"
                              />{" "}
                              Loading Edits...
                            </span>
                          </td>
                        </tr>
                      </tbody>
                    ) : !loader2 && editList.length === 0 ? (
                      <tbody>
                        <tr>
                          <td colSpan="6" className="text-center">
                            <span className="relative top-[10px] m-4 p-4 font-semibold text-white">
                              No data found
                            </span>
                          </td>
                        </tr>
                      </tbody>
                    ) : (
                      loader && (
                        <tbody>
                          <tr>
                            <td colSpan="6" className="text-center">
                              <span className="trans relative top-[30px] m-4 animate-pulse whitespace-nowrap p-4 pb-8 text-xl font-semibold text-white ease-out">
                                <ClipLoader
                                  color="#fff"
                                  size={20}
                                  className="mr-3"
                                />{" "}
                                Loading Edits...
                              </span>
                            </td>
                          </tr>
                        </tbody>
                      )
                    )}
                  </table>
                </div>

                {/* Pagination */}
                {/* {editList.length > 0 && !loader2 && (
                  <div className="px-4 py-10 w-full md:px-6 2xl:px-9">
                    <PaginationBar
                      currentPage={currentPage}
                      pageCount={pageCount}
                      pageSize={pageSize}
                      canPreviousPage={canPreviousPage}
                      canNextPage={canNextPage}
                      updatePageSize={updatePageSize}
                      previousPage={previousPage}
                      nextPage={nextPage}
                      dataTotal={dataTotal}
                      setCurrentPage={setPage}
                    />
                  </div>
                )} */}
              </div>
            </div>
          </>
        ) : (
          <div className="flex justify-center items-center w-full h-screen">
            <ClipLoader color="#fff" size={20} className="mr-3" />
          </div>
        )
      ) : null}
    </div>
  );
};

export default ClientEditsPage;
