"use client";
import SiteBreadcrumb from "@/components/site-breadcrumb";
import { Button } from "@/components/ui/button";
import ManagementUserVisualization from "@/components/visualization/management-user-viz";
import { Link, useRouter } from "@/i18n/routing";
import { PlusIcon } from "lucide-react";
import { useEffect, useState } from "react";
import Cookies from "js-cookie";
import { getCookiesDecrypt } from "@/lib/utils";
import UserInternalTable from "@/components/table/management-user/management-user-internal-table";
import UserExternalTable from "@/components/table/management-user/management-user-external-table";

export default function ManagementUser() {
  const [isInternal, setIsInternal] = useState(true);
  const [levelNumber, setLevelNumber] = useState<number | null>(null);
  const router = useRouter();

  useEffect(() => {
    const encryptedLevel = Cookies.get("ulne");
    if (encryptedLevel) {
      const decryptedLevel = getCookiesDecrypt("ulne");
      setLevelNumber(Number(decryptedLevel));
    }
  }, []);

  useEffect(() => {
    router.push("?page=1");
  }, [isInternal]);

  const showExternalButton = levelNumber !== 2 && levelNumber !== 3;

  return (
    <div>
      <SiteBreadcrumb />
      <section id="viz">
        <ManagementUserVisualization />
      </section>

      <section className="flex flex-col gap-2 bg-white dark:bg-black rounded-lg p-3 mt-5">
        <div className="flex justify-between py-3">
          <p className="text-lg">
            Data User {isInternal ? "Internal" : "Eksternal"}
          </p>
          {isInternal && (
            <Link href="/admin/management-user/internal/create">
              <Button color="primary" size="md">
                <PlusIcon />
                Add User
              </Button>
            </Link>
          )}
        </div>

        <div className="flex flex-row gap-1 border-2 rounded-md w-fit mb-5">
          <Button
            rounded="md"
            onClick={() => setIsInternal(true)}
            className={`hover:text-white ${
              !isInternal ? "bg-white text-black" : "bg-black text-white"
            }`}
          >
            User Internal
          </Button>

          {showExternalButton && (
            <Button
              rounded="md"
              onClick={() => setIsInternal(false)}
              className={`hover:text-white ${
                !isInternal ? "bg-black text-white" : "bg-white text-black"
              }`}
            >
              User Eksternal
            </Button>
          )}
        </div>

        {isInternal ? <UserInternalTable /> : <UserExternalTable />}
      </section>
    </div>
  );
}
