"use client";

import Loading from "@/components/loading";
import IsVisible from "@/components/ui/IsVisible";
import { useGetMyNotifications } from "@/hooks/queries/useNotificationQueries";
import { TNotificationDetailsResponse } from "@/lib/api/types/NotificationHistory";
import { truncateString } from "@/utils/shared";
import { Dispatch, SetStateAction, useEffect } from "react";

interface IProps {
  setUnreadNotificationCount: Dispatch<SetStateAction<number>>;
  onNotificationClick: (notification: TNotificationDetailsResponse) => void;
}

const NotificationList = ({
  setUnreadNotificationCount,
  onNotificationClick,
}: IProps) => {
  const { data, isLoading } = useGetMyNotifications({ seen: false });
  useEffect(() => {
    setUnreadNotificationCount(data?.data.length ?? 0);
  }, [data, isLoading]);

  if (isLoading)
    return (
      <Loading className="min-h-48 flex-none justify-center p-6" />
    );

  return (
    <ul className="mb-3 max-h-[23rem] space-y-1.5 overflow-y-auto">
      <IsVisible condition={data?.data.length === 0}>
        <h2 className="cursor-default ps-2">No new notification</h2>
      </IsVisible>
      {data?.data.map((notification) => (
        <li
          role="menuitem"
          key={notification.id}
          onClick={() => onNotificationClick(notification)}
        >
          <div className="cursor-pointer rounded-lg px-1 py-2 transition-all duration-300 hover:bg-gray-2 dark:hover:bg-gray-7">
            <strong className="block text-lg font-medium capitalize text-dark dark:text-white">
              {notification.title}
            </strong>
            <span className="text-sm font-medium text-dark-5 dark:text-dark-6">
              {truncateString(notification.message, 50, 50)}
            </span>
          </div>
        </li>
      ))}
    </ul>
  );
};

export default NotificationList;
