import React from "react";
import { AuthContext, tokenExpireError } from "@/context/Auth";
import BaasSDK from "@/utils/BaasSDK";
import { GlobalContext } from "@/context/Global";
import { PaginationBar } from "@/components/PaginationBar";
import { Skeleton as SkeletonLoader } from "@/components/Skeleton";
import { BiSearch } from "react-icons/bi";
import { AiOutlineClose } from "react-icons/ai";
import { ModalSidebar } from "@/components/ModalSidebar";
import { ViewAdminDeploymentTablePage } from "@/src/routes/LazyLoad";

let baasSdk = new BaasSDK();

const columns = [
  {
    header: "Name",
    accessor: "project_id",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },

  {
    header: "Domain ID",
    accessor: "domain_id",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Frontend Deployed",
    accessor: "fe_deployed",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: true,
    mappings: {
      0: "Inactive",
      1: "Active",
    },
  },
  {
    header: "Backend Deployed",
    accessor: "be_deployed",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: true,
    mappings: {
      0: "Inactive",
      1: "Active",
    },
  },
  {
    header: "Action",
    accessor: "",
  },
];

export default function ListAdminDeploymentTablePage() {
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [currentTableData, 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 [showViewSidebar, setShowViewSidebar] = React.useState(false);
  const [activeViewId, setActiveViewId] = React.useState();
  const [loading, setLoading] = React.useState(true);
  function onSort(columnIndex) {
    console.log(columns[columnIndex]);
    if (columns[columnIndex].isSorted) {
      columns[columnIndex].isSortedDesc = !columns[columnIndex].isSortedDesc;
    } else {
      columns.map((i) => (i.isSorted = false));
      columns.map((i) => (i.isSortedDesc = false));
      columns[columnIndex].isSorted = true;
    }

    (async function () {
      await getData(1, pageSize);
    })();
  }

  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, currentTableData) {
    setLoading(true);
    try {
      let sortField = columns.filter((col) => col.isSorted);

      baasSdk.setTable("deployment");
      const result = await baasSdk.callRestAPI(
        {
          payload: { ...currentTableData },
          page: pageNum,
          limit: limitNum,
          sortId: sortField.length ? sortField[0].accessor : "",
          direction: sortField.length
            ? sortField[0].isSortedDesc
              ? "DESC"
              : "ASC"
            : "",
          filter: [...filterConditions],
        },
        "PAGINATE"
      );
      const { list, limit, num_pages, page } = result;

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

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

    (async function () {
      await getData(1, pageSize);
    })();
  }, [filterConditions]);

  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("name", "cs", e.target?.value)}
            />
            <AiOutlineClose
              onClick={() => addFilterCondition("name", "cs", "")}
              className="text-lg text-gray-200"
            />
          </div>
        </div>
      </div>
      {loading ? (
        <SkeletonLoader />
      ) : (
        <>
          <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, i) => (
                    <th
                      key={i}
                      scope="col"
                      className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
                      onClick={() => onSort(i)}
                    >
                      {column.header}
                      <span>
                        {column.isSorted
                          ? column.isSortedDesc
                            ? " ▼"
                            : " ▲"
                          : ""}
                      </span>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 bg-white">
                {currentTableData.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="px-1 text-xs text-[#4F46E5]"
                                onClick={() => {
                                  setActiveViewId(row.id);
                                  setShowViewSidebar(true);
                                }}
                              >
                                View
                              </button>
                            </td>
                          );
                        }
                        if (
                          cell.mappings &&
                          [ "fe_deployed", "be_deployed"].includes(
                            cell.accessor
                          )
                        ) {
                          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.mappings[row[cell.accessor]]}
                                </span>
                              ) : (
                                <span className="rounded-md bg-[#F4F4F4] px-3 py-1 text-[#393939]">
                                  {cell.mappings[row[cell.accessor]]}
                                </span>
                              )}
                            </td>
                          );
                        }
                        if (cell.mappingExist) {
                          return (
                            <td
                              key={index}
                              className="whitespace-nowrap px-6 py-4"
                            >
                              {cell.mappings[row[cell.accessor]]}
                            </td>
                          );
                        }

                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {row[cell.accessor]}
                          </td>
                        );
                      })}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          <PaginationBar
            currentPage={currentPage}
            pageCount={pageCount}
            pageSize={pageSize}
            canPreviousPage={canPreviousPage}
            canNextPage={canNextPage}
            updatePageSize={updatePageSize}
            previousPage={previousPage}
            nextPage={nextPage}
          />{" "}
        </>
      )}
      <ModalSidebar
        isModalActive={showViewSidebar}
        closeModalFn={() => setShowViewSidebar(false)}
      >
        <ViewAdminDeploymentTablePage
          activeId={activeViewId}
          setSidebar={setShowViewSidebar}
        />
      </ModalSidebar>
    </div>
  );
}
