import React from "react";
import MkdSDK from "@/utils/MkdSDK";
import { AuthContext, tokenExpireError } from "@/context/Auth";
import { GlobalContext } from "@/context/Global";
import { PaginationBar } from "@/components/PaginationBar";
import { MkdButton } from "@/components/MkdButton";
import { Skeleton } from "@/components/Skeleton";
import { BiSearch } from "react-icons/bi";
import { AiOutlineClose } from "react-icons/ai";
import { ModalSidebar } from "@/components/ModalSidebar";
import { AddAdminUserPage, EditAdminUserPage } from "@/src/routes/LazyLoad";
import TreeSDK from "@/utils/TreeSDK";

let sdk = new MkdSDK();

const columns = [
  {
    header: "Email",
    accessor: "email",
  },
  {
    header: "Role",
    accessor: "role",
  },
  {
    header: "Status",
    accessor: "status",
    mapping: ["Inactive", "Active", "Suspend"],
  },
  {
    header: "Action",
    accessor: "",
  },
];
const AdminUserListPage = () => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const { dispatch } = React.useContext(AuthContext);
  const [data, setCurrentTableData] = React.useState([]);
  const [pageSize, setPageSize] = React.useState(10);
  const [pageCount, setPageCount] = React.useState(0);
  const [currentPage, setPage] = React.useState(1);
  const [canPreviousPage, setCanPreviousPage] = React.useState(false);
  const [canNextPage, setCanNextPage] = React.useState(false);
  const [filterConditions, setFilterConditions] = React.useState([]);
  const [searchValue, setSearchValue] = React.useState("");
  const [loading, setLoading] = React.useState(true);
  const [showEditSidebar, setShowEditSidebar] = React.useState(false);
  const [showAddSidebar, setShowAddSidebar] = React.useState(false);
  const [activeEditId, setActiveEditId] = React.useState();

  function updatePageSize(limit) {
    (async function () {
      setPageSize(limit);
      await getData(1, limit);
    })();
  }
  function previousPage() {
    (async function () {
      await getData(currentPage - 1 > 0 ? currentPage - 1 : 0, pageSize);
    })();
  }

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

  const addFilterCondition = (option, selectedValue, inputValue) => {
    const input =
      selectedValue === "eq" && isNaN(inputValue)
        ? `"${inputValue}"`
        : inputValue;
    const condition = `${option},${selectedValue},${input}`;
    setFilterConditions((prevConditions) => {
      const newConditions = prevConditions.filter(
        (condition) => !condition.includes(option)
      );
      return [...newConditions, condition];
    });
    setSearchValue(inputValue);
  };

  async function getData(pageNum, limitNum, data) {
    setLoading(true);
    try {
      let tdk = new TreeSDK();
      let sortField = columns.filter((col) => col.isSorted);
      const result = await tdk.getPaginate("user", {
        // payload: { ...currentTableData },
        page: pageNum,
        size: limitNum,
        order: sortField.length ? sortField[0].accessor : "",
        direction: sortField.length
          ? sortField[0].isSortedDesc
            ? "DESC"
            : "ASC"
          : "",
        filter: [...filterConditions],
      });

      if (!result.error) {
        setLoading(false);
        const { list, limit, num_pages, page } = result;
        setCurrentTableData(list);
        setPageSize(limit);
        setPageCount(num_pages);
        setPage(page);
        setCanPreviousPage(page > 1);
        setCanNextPage(page + 1 <= num_pages);
      }
    } catch (error) {
      setLoading(false);
      console.log("ERROR", error);
      tokenExpireError(dispatch, error.message);
    }
  }

  React.useEffect(() => {
    (async function () {
      await getData(1, pageSize);
    })();
  }, [filterConditions]);

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

  return (
    <div className="px-8">
      <div className="flex items-center justify-between py-3">
        <div className="flex items-center gap-4 text-gray-700">
          <div className=" flex cursor-pointer items-center justify-between gap-3 rounded-md border border-gray-200 px-2 py-1 focus-within:border-gray-400">
            <BiSearch className="text-xl text-gray-200" />
            <input
              type="text"
              placeholder="search..."
              className="border-none p-0 placeholder:text-left  focus:outline-none"
              style={{ boxShadow: "0 0 transparent" }}
              value={searchValue}
              onInput={(e) =>
                addFilterCondition("email", "cs", e.target?.value)
              }
            />
            <AiOutlineClose
              onClick={() => addFilterCondition("email", "cs", "")}
              className="text-lg text-gray-400 hover:text-gray-700"
            />
          </div>
        </div>
        <MkdButton onClick={() => setShowAddSidebar(true)} />
      </div>
      {loading ? (
        <Skeleton />
      ) : (
        <div className="overflow-x-auto border-b border-gray-200 shadow ">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                {columns.map((column, index) => (
                  <th
                    key={index}
                    scope="col"
                    className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
                  >
                    {column.header}
                    <span>
                      {column.isSorted
                        ? column.isSortedDesc
                          ? " ▼"
                          : " ▲"
                        : ""}
                    </span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200 bg-white">
              {data.map((row, i) => {
                return (
                  <tr key={i}>
                    {columns.map((cell, index) => {
                      if (cell.accessor == "") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            <button
                              className="text-[#4F46E5]"
                              onClick={() => {
                                setActiveEditId(row.id);
                                setShowEditSidebar(true);
                              }}
                            >
                              {" "}
                              Edit
                            </button>
                          </td>
                        );
                      }
                      if (cell.mapping && cell.accessor === "status") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4 text-sm"
                          >
                            {row[cell.accessor] === 1 ? (
                              <span className="rounded-md bg-[#D1FAE5] px-3 py-1 text-[#065F46]">
                                {cell.mapping[row[cell.accessor]]}
                              </span>
                            ) : (
                              <span className="rounded-md bg-[#F4F4F4] px-3 py-1 text-[#393939]">
                                {cell.mapping[row[cell.accessor]]}
                              </span>
                            )}
                          </td>
                        );
                      }
                      if (cell.mapping) {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {cell.mapping[row[cell.accessor]]}
                          </td>
                        );
                      }
                      return (
                        <td key={index} className="whitespace-nowrap px-6 py-4">
                          {row[cell.accessor]}
                        </td>
                      );
                    })}
                  </tr>
                );
              })}
            </tbody>
          </table>
          {!loading && data.length === 0 && (
            <p className=" px-10 py-3 text-xl capitalize ">
              You Don't have any User
            </p>
          )}
        </div>
      )}
      <PaginationBar
        currentPage={currentPage}
        pageCount={pageCount}
        pageSize={pageSize}
        canPreviousPage={canPreviousPage}
        canNextPage={canNextPage}
        updatePageSize={updatePageSize}
        previousPage={previousPage}
        nextPage={nextPage}
      />
      <ModalSidebar
        isModalActive={showAddSidebar}
        closeModalFn={() => setShowAddSidebar(false)}
      >
        <AddAdminUserPage setSidebar={setShowAddSidebar} />
      </ModalSidebar>
      <ModalSidebar
        isModalActive={showEditSidebar}
        closeModalFn={() => setShowEditSidebar(false)}
      >
        <EditAdminUserPage
          activeId={activeEditId}
          setSidebar={setShowEditSidebar}
        />
      </ModalSidebar>
    </div>
  );
};

export default AdminUserListPage;
