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 RequestEdit1 from "Components/Client/RequestEdit1";
// import RequestEdit2 from "Components/Client/RequestEdit2";
import { GlobalContext } from "Src/globalContext";
import {
  getAllEditAPI,
  getAllEditTypesListAPI,
} from "Src/services/editService";
import { retrieveAllUserAPI } from "Src/services/userService";
import moment from "moment";
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router";
import { ClipLoader } from "react-spinners";

const AdminEditsPage = () => {
  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("adminPageSizeEdit");
  const [pageSize, setPageSize] = React.useState(
    pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : 30 // Default pageSize
  );
  const pendingViewFromLocalStorage = localStorage.getItem(
    "adminPendingViewEdits"
  );
  const completedViewFromLocalStorage = localStorage.getItem(
    "adminCompletedViewEdits"
  );
  const typeViewFromLocalStorage = localStorage.getItem("adminTypeViewEdits");
  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 [confirmationPage, setConfirmationPage] = useState(false);
  const selectedMemberFromLocalStorage = localStorage.getItem(
    "adminSelectedMemberId"
  );
  const [selectedMemberId, setSelectedMemberId] = React.useState(
    selectedMemberFromLocalStorage ? selectedMemberFromLocalStorage : ""
  );
  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 retrieveAllUsers = async () => {
    try {
      let filter = {
        role: "member",
      };
      const result = await retrieveAllUserAPI(1, 10000, filter);
      if (!result.error) {
        if (result.list.length > 0) {
          let list = result.list;
          // concat first_name and last_name into user_name
          // then sort by ascending order of user_name
          list = list.map((row) => {
            row.user_name = row.first_name + " " + row.last_name;
            return row;
          });
          list = list.sort((a, b) => {
            return a.user_name.localeCompare(b.user_name);
          });

          setMembers(list);
        }
      }
    } 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]);

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

        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("adminPageSizeclientPageSize", 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 retrieveAllUsers();
      setLoader(false);
    })();
  }, []);

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

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "edits",
      },
    });
    selectedMemberId && getData(currentPage, pageSize);

    localStorage.setItem("adminTypeViewEdits", typesView);
    localStorage.setItem("adminCompletedViewEdits", completedView);
    localStorage.setItem("adminPendingViewEdits", pendingView);
  }, [completedView, typesView, filterEditType, selectedMemberId, pendingView]);

  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}
        />
      )}

      {/* Main Container */}
      <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
                label="Producer"
                placeholder="Select Producer"
                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("adminSelectedMemberId", value);
                }}
              >
                <option value="">--Select Producer--</option>
                {members &&
                  members.length > 0 &&
                  members.map((row, i) => (
                    <option key={i} value={row.id}>
                      {row.user_name}
                    </option>
                  ))}
              </CustomSelect2>
            </div>
          </div>
        </div>

        {!loader && selectedMemberId ? (
          <>
            {/* Filter Section */}
            <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
                    label="Edit Type"
                    placeholder="Select Edit Type"
                    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>

            {/* Edit Type Filter */}
            <div className="sm:px-6.5 px-4 py-4 2xl:px-9">
              {/* Table Content */}
              <div className="min-h-[200px]">
                {!typesView ? (
                  <table className="w-full table-auto">
                    <thead className="bg-meta-4">
                      <tr>
                        <th
                          scope="col"
                          className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white"
                        >
                          Program Name
                        </th>
                        <th
                          scope="col"
                          className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white"
                        >
                          Team Name
                        </th>

                        <th
                          scope="col"
                          className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white"
                        >
                          Edit Type
                        </th>
                        <th
                          scope="col"
                          className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white"
                        >
                          #Number Of lines
                        </th>
                        <th
                          scope="col"
                          className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white"
                        >
                          Requested Date
                        </th>
                        <th
                          scope="col"
                          className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white"
                        >
                          Due Date
                        </th>
                      </tr>
                    </thead>
                    <tbody className="cursor-pointer text-white">
                      {editList.map((elem) => (
                        <tr
                          onClick={() =>
                            navigate(
                              `/admin/view-edit/${elem.id}/${elem.project_id}`
                            )
                          }
                        >
                          <td className="whitespace-nowrap px-4 py-4">
                            <span>{elem.program_name}</span>
                          </td>
                          <td className="whitespace-nowrap px-4 py-4">
                            <span>{elem.team_name}</span>
                          </td>
                          <td className="whitespace-nowrap px-4 py-4">
                            <span>{elem.edit_type_name}</span>
                          </td>{" "}
                          <td className="whitespace-nowrap px-4 py-4">
                            <span>{elem?.number_of_lines}</span>
                          </td>
                          <td className="whitespace-nowrap px-4 py-4">
                            <span>
                              {" "}
                              {moment(elem?.request_date, "YYYY-MM-DD").format(
                                "MM-DD-YY"
                              )}
                            </span>
                          </td>{" "}
                          <td className="whitespace-nowrap px-4 py-4">
                            <span>{convertDateFormat(elem.due_date)}</span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                ) : (
                  <TypesList TypeList={TypeLists} />
                )}
              </div>

              {/* Pagination */}
              {!typesView && editList.length > 0 && !loader && (
                <div className="mt-6">
                  <PaginationBar
                    currentPage={currentPage}
                    pageCount={pageCount}
                    pageSize={pageSize}
                    canPreviousPage={canPreviousPage}
                    canNextPage={canNextPage}
                    updatePageSize={updatePageSize}
                    previousPage={previousPage}
                    nextPage={nextPage}
                    dataTotal={dataTotal}
                    setCurrentPage={setPage}
                  />
                </div>
              )}
            </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 AdminEditsPage;
