import { cloneDeep, debounce } from "lodash";
import { useCallback, useContext, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import PaginatorComponent from "@/components/common/paginatorComponent";
import {
  useAddUser,
  useDeleteUsers,
  useGetUsers,
  useUpdateUser,
} from "@/controllers/API/queries/auth";
import CustomLoader from "@/customization/components/custom-loader";
import { useCustomNavigate } from "@/customization/hooks/use-custom-navigate";
import IconComponent from "../../components/common/genericIconComponent";
import ShadTooltip from "../../components/common/shadTooltipComponent";
import { Button } from "../../components/ui/button";
import { CheckBoxDiv } from "../../components/ui/checkbox";
import { Input } from "../../components/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../components/ui/table";
import {
  PAGINATION_PAGE,
  PAGINATION_ROWS_COUNT,
  PAGINATION_SIZE,
} from "../../constants/constants";
import { AuthContext } from "../../contexts/authContext";
import ConfirmationModal from "../../modals/confirmationModal";
import UserManagementModal from "../../modals/userManagementModal";
import useAlertStore from "../../stores/alertStore";
import type { Users } from "../../types/api";
import type { UserInputType } from "../../types/components";

export default function AdminPage() {
  const { t } = useTranslation();
  const [inputValue, setInputValue] = useState("");

  const [size, setPageSize] = useState(PAGINATION_SIZE);
  const [index, setPageIndex] = useState(PAGINATION_PAGE);
  const setSuccessData = useAlertStore((state) => state.setSuccessData);
  const setErrorData = useAlertStore((state) => state.setErrorData);
  const { userData } = useContext(AuthContext);
  const navigate = useCustomNavigate();
  const [totalRowsCount, setTotalRowsCount] = useState(0);

  const { mutate: mutateDeleteUser } = useDeleteUsers();
  const { mutate: mutateUpdateUser } = useUpdateUser();
  const { mutate: mutateAddUser } = useAddUser();

  const [userList, setUserList] = useState<Users[]>([]);

  const { mutate: mutateGetUsers, isPending, isIdle } = useGetUsers({});

  const fetchUsers = useCallback(
    (skip: number, limit: number, search?: string) => {
      mutateGetUsers(
        { skip, limit, search: search || undefined },
        {
          onSuccess: (users) => {
            setTotalRowsCount(users["total_count"]);
            setUserList(users["users"]);
          },
          onError: () => {},
        },
      );
    },
    [mutateGetUsers],
  );

  useEffect(() => {
    setTimeout(() => {
      fetchUsers(size * (index - 1), size);
    }, 500);
  }, []);

  function handleChangePagination(pageIndex: number, pageSize: number) {
    setPageSize(pageSize);
    setPageIndex(pageIndex);
    fetchUsers(pageSize * (pageIndex - 1), pageSize, inputValue);
  }

  function resetFilter() {
    setInputValue("");
    setPageIndex(PAGINATION_PAGE);
    setPageSize(PAGINATION_SIZE);
    fetchUsers(0, PAGINATION_SIZE);
  }

  const debouncedSearch = useCallback(
    debounce((search: string) => {
      setPageIndex(PAGINATION_PAGE);
      fetchUsers(0, size, search);
    }, 300),
    [size, fetchUsers],
  );

  useEffect(() => {
    return () => {
      debouncedSearch.cancel();
    };
  }, [debouncedSearch]);

  function handleFilterUsers(input: string) {
    setInputValue(input);
    debouncedSearch(input);
  }

  function handleDeleteUser(user) {
    mutateDeleteUser(
      { user_id: user.id },
      {
        onSuccess: () => {
          resetFilter();
          setSuccessData({
            title: t("success.userDeleted"),
          });
        },
        onError: (error) => {
          setErrorData({
            title: t("errors.deleteUser"),
            list: [error["response"]["data"]["detail"]],
          });
        },
      },
    );
  }

  function handleEditUser(userId, user) {
    mutateUpdateUser(
      { user_id: userId, user: user },
      {
        onSuccess: () => {
          resetFilter();
          setSuccessData({
            title: t("success.userEdited"),
          });
        },
        onError: (error) => {
          setErrorData({
            title: t("errors.editUser"),
            list: [error["response"]["data"]["detail"]],
          });
        },
      },
    );
  }

  function handleDisableUser(check, userId, user) {
    const userEdit = cloneDeep(user);
    userEdit.is_active = !check;

    mutateUpdateUser(
      { user_id: userId, user: userEdit },
      {
        onSuccess: () => {
          resetFilter();
          setSuccessData({
            title: t("success.userEdited"),
          });
        },
        onError: (error) => {
          setErrorData({
            title: t("errors.editUser"),
            list: [error["response"]["data"]["detail"]],
          });
        },
      },
    );
  }

  function handleSuperUserEdit(check, userId, user) {
    const userEdit = cloneDeep(user);
    userEdit.is_superuser = !check;

    mutateUpdateUser(
      { user_id: userId, user: userEdit },
      {
        onSuccess: () => {
          resetFilter();
          setSuccessData({
            title: t("success.userEdited"),
          });
        },
        onError: (error) => {
          setErrorData({
            title: t("errors.editUser"),
            list: [error["response"]["data"]["detail"]],
          });
        },
      },
    );
  }

  function handleNewUser(user: UserInputType) {
    mutateAddUser(user, {
      onSuccess: (res) => {
        mutateUpdateUser(
          {
            user_id: res["id"],
            user: {
              is_active: user.is_active,
              is_superuser: user.is_superuser,
            },
          },
          {
            onSuccess: () => {
              resetFilter();
              setSuccessData({
                title: t("success.userAdded"),
              });
            },
            onError: (error) => {
              setErrorData({
                title: t("errors.addUser"),
                list: [error["response"]["data"]["detail"]],
              });
            },
          },
        );
      },
      onError: (error) => {
        setErrorData({
          title: t("errors.addUser"),
          list: [error["response"]["data"]["detail"]],
        });
      },
    });
  }

  return (
    <>
      {userData && (
        <div className="admin-page-panel flex h-full flex-col pb-8">
          <div className="main-page-nav-arrangement">
            <span className="main-page-nav-title">
              <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
                <IconComponent name="ChevronLeft" className="w-5" />
              </Button>
              <IconComponent name="Shield" className="w-6" />
              {t("settings.adminTitle")}
            </span>
          </div>
          <span className="admin-page-description-text">
            {t("settings.adminDescription")}
          </span>
          <div className="flex w-full justify-between">
            <div className="flex w-96 items-center gap-4">
              <Input
                placeholder={t("admin.searchPlaceholder")}
                value={inputValue}
                onChange={(e) => handleFilterUsers(e.target.value)}
              />
              {inputValue.length > 0 ? (
                <div
                  className="cursor-pointer"
                  onClick={() => {
                    setInputValue("");
                    setPageIndex(PAGINATION_PAGE);
                    fetchUsers(0, size);
                  }}
                >
                  <IconComponent name="X" className="w-6 text-foreground" />
                </div>
              ) : (
                <div>
                  <IconComponent
                    name="Search"
                    className="w-6 text-foreground"
                  />
                </div>
              )}
            </div>
            <div>
              <UserManagementModal
                title={t("admin.newUserTitle")}
                titleHeader={t("admin.newUserHeader")}
                cancelText={t("admin.cancelButton")}
                confirmationText={t("admin.saveButton")}
                icon={"UserPlus2"}
                onConfirm={(index, user) => {
                  handleNewUser(user);
                }}
                asChild
              >
                <Button variant="primary">{t("admin.newUserButton")}</Button>
              </UserManagementModal>
            </div>
          </div>
          {(isPending || isIdle) && userList.length === 0 ? (
            <div className="flex h-full w-full items-center justify-center">
              <CustomLoader remSize={12} />
            </div>
          ) : userList.length === 0 && !isPending && !isIdle ? (
            <>
              <div className="m-4 flex items-center justify-between text-sm">
                {t("admin.noUsersRegistered")}
              </div>
            </>
          ) : (
            <div className="flex flex-1 flex-col">
              <div
                className={
                  "my-4 flex-1 overflow-x-hidden overflow-y-scroll rounded-md border bg-background custom-scroll" +
                  (isPending ? " border-0" : "")
                }
              >
                <Table className={"table-fixed outline-1"}>
                  <TableHeader
                    className={
                      isPending ? "hidden" : "table-fixed bg-muted outline-1"
                    }
                  >
                    <TableRow>
                      <TableHead className="h-10">
                        {t("admin.columnId")}
                      </TableHead>
                      <TableHead className="h-10">
                        {t("admin.columnUsername")}
                      </TableHead>
                      <TableHead className="h-10">
                        {t("admin.columnActive")}
                      </TableHead>
                      <TableHead className="h-10">
                        {t("admin.columnSuperuser")}
                      </TableHead>
                      <TableHead className="h-10">
                        {t("admin.columnCreatedAt")}
                      </TableHead>
                      <TableHead className="h-10">
                        {t("admin.columnUpdatedAt")}
                      </TableHead>
                      <TableHead className="h-10 w-[100px] text-right"></TableHead>
                    </TableRow>
                  </TableHeader>
                  {
                    <TableBody className="border-b">
                      {userList.map((user: UserInputType, index) => (
                        <TableRow key={user.id}>
                          <TableCell className="truncate py-2 font-medium">
                            <ShadTooltip content={user.id}>
                              <span className="cursor-default">{user.id}</span>
                            </ShadTooltip>
                          </TableCell>
                          <TableCell className="truncate py-2">
                            <ShadTooltip content={user.username}>
                              <span className="cursor-default">
                                {user.username}
                              </span>
                            </ShadTooltip>
                          </TableCell>
                          <TableCell className="relative left-1 truncate py-2 text-align-last-left">
                            {user.id === userData?.id ? (
                              <ShadTooltip
                                content={t("admin.cannotDeactivateSelf")}
                              >
                                <div className="flex w-fit cursor-not-allowed opacity-50">
                                  <CheckBoxDiv checked={user.is_active} />
                                </div>
                              </ShadTooltip>
                            ) : (
                              <ConfirmationModal
                                size="x-small"
                                title={t("admin.editTitle")}
                                titleHeader={`${user.username}`}
                                modalContentTitle={t("admin.attentionTitle")}
                                cancelText={t("admin.cancelButton")}
                                confirmationText={t("admin.confirmButton")}
                                icon={"UserCog2"}
                                data={user}
                                index={index}
                                onConfirm={(index, user) => {
                                  handleDisableUser(
                                    user.is_active,
                                    user.id,
                                    user,
                                  );
                                }}
                              >
                                <ConfirmationModal.Content>
                                  <span>
                                    {t("admin.editUserConfirmContent")}
                                  </span>
                                </ConfirmationModal.Content>
                                <ConfirmationModal.Trigger>
                                  <div className="flex w-fit">
                                    <CheckBoxDiv checked={user.is_active} />
                                  </div>
                                </ConfirmationModal.Trigger>
                              </ConfirmationModal>
                            )}
                          </TableCell>
                          <TableCell className="relative left-1 truncate py-2 text-align-last-left">
                            <ConfirmationModal
                              size="x-small"
                              title={t("admin.editTitle")}
                              titleHeader={`${user.username}`}
                              modalContentTitle={t("admin.attentionTitle")}
                              cancelText={t("admin.cancelButton")}
                              confirmationText={t("admin.confirmButton")}
                              icon={"UserCog2"}
                              data={user}
                              index={index}
                              onConfirm={(index, user) => {
                                handleSuperUserEdit(
                                  user.is_superuser,
                                  user.id,
                                  user,
                                );
                              }}
                            >
                              <ConfirmationModal.Content>
                                <span>{t("admin.editUserConfirmContent")}</span>
                              </ConfirmationModal.Content>
                              <ConfirmationModal.Trigger>
                                <div className="flex w-fit">
                                  <CheckBoxDiv checked={user.is_superuser} />
                                </div>
                              </ConfirmationModal.Trigger>
                            </ConfirmationModal>
                          </TableCell>
                          <TableCell className="truncate py-2">
                            {
                              new Date(user.create_at!)
                                .toISOString()
                                .split("T")[0]
                            }
                          </TableCell>
                          <TableCell className="truncate py-2">
                            {
                              new Date(user.updated_at!)
                                .toISOString()
                                .split("T")[0]
                            }
                          </TableCell>
                          <TableCell className="flex w-[100px] py-2 text-right">
                            <div className="flex">
                              <UserManagementModal
                                title={t("admin.editTitle")}
                                titleHeader={`${user.id}`}
                                cancelText={t("admin.cancelButton")}
                                confirmationText={t("admin.saveButton")}
                                icon={"UserPlus2"}
                                data={user}
                                index={index}
                                onConfirm={(index, editUser) => {
                                  handleEditUser(user.id, editUser);
                                }}
                              >
                                <ShadTooltip
                                  content={t("admin.editTitle")}
                                  side="top"
                                >
                                  <IconComponent
                                    name="Pencil"
                                    className="h-4 w-4 cursor-pointer"
                                  />
                                </ShadTooltip>
                              </UserManagementModal>

                              <ConfirmationModal
                                size="x-small"
                                title={t("admin.deleteTitle")}
                                titleHeader={t("admin.deleteUserHeader")}
                                modalContentTitle={t("admin.attentionTitle")}
                                cancelText={t("admin.cancelButton")}
                                confirmationText={t("admin.deleteTitle")}
                                icon={"UserMinus2"}
                                data={user}
                                index={index}
                                onConfirm={(index, user) => {
                                  handleDeleteUser(user);
                                }}
                              >
                                <ConfirmationModal.Content>
                                  <span>
                                    {t("admin.deleteUserConfirmContent")}
                                  </span>
                                </ConfirmationModal.Content>
                                <ConfirmationModal.Trigger>
                                  <IconComponent
                                    name="Trash2"
                                    className="ml-2 h-4 w-4 cursor-pointer"
                                  />
                                </ConfirmationModal.Trigger>
                              </ConfirmationModal>
                            </div>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  }
                </Table>
              </div>

              <div className="mt-auto">
                <PaginatorComponent
                  pageIndex={index}
                  pageSize={size}
                  totalRowsCount={totalRowsCount}
                  paginate={handleChangePagination}
                  rowsCount={PAGINATION_ROWS_COUNT}
                ></PaginatorComponent>
              </div>
            </div>
          )}
        </div>
      )}
    </>
  );
}
