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 { removeKeysWhenValueIsNull } 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 MemberEditsPage = () => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const { dispatch, state: authState } = React.useContext(AuthContext);

  const [loader2, setLoader2] = useState(false);

  const [currentPage, setPage] = React.useState(0);
  const [canPreviousPage, setCanPreviousPage] = React.useState(false);
  const [canNextPage, setCanNextPage] = React.useState(false);
  const pageSizeFromLocalStorage = localStorage.getItem("MemberPageSizeEdit");
  const [pageSize, setPageSize] = React.useState(
    pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : 30 // Default pageSize
  );
  const pendingViewFromLocalStorage = localStorage.getItem(
    "memberPendingViewEdits"
  );
  const completedViewFromLocalStorage = localStorage.getItem(
    "memberCompletedViewEdits"
  );
  const typeViewFromLocalStorage = localStorage.getItem("memberTypeViewEdits");
  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 [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 [TypeListsSelect, setTypeListsSelect] = useState([]);
  const [isLoading, setIsLoading] = React.useState(false);

  const location = useLocation();

  const getPendingEdits = async () => {
    const res = await getAllEditAPI({
      producer_id: localStorage.getItem("user"),
      page: 1,
      limit: 50000,

      edit_status: 2,
    });

    globalDispatch({
      type: "SET_CURRENT_PENDING_LENGTH",
      payload: { pendingLength: res?.list?.length || 0 },
    });
  };

  useEffect(() => {
    getPendingEdits();
  }, [location.pathname]);

  useEffect(() => {
    (async function () {
      const res = await getAllEditTypesListAPI({
        user_id: localStorage.getItem("user"),

        id: filterEditType ? parseInt(filterEditType) : null,
      });

      let list = res.list.reverse();
      console.log(res.list, list);
      setTypeListsSelect(list);
    })();
  }, []);

  async function getData(
    pageNum,
    limitNum,
    filter = completedView ? { edit_status: 1 } : { edit_status: 2 }
  ) {
    setIsLoading(true);
    try {
      console.log(pageNum, limitNum);
      let res;
      if (typesView) {
        res = await getAllEditTypesListAPI(
          removeKeysWhenValueIsNull({
            user_id: localStorage.getItem("user"),

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

            ...filter,
            edit_type_name: 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;

      list.length === 0 ? setPage(0) : setPage(page);
      setPageCount(num_pages);
      setDataTotal(total);
      setCanPreviousPage(page > 1);
      setCanNextPage(page + 1 <= num_pages);

      setIsLoading(false);
    } catch (error) {
      console.log(error);
      setIsLoading(false);
      tokenExpireError(dispatch, error.message);
    }
  }

  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;
    }
  }
  function updatePageSize(limit) {
    (async function () {
      setLoader2(true);
      setPageSize(limit);
      await getData(1, limit);
      setLoader2(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth",
      });
    })();
    localStorage.setItem("MemberPageSizeEdit", limit);
  }

  function previousPage() {
    (async function () {
      setLoader2(true);
      await getData(
        currentPage - 1,
        pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : pageSize
      );
      setLoader2(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth",
      });
    })();
  }

  function nextPage() {
    (async function () {
      setLoader2(true);
      await getData(
        currentPage + 1,
        pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : pageSize
      );
      setLoader2(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth",
      });
    })();
  }

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "edits",
      },
    });
    getData(currentPage, pageSize);
    localStorage.setItem("memberTypeViewEdits", typesView);
    localStorage.setItem("memberCompletedViewEdits", completedView);
    localStorage.setItem("memberPendingViewEdits", pendingView);
  }, [completedView, typesView, filterEditType, pendingView]);

  console.log(completedView, typesView, pendingView);
  return (
    <div
      className="p-4 h-full max-w-screen md:p-4 lg:p-6 xl:p-8"
      id="mainContainer"
    >
      {/* Remove standalone loader2 spinner since we'll handle loading states in the table */}

      <div className="rounded border shadow-default border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
        {/* Header Section - Matching ListWorkOrderPage structure */}
        <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);
                    setTypesView(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);
                    setTypesView(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>
                <button
                  onClick={() => {
                    setTypesView(true);
                    setPendingView(false);
                    setCompletedView(false);
                  }}
                  className={`rounded-md px-3 py-1 text-sm font-medium ${
                    typesView
                      ? "text-white bg-primary"
                      : "text-white hover:bg-meta-4"
                  }`}
                >
                  Types
                </button>

                <div className="flex gap-3 items-center">
                  <CustomSelect2
                    value={filterEditType}
                    onChange={(value) => setFilterEditType(value)}
                    className="border-form-sstrokedark h-[36px] w-64 rounded border-[1.5px] bg-form-input px-3 py-2 text-sm outline-none transition placeholder:font-normal placeholder:font-normal placeholder:text-bodydark placeholder:text-bodydark focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary"
                  >
                    <option value="">All Edit Types</option>
                    {TypeListsSelect.map((elem) => (
                      <option
                        key={elem.id}
                        value={elem.edit_type}
                        className="bg-meta-4"
                      >
                        {elem.edit_type}
                      </option>
                    ))}
                  </CustomSelect2>
                </div>
              </div>
            </div>
            {/* <button
              onClick={() => setOpenSpecialEdit(true)}
              className="inline-flex 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>

        <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-xs font-medium tracking-wider text-left uppercase text-bodydark1 md:pl-6 2xl:pl-9">
                      Program Name
                    </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">
                      Edit Type
                    </th>
                    <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                      Number of Lines
                    </th>
                    <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase 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>
                {!isLoading && editList.length > 0 ? (
                  <tbody className="cursor-pointer text-bodydark1">
                    {editList.map((elem) => (
                      <tr
                        key={elem.id}
                        onClick={() =>
                          navigate(
                            `/member/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.edit_type_name}</span>
                        </td>
                        <td className="px-4 py-4 whitespace-nowrap">
                          <span>{elem?.number_of_lines}</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>
                ) : isLoading && editList.length === 0 ? (
                  <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>
                ) : !isLoading && 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>
                ) : (
                  isLoading && (
                    <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>
            </>
          ) : (
            <TypesList TypeList={TypeLists} loading={isLoading} />
          )}
        </div>

        {/* Pagination */}
        {editList.length > 0 && !typesView && !isLoading ? (
          <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>
        ) : null}
      </div>
    </div>
  );
};

export default MemberEditsPage;
