import React from "react";
import { AuthContext, tokenExpireError } from "../authContext";
import MkdSDK from "../utils/MkdSDK";
import { useNavigate } from "react-router-dom";
import { GlobalContext } from "../globalContext";
import AddButton from "../components/AddButton";
import { ClipLoader } from "react-spinners";

let sdk = new MkdSDK();

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

const AdminEmailListPage = () => {
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [currentTableData, setCurrentTableData] = React.useState([]);
  const [loadingData, setLoadingData] = 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="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8">
      <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
        {/* Header Section */}
        <div className="flex items-center justify-between border-b border-strokedark px-4 md:px-6 2xl:px-9">
          <h4 className="my-3 text-2xl font-semibold text-white dark:text-white">
            Emails
          </h4>
          <AddButton link={"/admin/add-email"} />
        </div>

        {/* Table Section */}
        <div>
          <div className="custom-overflow min-h-[150px] overflow-x-auto">
            <table className="w-full table-auto">
              <thead className="bg-meta-4">
                <tr>
                  {columns.map((column, i) => (
                    <th
                      key={i}
                      className={`whitespace-nowrap px-3 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1 ${
                        i === 0 ? "xl:pl-6 2xl:pl-9" : ""
                      }`}
                    >
                      {column.header}
                    </th>
                  ))}
                </tr>
              </thead>

              {!loadingData && currentTableData.length > 0 ? (
                <tbody className="cursor-pointer text-white">
                  {currentTableData.map((row, i) => (
                    <tr
                      key={i}
                      onClick={() => {
                        navigate(`/admin/edit-email/${row.id}`, {
                          state: row,
                        });
                      }}
                      className="border-b border-strokedark hover:bg-primary/5"
                    >
                      {columns.map((cell, index) => (
                        <td
                          key={index}
                          className={`whitespace-nowrap px-3 py-4 ${
                            index === 0
                              ? "text-bodydark1 xl:pl-6 2xl:pl-9"
                              : "text-bodydark"
                          }`}
                        >
                          {cell.mapping
                            ? cell.mapping[row[cell.accessor]]
                            : row[cell.accessor]}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              ) : loadingData ? (
                <tbody>
                  <tr>
                    <td colSpan={columns.length} className="text-center">
                      <span className="trans relative top-[30px] m-4 animate-pulse whitespace-nowrap p-4 pb-8 text-xl font-semibold text-white ease-out">
                        <ClipLoader color="#fff" size={20} className="mr-3" />{" "}
                        Loading Emails...
                      </span>
                    </td>
                  </tr>
                </tbody>
              ) : (
                <tbody>
                  <tr>
                    <td colSpan={columns.length} className="text-center">
                      <span className="relative top-[10px] m-4 p-4 font-semibold text-white">
                        No data found
                      </span>
                    </td>
                  </tr>
                </tbody>
              )}
            </table>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AdminEmailListPage;
