"use client"
import { NotificationsIcon } from "@/assets/svgs/Icons";
import React, { useEffect, useState } from "react";
import EmptyContent from "./EmptyContent";
import AppDrawer from "@/components/UiComponents/drawers/AppDrawer";
import { useTranslations } from "next-intl";
import { getNotifications, markAllAsNotificationsRead, markAsNotificationRead } from "@/services/ClientApiHandler";
import toast from "react-hot-toast";
import ImageWithFallback from "@/components/UiComponents/ImageWithFallback";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "@/store/store";
import { setNotificationsModal } from "@/store/general";
import { useRouter } from "next/navigation";
import AppSkeleton from "@/components/UiComponents/Loader/AppSkeleton";
import { Spin } from "antd"; // Ensure Spin is imported from Ant Design
import { ArrowDown, ArrowUp } from "lucide-react";

const NotificationsDrawer = () => {
  const [notifications, setNotifications] = React.useState<any[]>([]);
  const [loading, setLoading] = React.useState<boolean>(true);
  const [page, setPage] = useState(1);
  const [lastPage, setLastPage] = useState(1);
  const t = useTranslations();
  const isOpen = useSelector((state: RootState) => state.generalConfig.notificationsModal);
  const { refetch } = useSelector((state: RootState) => state.socketConfig);
  const { token } = useSelector((state: RootState) => state.ProfileConfig);
  const dispatch = useDispatch<AppDispatch>();
  const router = useRouter();

  const fetchNotifications = async (page: number) => {
    try {
      setLoading(true);
      const { notifications: newNotifications, meta } = await getNotifications(page);

      if (page === 1) {
        setNotifications(newNotifications);
      } else {
        setNotifications((prev) => [...prev, ...newNotifications]); 
      }
      setLastPage(meta.last_page); 
    } catch (error: any) {
      toast.error(error?.response?.data?.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (token) {
      fetchNotifications(page);
    }
  }, [token, refetch, page]);

  const handleMarkAll = async () => {
    try {
      const res = await markAllAsNotificationsRead();
      if (res?.status == "success") {
        setNotifications((prev) =>
          prev.map((item) => ({ ...item, is_readed: true })))
      }
    } catch (error: any) {
      toast.error(error?.response?.data?.message);
    }
  };

  const handleMarkRead = async (notification: any) => {
    try {
      if (!notification?.is_readed) {
        const res = await markAsNotificationRead(notification.id);
        if (res?.status == "success") {
          setNotifications((prev) =>
            prev.map((item) => item.id === notification.id ? { ...item, is_readed: true } : item)
          );
        }
      }
      if (notification.type === "chat") {
        router.push(`/messages?chat_id=${notification.notifiable_id}`);
      } else if (notification.type == "wallet") {
        router.push(`/account/wallet`);
      } else if (notification.type === "buyer_return") {
        router.push(`/account/returns/${notification.notifiable_id}`);
      }else if (notification.type === "buyer_order") {
        router.push(`/account/orders/${notification.notifiable_id}`);
      } else if (notification.type === "order") {
        router.push(`/received-orders/${notification.notifiable_id}`);
      }else if (notification.type === "return") {
        router.push(`/returns/${notification.notifiable_id}`);
      }
      dispatch(setNotificationsModal(false));
    } catch (error: any) {
      toast.error(error?.response?.data?.message);
    }
  };

  const renderGetMoreButton = () => {
    if (page < lastPage) {
      return (
        <Spin spinning={loading}>
          <button
            disabled={loading}
            onClick={() => setPage(prev => prev + 1)}
            className="w-full flex flex-col items-center justify-center gap-1 text-text-gray font-semibold text-sm mt-10"
          >
            <ArrowDown className="size-4" />
            {t("Text.getMoreNotifications")}
          </button>
        </Spin>
      );
    }
    return null;
  };

  return (
    <>
      <button onClick={() => dispatch(setNotificationsModal(true))} className="relative">
        <div className="bg-error w-2 h-2 rounded-full absolute top-2 start-2 lg:top-[.9rem] lg:start-[16px]" />
        <NotificationsIcon className="bg-greynormal size-10 rounded-xl p-3 lg:p-4 lg:size-[52px]" />
      </button>
      <AppDrawer
        title={
          <div className="flex items-center justify-between">
            <h5 className="text-2xl font-bold">
              {t("Text.notifications")}
            </h5>
            {notifications.length > 0 && (
              <button onClick={handleMarkAll} className="text-sm text-primary underline font-semibold">{t("Text.seen_mark")}</button>
            )}
          </div>
        }
        placement="left"
        open={isOpen}
        handleClose={() => dispatch(setNotificationsModal(false))}
        rootClassName="notifications-drawer-container"
      >
        {notifications.length ? (
          <div className="overflow-auto max-h-[calc(100vh-10rem)]">
            <ul className="space-y-4">
              {notifications.map((item) => (
                <li
                  key={`notifications_${item?.id}`}
                  onClick={() => handleMarkRead(item)}
                  className={`flex items-center gap-4 p-4 rounded-2xl text-gray-500 ${item?.is_readed ? "bg-white" : "bg-greynormal"} cursor-pointer`}
                >
                  <figure className="size-12 flex-center-content rounded-full bg-[#3512390D]">
                    {item?.icon ? (
                      <ImageWithFallback
                        src={item?.icon}
                        width={100}
                        height={100}
                        alt={item?.title}
                        className="size-5"
                      />
                    ) : <NotificationsIcon />}
                  </figure>
                  <div className="flex-1 flex items-center justify-between">
                    <div className="space-y-3">
                      <h6 className="font-bold text-text-gray">{item?.title}</h6>
                      <p className="text-sm font-semibold">{item?.created_at}</p>
                    </div>
                    {!item?.is_readed && (
                      <span className="size-2.5 bg-primary rounded-full"></span>
                    )}
                  </div>
                </li>
              ))}
              {loading && [...Array(10)].map((_, index) => <AppSkeleton key={index} width="100%" height="80px" />)}
            </ul>
            {renderGetMoreButton()}
          </div>
        ) : <EmptyContent />}
      </AppDrawer>
    </>
  );
};

export default NotificationsDrawer;
