"use client";

import { useUserItems, ChangeUserStatus } from "@/hooks/user";
import { Suspense } from "react";
import Image from "next/image";
import Link from "next/link";
import Loader from "../../components/ui/loader.svg";
import { ChangeStatusRequest, Role } from "@/lib/interfaces";
import { Status } from "@/lib/Enums";
import { useRoleItems } from "@/hooks/role";

export default function User() {
  let refreshData: any;

  const DeleteButton = (itemId: any) => {
    return (
      <button
        className="button deleteBtn"
        value="Delete"
        onClick={async () => {
          const statusRequest: ChangeStatusRequest = {
            id: itemId.itemId,
            status: Status.Deleted,
          };
          await ChangeUserStatus(statusRequest);
          refreshData();
        }}
      >
        Delete
      </button>
    );
  };

  const ItemsData = () => {
    const { items, error, isLoading, mutate } = useUserItems();
    const {
      items: roleItems,
      error: roleError,
      isLoading: isRoleLoading,
      mutate: mutateRole,
    } = useRoleItems();
    const roleLookup = roleItems?.reduce((acc: any, role: Role) => {
      if (role && role.id != null && role.name) {
        acc[role.id] = role.name;
      }
      return acc;
    }, {});
    refreshData = mutate;
    if (!isLoading && !error && items != null) {
      return items.map((item) => (
        <tr key={item.id}>
          <td>
            <Link href={`user/${item.id}`}>{item.displayName}</Link>
          </td>
          <td>{item.email}</td>
          <td>{roleLookup[item.roleId] || [item.roleId]}</td>{" "}
          <td>{item.status}</td>
          <td>
            <div className="flex flex-nowrap">
              <Link className="button editBtn" href={`user/${item.id}`}>
                Edit
              </Link>
              <DeleteButton itemId={item.id}></DeleteButton>
            </div>
          </td>
        </tr>
      ));
    } else return Loading();
  };

  const Loading = () => (
    <tr>
      <td className="flex align-items-end" colSpan={5}>
        <Image src={Loader} alt="Loading" width={62} />
        Loading
      </td>
    </tr>
  );
  return (
    <div id="container" className="flex align-items-start place-content-center">
      <div>
        <table>
          <thead>
            <tr>
              <th colSpan={5}>
                <Link className="button" href={`user/create`}>
                  <span>Add new</span>
                </Link>
              </th>
            </tr>
            <tr>
              <th>Name</th>
              <th>Email</th>
              <th>Role</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <Suspense fallback={Loading()}>
              <ItemsData></ItemsData>
            </Suspense>
          </tbody>
        </table>
      </div>
      {process.env.PUBLIC_CERBEROS_API_URL}
    </div>
  );
}
