"use server";
import React from "react";
import Link from "next/link";
import { redirect } from "next/navigation";
import { RefreshCcw, PlusCircle } from "lucide-react";
import {
  decryptQuery,
  defaultPagination,
  handleFormSubmission,
} from "@/apicalls/test";
import { TableComponent } from "@/components/commons/Table";
import Pagination from "@/components/commons/pagination";
import MainBodyWithHeader from "@/components/defaultLayout/MainBodyWithHeader";
import {
  createBuild,
  retrieveBuildList,
  updateBuild,
} from "@/apicalls/building/build";
import {
  checkAccessTokenIsValid,
  retrieveUserSelection,
} from "@/apicalls/cookies/token";
import { retrievePageInfoByComponentName } from "@/hooks/retrievePageInfoByComponentName";
import { checkPageAvaliable } from "@/hooks/checkpageAvaliable";

const BuildinPage = async ({ searchParams }: { searchParams: any }) => {
  const buildKey = "building";
  const pageName = "BuildingPage";
  const searchParamsKeys = await searchParams;

  if (!searchParamsKeys?.q) {
    const defaultURL = await defaultPagination();
    redirect(`/${buildKey}?q=${defaultURL}`);
  }
  const queryEncrypt = await decryptQuery(searchParamsKeys?.q);
  if (!(await checkAccessTokenIsValid())) {
    redirect("/login/email");
  }
  const user = await retrieveUserSelection();

  const tableValues = {
    endpoint: "building/build/list",
    name: "table",
    url: "/building",
    function: retrieveBuildList,
    data: [],
    headers: {},
    validation: {},
  };
  const createValues = {
    endpoint: "building/build/create",
    name: "create",
    url: "/building/create",
    function: createBuild,
    data: [],
    headers: {},
    validation: {},
  };
  const updateValues = {
    endpoint: "building/build/update/{build_uu_id}",
    function: updateBuild,
    name: "update",
    url: "/building/update",
    data: [],
    headers: {},
    validation: {},
  };

  let restrictions: any = {
    update: updateValues,
    create: createValues,
    table: tableValues,
  };

  if (!user?.lang) {
    return (
      <MainBodyWithHeader
        children={<h1>User selection is not successfully retrieved.</h1>}
      />
    );
  } else {
    const pageContent = retrievePageInfoByComponentName(pageName, user?.lang);
    const restrictionsChecked = await checkPageAvaliable({
      pageContent,
      restrictions,
      queryEncrypt,
    });

    if (!restrictionsChecked || !restrictionsChecked?.table) {
      return (
        <MainBodyWithHeader
          children={<h1>This user does not have access to this page.</h1>}
        />
      );
    }

    const BuildingPage = (
      <div className="p-4 overflow-hidden">
        <h1 className="text-2xl font-bold mb-4 ">Dashboard</h1>
        <form
          action={handleFormSubmission}
          className="bg-white p-4 rounded-lg shadow"
        >
          <div className="grid gap-4">
            <p>Welcome to your dashboard</p>
            {restrictionsChecked?.create && (
              <Link
                href={"/building/create"}
                className="flex items-center justify-center gap-2 px-4 py-2 bg-slate-500 text-white rounded hover:bg-slate-700"
              >
                <PlusCircle size={16} />
                Create
              </Link>
            )}
            <h1>{JSON.stringify(queryEncrypt)}</h1>

            {restrictionsChecked && (
              <div>
                <input type="hidden" name="section" value={buildKey} readOnly />
                <TableComponent
                  pageContent={pageContent}
                  tableValidateAndHeaders={restrictionsChecked?.table}
                  apiFunction={retrieveBuildList}
                  redirectTo={"/building/update"}
                />
              </div>
            )}

            <button
              type="submit"
              className="flex items-center justify-center gap-2 px-4 py-2 bg-slate-500 text-white rounded hover:bg-slate-700"
            >
              <RefreshCcw size={16} />
              Search
            </button>
            <Pagination
              size={parseInt(queryEncrypt?.size || "10")}
              page={parseInt(queryEncrypt?.page || "1")}
              orderBy={queryEncrypt?.orderBy || "id"}
              orderType={queryEncrypt?.orderType || "asc"}
              totalPage={3}
            />
          </div>
        </form>
      </div>
    );
    return (
      <>
        <MainBodyWithHeader
          children={BuildingPage}
          section={`/${buildKey}`}
          profileInfo={user}
        />
      </>
    );
  }
};

export default BuildinPage;
