import Spinner from "Components/Spinner";
import React from "react";
import Skeleton from "react-loading-skeleton";
import { useNavigate } from "react-router-dom";
import { AuthContext, tokenExpireError } from "../../authContext";
import AddButton from "../../components/AddButton";
import { GlobalContext } from "../../globalContext";
import MkdSDK from "../../utils/MkdSDK";

let sdk = new MkdSDK();

const columns = [
  {
    header: "ID",
    accessor: "id",
  },
  {
    header: "Email Type",
    accessor: "slug",
  },
  {
    header: "Subject",
    accessor: "subject",
  },
  {
    header: "Tags",
    accessor: "tag",
  },
];

const ManagerEmailListPage = () => {
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [currentTableData, setCurrentTableData] = React.useState([]);
  const [loadingData, setLoadingData] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const navigate = useNavigate();

  async function getData() {
    try {
      sdk.setTable("email");
      const result = await sdk.callRestAPI({}, "GETALL");
      const { list } = result;
      setCurrentTableData(list);
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  }

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

    (async function () {
      setLoadingData(true);
      await getData();
      setLoadingData(false);
    })();
  }, []);

  return (
    <>
      <div className="overflow-x-auto rounded border-gray-500 bg-gray-800 p-5 shadow">
        <div className="mb-3 flex w-full flex-row justify-between">
          <h4 className="text-2xl font-medium text-white">Emails </h4>
          <AddButton link={"/admin/add-email"} />
        </div>
        <div className="overflow-x-auto rounded-md border-b border-gray-200 shadow">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-900">
              <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-white"
                  >
                    {column.header}
                    <span>
                      {column.isSorted
                        ? column.isSortedDesc
                          ? " ▼"
                          : " ▲"
                        : ""}
                    </span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="cursor-pointer divide-y divide-gray-100 bg-neutral-950 text-white">
              {loading && <Spinner />}
              {currentTableData.length === 0 ? (
                <tr>
                  <td colSpan={5}>{loadingData && <Skeleton count={10} />}</td>
                </tr>
              ) : null}
              {currentTableData.map((row, i) => {
                return (
                  <tr
                    key={i}
                    className="hover:bg-gray-800"
                    onClick={() => {
                      navigate(`/admin/edit-email/` + row.id, {
                        state: row,
                      });
                    }}
                  >
                    {columns.map((cell, index) => {
                      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>
        </div>
      </div>
    </>
  );
};

export default ManagerEmailListPage;
