import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { PaginationBar } from "@/components/PaginationBar";
import { MkdButton } from "@/components/MkdButton";
import { BiSearch } from "react-icons/bi";
import { AiOutlineClose } from "react-icons/ai";
import { ModalSidebar } from "@/components/ModalSidebar";
import {
  AddAdminSowTablePage,
  AddAdminWireframeTablePage,
} from "@/routes/LazyLoad";

import { ModalPrompt } from "@/components/Modal";
import { DropdownOption } from "@/components/DropdownOptions/DropdownOption";
import {
  CaptureSpatialIcon,
  EditIcon,
  KebabIcon,
  RobotIcon,
  TrashIcon,
} from "@/assets/svgs";
import { MkdPopover } from "@/components/MkdPopover";
import { LazyLoad } from "@/components/LazyLoad";
import { useContexts } from "@/hooks/useContexts";
import { useSDK } from "@/hooks/useSDK";

function formatDate(date) {
  const newDate = new Date(date);
  const year = newDate.getFullYear();
  const month = (newDate.getMonth() + 1).toString().padStart(2, "0");
  const day = newDate.getDate().toString().padStart(2, "0");
  return `${year}-${month}-${day}`;
}

const columns = [
  {
    header: "Name",
    accessor: "name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Created Date",
    accessor: "create_at",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Updated Date",
    accessor: "update_at",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Action",
    accessor: "",
  },
];

const SowListPage = () => {
  const { sdk, tdk } = useSDK();
  const {
    globalDispatch,
    authDispatch: dispatch,
    tokenExpireError,
  } = useContexts();
  const [currentTableData, setCurrentTableData] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [pageCount, setPageCount] = useState(0);
  const [currentPage, setPage] = useState(1);
  const [canPreviousPage, setCanPreviousPage] = useState(false);
  const [canNextPage, setCanNextPage] = useState(false);
  const [filterConditions, setFilterConditions] = useState([]);
  const [searchValue, setSearchValue] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [showAddSidebar, setShowAddSidebar] = useState(false);
  const [showAddWireframeSidebar, setShowAddWireframeSidebar] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [deleteID, setDeleteID] = useState("");
  const [sowToAddToWireframe, setSowToAddToWireframe] = useState(null);
  const [initialLoad, setInitialLoad] = useState(true);
  const navigate = useNavigate();

  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(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) {
    setIsLoading(true);

    try {
      let sortField = columns.filter((col) => col.isSorted);
      const result = await tdk.getPaginate("sow", "super_admin", {
        // payload: { ...currentTableData },
        page: pageNum,
        size: limitNum,
        order: sortField.length ? sortField[0].accessor : "",
        direction: sortField.length
          ? sortField[0].isSortedDesc
            ? "DESC"
            : "ASC"
          : "",
        filter: [...filterConditions],
      });

      const { list, limit, num_pages, page } = result;
      setCurrentTableData(list);
      setPageSize(limit);
      setPageCount(num_pages);
      setPage(page);
      setCanPreviousPage(page > 1);
      setCanNextPage(page + 1 <= num_pages);
      setInitialLoad(false);
    } catch (error) {
      tokenExpireError(error.message);
    }
    setIsLoading(false);
  }

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

  React.useEffect(() => {
    if (!showAddSidebar) {
      getData(1, pageSize, filterConditions);
    }

    if (!showAddWireframeSidebar) {
      setSowToAddToWireframe(null);
    }
  }, [showAddSidebar, showAddWireframeSidebar, filterConditions]);

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

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

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

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

  if (initialLoad) {
    return <SowFullPageSkeletonLoader />;
  }

  return (
    <div className="px-8">
      <div className="flex items-center justify-between gap-2 py-3">
        <div className="flex w-[auto] items-center gap-4 text-gray-700 md:!w-[12.5rem] ">
          <div className="flex w-full 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="w-full 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>

      {isLoading ? (
        <SowTableSkeletonLoader />
      ) : (
        <div className="my-1 overflow-x-auto overflow-y-hidden 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.indexOf("name") > -1) {
                        return (
                          <td
                            onClick={() => {
                              navigate("/admin/requirement/" + row.id, {
                                state: row,
                              });
                            }}
                            key={index}
                            className="cursor-pointer whitespace-nowrap px-6 py-4 hover:font-bold"
                          >
                            {row[cell.accessor]}
                          </td>
                        );
                      }

                      if (cell.accessor === "update_at") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {formatDate(row[cell.accessor])}
                          </td>
                        );
                      }

                      if (cell.accessor == "") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            <div
                              className={
                                isModalOpen
                                  ? "hidden"
                                  : "items center relative flex"
                              }
                            >
                              <LazyLoad>
                                <MkdPopover
                                  display={<KebabIcon />}
                                  tooltipClasses="!right-[3.25rem] !rounded-md !border"
                                  place={"left"}
                                >
                                  <LazyLoad>
                                    <DropdownOption
                                      icon={
                                        <EditIcon className="mr-1 h-6 w-6" />
                                      }
                                      name={"Edit"}
                                      onClick={() => {
                                        navigate(
                                          "/admin/requirement/" + row.id,
                                          {
                                            state: row,
                                          }
                                        );
                                      }}
                                    />
                                  </LazyLoad>
                                  <LazyLoad>
                                    <DropdownOption
                                      icon={
                                        <RobotIcon className="mr-1 h-6 w-6" />
                                      }
                                      name={"Ask GPT"}
                                      onClick={() => {
                                        navigate("/admin/ask-gpt/" + row.id, {
                                          state: row,
                                        });
                                      }}
                                    />
                                  </LazyLoad>

                                  <LazyLoad>
                                    <DropdownOption
                                      icon={
                                        <CaptureSpatialIcon className="mr-1 h-6 w-6" />
                                      }
                                      name={"Make Build"}
                                      onClick={() => {
                                        setSowToAddToWireframe(row.id);
                                        setShowAddWireframeSidebar(true);
                                      }}
                                    />
                                  </LazyLoad>
                                  <LazyLoad>
                                    <DropdownOption
                                      icon={
                                        <TrashIcon className="mr-1 h-6 w-6" />
                                      }
                                      name={"Delete"}
                                      onClick={() => openModal(row.id)}
                                    />
                                  </LazyLoad>
                                </MkdPopover>
                              </LazyLoad>
                            </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)}
      >
        <AddAdminSowTablePage setSidebar={setShowAddSidebar} />
      </ModalSidebar>

      <ModalSidebar
        isModalActive={showAddWireframeSidebar}
        closeModalFn={() => setShowAddWireframeSidebar(false)}
      >
        <AddAdminWireframeTablePage
          setSidebar={setShowAddWireframeSidebar}
          sowToAddToWireframe={sowToAddToWireframe}
          showAddSidebar={showAddSidebar}
        />
      </ModalSidebar>
      {isModalOpen && (
        <ModalPrompt
          open={isModalOpen}
          actionHandler={handleDelete}
          closeModalFunction={closeModal}
          title={`Are you sure?`}
          message={`Are you sure you want to delete SOW table? `}
          acceptText={`Delete`}
          rejectText={`Cancel`}
        />
      )}
    </div>
  );
};

export default SowListPage;

const SowFullPageSkeletonLoader = () => (
  <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="h-9 w-64 rounded-md bg-gray-200"></div>
      </div>
      <div className="h-9 w-32 rounded-md bg-gray-200"></div>
    </div>

    <div className="overflow-x-auto border-b border-gray-200 shadow">
      <div className="min-w-full divide-y divide-gray-200">
        <div className="bg-gray-50">
          <div className="flex">
            {columns.map((_, i) => (
              <div key={i} className="flex-1 px-6 py-3">
                <div className="h-5 w-24 rounded bg-gray-300"></div>
              </div>
            ))}
          </div>
        </div>
        <div className="divide-y divide-gray-200 bg-white">
          {[...Array(10)].map((_, rowIndex) => (
            <div key={rowIndex} className="flex">
              {columns.map((_, cellIndex) => (
                <div key={cellIndex} className="flex-1 px-6 py-4">
                  <div className="h-5 w-full rounded bg-gray-200"></div>
                </div>
              ))}
            </div>
          ))}
        </div>
      </div>
    </div>

    <div className="flex items-center justify-between py-3">
      <div className="h-8 w-32 rounded bg-gray-200"></div>
      <div className="flex items-center gap-2">
        <div className="h-8 w-8 rounded bg-gray-200"></div>
        <div className="h-8 w-16 rounded bg-gray-200"></div>
        <div className="h-8 w-16 rounded bg-gray-200"></div>
        <div className="h-8 w-8 rounded bg-gray-200"></div>
      </div>
    </div>
  </div>
);

const SowTableSkeletonLoader = () => (
  <div className="animate-pulse space-y-4 py-1">
    <div className="overflow-x-auto overflow-y-hidden rounded-lg border border-gray-200">
      <div className="min-w-full divide-y divide-gray-200">
        <div className="bg-gray-50">
          <div className="flex">
            {columns.map((_, i) => (
              <div key={i} className="flex-1 px-4 py-4">
                <div className="h-4 w-24 rounded bg-gray-300"></div>
              </div>
            ))}
          </div>
        </div>
        <div className="divide-y divide-gray-200 bg-white">
          <div className="h-0"></div>
          {[...Array(10)].map((_, rowIndex) => (
            <div key={rowIndex} className="flex">
              {columns.map((_, cellIndex) => (
                <div key={cellIndex} className="flex-1 px-4 py-5">
                  <div className="h-4 w-full rounded bg-gray-200"></div>
                </div>
              ))}
            </div>
          ))}
        </div>
      </div>
    </div>
  </div>
);
