/* eslint-disable react-hooks/rules-of-hooks */
"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import Image from "next/image";
import NotificationCard from "@/components/notification";
import axios from "@/utils/axios-config";
import NotificationSkeleton from "@/components/skeletons/skeleton-notification";
import { useDispatch } from "react-redux";
import {
  fetchNotificationFailure,
  fetchNotificationLength,
  fetchNotificationSuccess,
} from "@/store/notification/actions";

export default function Notification() {
  const t = useTranslations();
  const [notifications, setnotifications] = useState<any>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const dispatch = useDispatch();

  useEffect(() => {
    const fetchNotificationsData = async () => {
      try {
        const response = await axios.get("/notifications");
        const data = await response?.data;
        setnotifications(data?.data || []);
        
        

        dispatch(fetchNotificationLength(response?.headers['x-unreadnotification-count']));
        dispatch(fetchNotificationSuccess(data?.data));
        console.log("notification array", data?.data);
      } catch (err) {
        setError("Failed to fetch notifications.");
        dispatch(fetchNotificationFailure((err as Error).message));
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchNotificationsData();
  }, []);

  return (
    <div className="pt-[2rem]">
      <div className="container mx-auto py-8 px-4">
        <h2 className="text-[#184363] text-[20px] sm:text-3xl md:text-3xl font-bold mb-4 sm:mb-6">
          {t("Notifications")}
        </h2>
        {/* Show loading skeleton */}
        {loading ? <NotificationSkeleton /> : null}

        {/* Show error message */}
        {/* {error ? (
          <p className="text-center mt-10 text-red-500">{error}</p>
        ) : null} */}
        {notifications.length > 0 ? (
          <div className="space-y-4">
            {notifications.map((notification: any) => (
              <NotificationCard key={notification.id} {...notification} />
            ))}
          </div>
        ) : !loading && notifications.length == 0 ? (
          // Show "No notification available" message
          <div className="flex flex-col items-center justify-center h-[500px] text-center bg-white">
            <div className="relative w-72 h-48 mb-6 max-[500px]:h-36">
              <Image
                src="/images/notify.png"
                alt="404 Not Found"
                layout="fill"
                objectFit="contain"
              />
            </div>

            <h1 className="lg:text-3xl md:text-3xl sm:text-xl text-lg font-bold text-gray-900">
              {t("No-notify")}
            </h1>
          </div>
        ) : null}
      </div>
    </div>
  );
}
