import AddSpecialEdit from "Components/AddSpecialEdit";
import CustomSelect2 from "Components/CustomSelect2";
import PaginationBar from "Components/PaginationBar";
import TypesList from "Components/TypesList";
import { AuthContext, tokenExpireError } from "Src/authContext";

import { GlobalContext } from "Src/globalContext";
import {
  getAllEditAPI,
  getAllEditTypesListAPI,
} from "Src/services/editService";
import { getAllMembersForManager } from "Src/services/managerServices";
import moment from "moment";
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router";
import { ClipLoader } from "react-spinners";

const ManagerEditsPage = () => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const [loader, setLoader] = useState(false);
  const [openSpecialEdit, setOpenSpecialEdit] = useState(false);

  const [currentPage, setPage] = React.useState(0);
  const [canPreviousPage, setCanPreviousPage] = React.useState(false);
  const [canNextPage, setCanNextPage] = React.useState(false);
  const pageSizeFromLocalStorage = localStorage.getItem("clientPageSizeEdit");
  const [pageSize, setPageSize] = React.useState(
    pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : 30 // Default pageSize
  );

  const pendingViewFromLocalStorage = localStorage.getItem(
    "managerPendingViewEdits"
  );
  const completedViewFromLocalStorage = localStorage.getItem(
    "managerCompletedViewEdits"
  );
  const typeViewFromLocalStorage = localStorage.getItem("managerTypeViewEdits");
  console.log(Boolean("false"));
  console.log(typeViewFromLocalStorage);
  const [pendingView, setPendingView] = useState(
    pendingViewFromLocalStorage ? JSON.parse(pendingViewFromLocalStorage) : true
  );
  const [completedView, setCompletedView] = useState(
    completedViewFromLocalStorage
      ? JSON.parse(completedViewFromLocalStorage)
      : false
  );
  const [typesView, setTypesView] = useState(
    typeViewFromLocalStorage ? JSON.parse(typeViewFromLocalStorage) : false
  );
  const selectedMemberFromLocalStorage = localStorage.getItem(
    "managerSelectedMemberId"
  );
  const [selectedMemberId, setSelectedMemberId] = React.useState(
    selectedMemberFromLocalStorage ? selectedMemberFromLocalStorage : ""
  );
  const [confirmationPage, setConfirmationPage] = useState(false);
  const [editList, setEditList] = useState([]);
  const [TypeLists, setTypeLists] = useState([]);
  const [pageCount, setPageCount] = React.useState(0);
  const [dataTotal, setDataTotal] = React.useState(0);
  const navigate = useNavigate();
  const [filterEditType, setFilterEditType] = useState("");
  const [members, setMembers] = React.useState([]);

  const [TypeListsSelect, setTypeListsSelect] = useState([]);

  const getAllProducers = async () => {
    try {
      const result = await getAllMembersForManager(
        localStorage.getItem("user")
      );

      if (!result.error) {
        if (result.list.length > 0) {
          let list = result.list;

          list = list.map((row) => {
            row.user_name = row.first_name + " " + row.last_name;
            return { value: row.id, label: row.user_name };
          });

          let forSelect = [];
          if (list.length > 0) {
            list.map((row, i) => {
              forSelect.push({
                value: row.value,
                label: row?.label,
              });
            });
          }

          setMembers(forSelect);
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  useEffect(() => {
    if (selectedMemberId) {
      (async function () {
        const res = await getAllEditTypesListAPI({
          user_id: selectedMemberId,

          id: filterEditType ? parseInt(filterEditType) : null,
        });
        let list = res.list.reverse();
        setTypeListsSelect(list);
      })();
    }
  }, [selectedMemberId]);

  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;
    }
  }

  async function getData(
    pageNum,
    limitNum,
    filter = completedView ? { edit_status: 1 } : { edit_status: 2 }
  ) {
    setLoader(true);
    try {
      console.log(pageNum, limitNum);
      let res;
      if (typesView) {
        res = await getAllEditTypesListAPI({
          user_id: selectedMemberId,

          id: filterEditType ? parseInt(filterEditType) : null,
        });
        let list = res.list.reverse();
        setTypeLists(list);
      } else {
        res = await getAllEditAPI({
          producer_id: selectedMemberId,
          page: pageNum,
          limit: limitNum,

          ...filter,
          edit_type_id: filterEditType ? filterEditType : null,
        });

        let sortedList = [];

        if (completedView) {
          sortedList = res.list.sort((a, b) => {
            return new Date(b?.completed_date) - new Date(a?.completed_date);
          });
        } else {
          sortedList = res.list.sort((a, b) => {
            return new Date(a?.due_date) - new Date(b?.due_date);
          });
        }
        console.log(sortedList);
        setEditList(sortedList);
      }

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

      setPage(page);
      setPageCount(num_pages);

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

  function updatePageSize(limit) {
    (async function () {
      setPageSize(limit);
      await getData(1, limit);
    })();
    localStorage.setItem("ManagerPageSizeclientPageSize", 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
      );
    })();
  }

  React.useEffect(() => {
    (async function () {
      setLoader(true);
      await getAllProducers();
      setLoader(false);
    })();
  }, []);

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "edits",
      },
    });
    selectedMemberId && getData(currentPage, pageSize);
    localStorage.setItem("managerTypeViewEdits", typesView);
    localStorage.setItem("managerCompletedViewEdits", completedView);
    localStorage.setItem("managerPendingViewEdits", pendingView);
  }, [completedView, typesView, filterEditType, selectedMemberId]);

  console.log(filterEditType);
  return (
    <div
      className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8"
      id="mainContainer"
    >
      {openSpecialEdit && (
        <AddSpecialEdit
          userID={selectedMemberId}
          getData={getData}
          setIsOpen={setOpenSpecialEdit}
          isOpen={openSpecialEdit}
        />
      )}

      {/* Producer Selection */}

      {
        <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
          {/* Header Section */}
          <div className="sm:px-6.5 mb-6 border-b border-strokedark px-4 py-4 2xl:px-9">
            <div className="flex flex-col items-start gap-4">
              <h4 className="text-2xl font-semibold text-white dark:text-white">
                Edits
              </h4>
              <div className="w-full min-w-[220px]">
                <CustomSelect2
                  className=" w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-5 py-3 text-sm outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input"
                  value={selectedMemberId}
                  onChange={(value) => {
                    setSelectedMemberId(value);
                    localStorage.setItem("managerSelectedMemberId", value);
                  }}
                >
                  <option value="">--Select Producer--</option>
                  {members?.map((row, i) => (
                    <option key={i} value={row.value}>
                      {row.label}
                    </option>
                  ))}
                </CustomSelect2>
              </div>
            </div>
          </div>
          {!loader && selectedMemberId ? (
            <>
              <div className="sm:px-6.5 flex items-center justify-between border-b border-strokedark px-4 py-4 2xl:px-9">
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => {
                      setPendingView(true);
                      setTypesView(false);
                      setCompletedView(false);
                    }}
                    className={`rounded-md px-3 py-1 text-sm font-medium ${
                      pendingView
                        ? "bg-primary text-white"
                        : "text-white hover:bg-meta-4"
                    }`}
                  >
                    Pending
                  </button>
                  <button
                    onClick={() => {
                      setCompletedView(true);
                      setTypesView(false);
                      setPendingView(false);
                    }}
                    className={`rounded-md px-3 py-1 text-sm font-medium ${
                      completedView
                        ? "bg-primary text-white"
                        : "text-white hover:bg-meta-4"
                    }`}
                  >
                    Completed
                  </button>
                  <button
                    onClick={() => {
                      setTypesView(true);
                      setCompletedView(false);
                      setPendingView(false);
                    }}
                    className={`rounded-md px-3 py-1 text-sm font-medium ${
                      typesView
                        ? "bg-primary text-white"
                        : "text-white hover:bg-meta-4"
                    }`}
                  >
                    Types
                  </button>
                  <div className="flex items-center gap-3">
                    <CustomSelect2
                      value={filterEditType}
                      onChange={(value) => setFilterEditType(value)}
                      className="h-[36px] w-64 rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input"
                    >
                      <option value="">All Edit Types</option>
                      {TypeListsSelect.map((elem) => (
                        <option
                          key={elem.id}
                          value={elem.id}
                          className="bg-meta-4"
                        >
                          {elem.edit_type}
                        </option>
                      ))}
                    </CustomSelect2>
                  </div>
                </div>
                {typesView && (
                  <button
                    onClick={() => setOpenSpecialEdit(true)}
                    className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                  >
                    Add Special Edit +
                  </button>
                )}
              </div>

              <div className="p-4 md:p-6 2xl:p-10">
                {/* Table Content */}
                <div className="min-h-[150px]">
                  {!typesView ? (
                    <table className="w-full table-auto">
                      <thead className="bg-meta-4">
                        <tr>
                          <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1 md:pl-6 2xl:pl-9">
                            Program Name
                          </th>
                          <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1">
                            Team Name
                          </th>
                          <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1">
                            Edit Type
                          </th>
                          <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1">
                            Number of Lines
                          </th>
                          <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1">
                            Request Date
                          </th>
                          <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1">
                            Due Date
                          </th>
                        </tr>
                      </thead>
                      {editList.length > 0 ? (
                        <tbody className="cursor-pointer text-bodydark1">
                          {editList.map((elem) => (
                            <tr
                              key={elem.id}
                              className="border-b border-strokedark hover:bg-primary/5"
                            >
                              <td className="whitespace-nowrap px-4 py-4 pl-6 text-white 2xl:pl-9">
                                {elem.program_name}
                              </td>
                              <td className="whitespace-nowrap px-4 py-4">
                                {elem.team_name}
                              </td>
                              <td className="whitespace-nowrap px-4 py-4">
                                {elem.edit_type_name}
                              </td>
                              <td className="whitespace-nowrap px-4 py-4">
                                {elem?.number_of_lines}
                              </td>
                              <td className="whitespace-nowrap px-4 py-4">
                                {moment(
                                  elem?.request_date,
                                  "YYYY-MM-DD"
                                ).format("MM-DD-YYYY")}
                              </td>
                              <td className="whitespace-nowrap px-4 py-4">
                                {convertDateFormat(elem.due_date)}
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      ) : (
                        <tbody>
                          <tr></tr>
                          <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>
                      )}
                    </table>
                  ) : (
                    <TypesList TypeList={TypeLists} loading={loader} />
                  )}
                </div>

                {/* Pagination */}
                {editList.length > 0 && !typesView && !loader ? (
                  <div className="w-full px-4 py-10 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>
                ) : null}
              </div>
            </>
          ) : loader ? (
            <div className="flex h-[calc(100vh-160px)] w-full items-center justify-center">
              <ClipLoader color="#fff" size={30} />
            </div>
          ) : null}
        </div>
      }
    </div>
  );
};

export default ManagerEditsPage;
