import Layout from "@/components/High/Layout";
import useUser from "@/hooks/useUser";
import useUsers from "@/hooks/useUsers";
import { sessionOptions } from "@/lib/session";
import useFilterStore from "@/stores/listFilterStore";
import { withIronSessionSsr } from "iron-session/next";
import Head from "next/head";
import { useRouter } from "next/router";
import { useEffect } from "react";
import { BsArrowLeft } from "react-icons/bs";
import { ToastContainer } from "react-toastify";
import UserList from "../(admin)/Lists/UserList";

export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
  const user = req.session.user;

  const envVariables: { [key: string]: string } = {};
  Object.keys(process.env)
    .filter((x) => x.startsWith("NEXT_PUBLIC"))
    .forEach((x: string) => {
      envVariables[x] = process.env[x]!;
    });

  if (!user || !user.isVerified) {
    return {
      redirect: {
        destination: "/login",
        permanent: false,
      },
    };
  }

  return {
    props: { user: req.session.user, envVariables },
  };
}, sessionOptions);

export default function UsersListPage() {
  const { user } = useUser();
  const { users } = useUsers();
  const [filters, clearFilters] = useFilterStore((state) => [
    state.userFilters,
    state.clearUserFilters,
  ]);
  const router = useRouter();

  return (
    <>
      <Head>
        <title>EnCoach</title>
        <meta
          name="description"
          content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
        />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <ToastContainer />

      {user && (
        <Layout user={user}>
          <UserList
            user={user}
            filters={filters.map((f) => f.filter)}
            renderHeader={(total) => (
              <div className="flex flex-col gap-4">
                <div
                  onClick={() => {
                    clearFilters();
                    router.back();
                  }}
                  className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
                >
                  <BsArrowLeft className="text-xl" />
                  <span>Back</span>
                </div>
                <h2 className="text-2xl font-semibold">Users ({total})</h2>
              </div>
            )}
          />
        </Layout>
      )}
    </>
  );
}
