import React from "react";
import MkdSDK from "Utils/MkdSDK";
import { useNavigate } from "react-router-dom";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext } from "Context/Global";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import * as yup from "yup";
import { getNonNullValue } from "Utils/utils";
import PaginationBar from "Components/PaginationBar";
import AddButton from "Components/AddButton";
import { SkeletonLoader } from "Components/Skeleton";
import { BiFilterAlt, BiSearch } from "react-icons/bi";
import { AiOutlineClose, AiOutlinePlus } from "react-icons/ai";
import { RiDeleteBin5Line } from "react-icons/ri";
import { ModalSidebar } from "Components/ModalSidebar";
import AddAdminUserPage from "Pages/Admin/Add/AddAdminUserPage";
import EditAdminUserPage from "Pages/Admin/Edit/EditAdminUserPage";

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 [query, setQuery] = React.useState("");
  const [data, setCurrentTableData] = React.useState([]);
  const [pageSize, setPageSize] = React.useState(10);
  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 [openFilter, setOpenFilter] = React.useState(false);
  const [showFilterOptions, setShowFilterOptions] = React.useState(false);
  const [selectedOptions, setSelectedOptions] = React.useState([]);
  const [filterConditions, setFilterConditions] = React.useState([]);
  const [searchValue, setSearchValue] = React.useState("");
  const [optionValue, setOptionValue] = React.useState("eq");
  const [loading, setLoading] = React.useState(false);
  const [showEditSidebar, setShowEditSidebar] = React.useState(false);
  const [showAddSidebar, setShowAddSidebar] = React.useState(false);
  const [activeEditId, setActiveEditId] = React.useState();
  const navigate = useNavigate();

  const schema = yup.object({
    id: yup.string(),
    email: yup.string(),
    role: yup.string(),
    status: yup.string(),
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const selectRole = ["", "admin", "employee"];
  const selectStatus = [
    { key: "", value: "All" },
    { key: "0", value: "Inactive" },
    { key: "1", value: "Active" },
    { key: "2", value: "Suspend" },
  ];

  function updatePageSize(limit) {
    (async function () {
      setPageSize(limit);
      await getData(0, 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 {
      sdk.setTable("user");
      const result = await sdk.callRestAPI(
        {
          payload: {
            ...data,
          },
          page: pageNum,
          limit: limitNum,
          filter: [...filterConditions],
        },
        "PAGINATE"
      );
      if (result) {
        setLoading(false);
      }
      const { list, total, limit, num_pages, page } = result;

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

  const onSubmit = (data) => {
    const email = getNonNullValue(data.email);
    const role = getNonNullValue(data.role);
    const status = getNonNullValue(data.status);
    const id = getNonNullValue(data.id);
    getData(0, pageSize, { email, role, status, id });
  };

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

    const delay = 700;
    const timeoutId = setTimeout(async () => {
      await getData(1, pageSize);
    }, delay);

    return () => {
      clearTimeout(timeoutId);
    };
  }, [searchValue, filterConditions, optionValue]);

  return (
    <div className="px-8">
      <div className="flex justify-between items-center py-3">
        <form
          className="relative rounded bg-brown-main-bg"
          onSubmit={handleSubmit(onSubmit)}
        >
          <div className="flex gap-4 items-center text-gray-700">
            <div
              className="flex cursor-pointer items-center justify-between gap-3 rounded-md border border-[#0003] px-3 py-1"
              onClick={() => setOpenFilter(!openFilter)}
            >
              <BiFilterAlt />
              <span>Filters</span>
              {selectedOptions.length > 0 && (
                <span className="flex justify-center items-center w-6 h-6 text-white bg-gray-800 rounded-full text-start">
                  {selectedOptions.length > 0 ? selectedOptions.length : null}
                </span>
              )}
            </div>
            <div className=" flex cursor-pointer items-center justify-between gap-3 rounded-md border border-[#0003] px-2 py-1 focus-within:border-gray-400">
              <BiSearch className="text-xl text-gray-200" />
              <input
                type="text"
                placeholder="search"
                className="p-0 border-none placeholder:text-left focus:outline-none"
                style={{ boxShadow: "0 0 transparent" }}
                onInput={(e) =>
                  addFilterCondition("name", "cs", e.target?.value)
                }
              />
              <AiOutlineClose className="text-lg text-gray-200" />
            </div>
          </div>
          {openFilter && (
            <div className="top-fill filter-form-holder bg-brown-main-bg absolute  left-0 z-20 mt-4 min-w-[70%] rounded-md border border-[#0003] p-5 shadow-xl">
              {selectedOptions?.map((option, index) => (
                <div
                  key={index}
                  className="flex gap-3 justify-between items-center mb-2 w-full text-gray-600"
                >
                  <div className="px-3 py-2 mb-3 w-1/3 leading-tight text-gray-700 rounded-md border outline-none border-black/60">
                    {option}
                  </div>
                  <select
                    className="w-[30%] appearance-none border-none outline-0"
                    onChange={(e) => {
                      setOptionValue(e.target.value);
                    }}
                  >
                    <option value="eq" selected>
                      equals
                    </option>
                    <option value="cs">contains</option>
                    <option value="sw">start with</option>
                    <option value="ew">ends with</option>
                    <option value="lt">lower than</option>
                    <option value="le">lower or equal</option>
                    <option value="ge">greater or equal</option>
                    <option value="gt">greater than</option>
                    <option value="bt">between</option>
                    <option value="in">in</option>
                    <option value="is">is null</option>
                  </select>

                  <input
                    type="text"
                    placeholder="Enter value"
                    className="px-3 py-2 mb-3 w-1/3 leading-tight text-gray-700 rounded-md border outline-none"
                    onChange={(e) =>
                      addFilterCondition(option, optionValue, e.target.value)
                    }
                  />
                  {/* <p className="text-xs italic text-red-500">
                         {errors.id?.message}
                       </p> */}

                  <RiDeleteBin5Line
                    className="text-xl cursor-pointer"
                    onClick={() => {
                      setSelectedOptions((prevOptions) =>
                        prevOptions.filter((op) => op !== option)
                      );
                      setFilterConditions((prevConditions) => {
                        return prevConditions.filter(
                          (condition) => !condition.includes(option)
                        );
                      });
                    }}
                  />
                </div>
              ))}

              <div className="flex relative justify-between items-center font-semibold search-buttons">
                <div
                  // type="submit"
                  className="bg-brown-main-bg mr-2 flex w-auto cursor-pointer items-center gap-2 rounded px-4 py-2.5 font-medium leading-tight text-gray-600 transition duration-150 ease-in-out "
                  onClick={() => {
                    setShowFilterOptions(!showFilterOptions);
                  }}
                >
                  <AiOutlinePlus />
                  Add filter
                </div>

                {showFilterOptions && (
                  <div className="absolute top-11 z-10 px-5 py-3 text-gray-600 shadow-md bg-brown-main-bg">
                    <ul className="flex flex-col gap-2 text-gray-500">
                      {columns.slice(0, -1).map((column) => (
                        <li
                          key={column.header}
                          className={`${
                            selectedOptions.includes(column.header)
                              ? "cursor-not-allowed text-gray-400"
                              : "cursor-pointer"
                          }`}
                          onClick={() => {
                            if (!selectedOptions.includes(column.header)) {
                              setSelectedOptions((prev) => [
                                ...prev,
                                column.header,
                              ]);
                            }
                            setShowFilterOptions(false);
                          }}
                        >
                          {column.header}
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
                {selectedOptions.length > 0 && (
                  <div
                    // type="reset"
                    onClick={() => {
                      setSelectedOptions([]);
                      setFilterConditions([]);
                    }}
                    className="inline-block cursor-pointer  rounded px-6  py-2.5 font-medium leading-tight text-gray-600  transition duration-150 ease-in-out"
                  >
                    Clear all filter
                  </div>
                )}
              </div>
            </div>
          )}
        </form>
        <AddButton onClick={() => setShowAddSidebar(true)} />
      </div>
      {loading ? (
        <SkeletonLoader />
      ) : (
        <div className="overflow-x-auto shadow">
          <table className="min-w-full divide-y divide-[#1f1d1a]/10">
            <thead>
              <tr>
                {columns.map((column, index) => (
                  <th
                    key={index}
                    scope="col"
                    className="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase"
                  >
                    {column.header}
                    <span>
                      {column.isSorted
                        ? column.isSortedDesc
                          ? " ▼"
                          : " ▲"
                        : ""}
                    </span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="font-iowan-regular divide-y divide-[#1f1d1a]/10">
              {data.map((row, i) => {
                return (
                  <tr className="  md:h-[60px]" key={i}>
                    {columns.map((cell, index) => {
                      if (cell.accessor == "") {
                        return (
                          <td
                            key={index}
                            className="px-6 py-4 whitespace-nowrap"
                          >
                            <button
                              className="text-[#4F46E5]"
                              onClick={() => {
                                setActiveEditId(row.id);
                                setShowEditSidebar(true);
                                // navigate("/admin/edit-user/" + row.id, {
                                //   state: row,
                                // });
                              }}
                            >
                              {" "}
                              Edit
                            </button>
                          </td>
                        );
                      }
                      if (cell.mapping && cell.accessor === "status") {
                        return (
                          <td
                            key={index}
                            className="px-6 py-4 text-sm whitespace-nowrap"
                          >
                            {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="px-6 py-4 whitespace-nowrap"
                          >
                            {cell.mapping[row[cell.accessor]]}
                          </td>
                        );
                      }
                      return (
                        <td key={index} className="px-6 py-4 whitespace-nowrap">
                          {row[cell.accessor]}
                        </td>
                      );
                    })}
                  </tr>
                );
              })}
            </tbody>
          </table>
          {loading && (
            <>
              <p className="px-10 py-3 text-xl capitalize">Loading...</p>
            </>
          )}
          {!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;
