import React from "react";
import { AuthContext, tokenExpireError } from "@/context/Auth";
import MkdSDK from "@/utils/MkdSDK";
import BaasSDK from "@/utils/BaasSDK";
import { GlobalContext, showToast } from "@/context/Global";
import { PaginationBar } from "@/components/PaginationBar";
import { MkdButton } from "@/components/MkdButton";
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 {
  AddAdminProjectTablePage,
  EditAdminProjectTablePage,
  ViewAdminProjectTablePage,
} from "@/src/routes/LazyLoad";
import { ModalPrompt } from "@/components/Modal";

let sdk = new MkdSDK();
let baasSdk = new BaasSDK();

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

  {
    header: "Slug",
    accessor: "slug",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },

  {
    header: "Secret",
    accessor: "secret",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },

  {
    header: "Api Deploy Status",
    accessor: "api_deploy_status",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },

  {
    header: "Frontend Deploy Status",
    accessor: "frontend_deploy_status",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },

  {
    header: "Action",
    accessor: "",
  },
];

const ProjectListPage = () => {
  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 [loading, setLoading] = React.useState(false);
  const [searchValue, setSearchValue] = React.useState("");
  const [filterConditions, setFilterConditions] = React.useState([]);
  const [showEditSidebar, setShowEditSidebar] = React.useState(false);
  const [showAddSidebar, setShowAddSidebar] = React.useState(false);
  const [showViewSidebar, setShowViewSidebar] = React.useState(false);
  const [activeEditId, setActiveEditId] = React.useState();
  const [activeViewId, setActiveViewId] = React.useState();
  const [isModalOpen, setIsModalOpen] = React.useState(false);
  const [deleteID, setDeleteID] = React.useState("");

  function onSort(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(0, pageSize);
    })();
  }

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

      const filters = searchValue.length
        ? { ...currentTableData }
        : { ...currentTableData };

      baasSdk.setTable("projects");
      const result = await baasSdk.callRestAPI(
        {
          payload: { ...filters },
          page: pageNum,
          limit: limitNum,
          sortId: sortField.length ? sortField[0].accessor : "",
          direction: sortField.length
            ? sortField[0].isSortedDesc
              ? "DESC"
              : "ASC"
            : "",
        },
        "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);
    }
  }

  const deleteItem = async (id) => {
    try {
      sdk.setTable("project");
      await sdk.callRestAPI({ id }, "DELETE");
      setCurrentTableData((list) =>
        list.filter((x) => Number(x.id) !== Number(id))
      );
    } catch (err) {
      throw new Error(err);
    }
  };

  const openModal = (id) => {
    setIsModalOpen(true);
    setDeleteID(id);
  };

  const handleDelete = () => {
    deleteItem(deleteID);
    setIsModalOpen(false);
  };

  const closeModal = () => {
    setIsModalOpen(false);
  };

  function copyToClipboard(text) {
    navigator.clipboard.writeText(text);
    showToast(globalDispatch, "Copied to clipboard");
  }

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

  React.useEffect(() => {
    if (!showEditSidebar && !showAddSidebar) {
      (async function () {
        await getData(1, pageSize);
      })();
    }
  }, [showEditSidebar, showAddSidebar, searchValue]);

  const selectStatus = [
    { key: "", value: "All" },
    { key: "0", value: "Inactive" },
    { key: "1", value: "Active" },
  ];

  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-400 hover:text-gray-700"
            />
          </div>
        </div>
        <MkdButton onClick={() => setShowAddSidebar(true)} />
      </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="text-xs text-[#4F46E5]"
                                onClick={() => {
                                  setActiveEditId(row.id);
                                  setShowEditSidebar(true);
                                }}
                              >
                                Edit
                              </button>
                              <button
                                className="px-1 text-xs text-[#4F46E5]"
                                onClick={() => {
                                  setActiveViewId(row.id);
                                  setShowViewSidebar(true);
                                }}
                              >
                                View
                              </button>
                              <button
                                className="px-1 text-xs text-[#8D8D8D]"
                                onClick={() => openModal(row.id)}
                              >
                                Delete
                              </button>
                            </td>
                          );
                        }
                        if (cell.accessor === "secret") {
                          return (
                            <td
                              key={index}
                              className="whitespace-nowrap px-6 py-4"
                            >
                              <div className="flex w-full items-center justify-between">
                                <span>{row[cell.accessor]} </span>
                                <span
                                  className="cursor-pointer"
                                  onClick={() =>
                                    copyToClipboard(row[cell.accessor])
                                  }
                                >
                                  <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    width="20"
                                    height="20"
                                    viewBox="0 0 20 20"
                                    fill="none"
                                  >
                                    <g clipPath="url(#clip0_948_1315)">
                                      <path
                                        d="M6.66663 6.6665V4.33317C6.66663 3.39975 6.66663 2.93304 6.84828 2.57652C7.00807 2.26292 7.26304 2.00795 7.57664 1.84816C7.93316 1.6665 8.39987 1.6665 9.33329 1.6665H15.6666C16.6 1.6665 17.0668 1.6665 17.4233 1.84816C17.7369 2.00795 17.9918 2.26292 18.1516 2.57652C18.3333 2.93304 18.3333 3.39975 18.3333 4.33317V10.6665C18.3333 11.5999 18.3333 12.0666 18.1516 12.4232C17.9918 12.7368 17.7369 12.9917 17.4233 13.1515C17.0668 13.3332 16.6 13.3332 15.6666 13.3332H13.3333M4.33329 18.3332H10.6666C11.6 18.3332 12.0668 18.3332 12.4233 18.1515C12.7369 17.9917 12.9918 17.7368 13.1516 17.4232C13.3333 17.0666 13.3333 16.5999 13.3333 15.6665V9.33317C13.3333 8.39975 13.3333 7.93304 13.1516 7.57652C12.9918 7.26292 12.7369 7.00795 12.4233 6.84816C12.0668 6.6665 11.6 6.6665 10.6666 6.6665H4.33329C3.39987 6.6665 2.93316 6.6665 2.57664 6.84816C2.26304 7.00795 2.00807 7.26292 1.84828 7.57652C1.66663 7.93304 1.66663 8.39975 1.66663 9.33317V15.6665C1.66663 16.5999 1.66663 17.0666 1.84828 17.4232C2.00807 17.7368 2.26304 17.9917 2.57664 18.1515C2.93316 18.3332 3.39987 18.3332 4.33329 18.3332Z"
                                        stroke="#8D8D8D"
                                        stroke-width="1.5"
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                      />
                                    </g>
                                    <defs>
                                      <clipPath id="clip0_948_1315">
                                        <rect
                                          width="20"
                                          height="20"
                                          fill="white"
                                        />
                                      </clipPath>
                                    </defs>
                                  </svg>
                                </span>
                              </div>
                            </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={showAddSidebar}
        closeModalFn={() => setShowAddSidebar(false)}
      >
        <AddAdminProjectTablePage setSidebar={setShowAddSidebar} />
      </ModalSidebar>
      <ModalSidebar
        isModalActive={showEditSidebar}
        closeModalFn={() => setShowEditSidebar(false)}
      >
        <EditAdminProjectTablePage
          activeId={activeEditId}
          setSidebar={setShowEditSidebar}
        />
      </ModalSidebar>
      <ModalSidebar
        isModalActive={showViewSidebar}
        closeModalFn={() => setShowViewSidebar(false)}
      >
        <ViewAdminProjectTablePage
          activeId={activeViewId}
          setSidebar={setShowViewSidebar}
        />
      </ModalSidebar>
      {isModalOpen && (
        <ModalPrompt
          actionHandler={handleDelete}
          closeModalFunction={closeModal}
          title={`Are you sure?`}
          message={`Are you sure you want to delete this project? `}
          acceptText={`Delete`}
          rejectText={`Cancel`}
        />
      )}
    </div>
  );
};

export default ProjectListPage;
