"use client";

import React, { useEffect, useRef, useState } from "react";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
import { Button } from "../ui/button";
import { Bell } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { ScrollArea } from "../ui/scroll-area";
import { useSession } from "next-auth/react";
import {
  ListAllNotifications,
  updateNotificationRead,
} from "@/app/services/api/login-api";
import Link from "next/link";
import { socket } from "@/lib/SocketProvider";
import { toast } from "../ui/use-toast";
type Res = {
  message: string;
  data: ResData[];
  status: boolean;
};

type ResData = {
  body: string;
  branchName: string;
  productName: string;
  data: NotiData;
  title: string;
  status: "read" | "unread";
  type: string;
  _id: string;
};

type NotiData = {
  branchId: string;
  createdAt: string;
  productId: string;
  quantity: number;
  updatedAt: string;
  __v: number;
  _id: string;
};

export default function NotificationComp() {
  const [newNotificationsCount, setNewNotificationsCount] = useState(0);
  const [notifications, setNotifications] = useState<ResData[] | null>(null);
  const bellRef = useRef<HTMLButtonElement>(null);
  const { data: session } = useSession();
  const [isOpen, setIsOpen] = useState(false);

  // function checkunread(notification: ResData) {
  //   return notification.status === "unread";
  // }
  // useEffect(() => {
  //   const Noti = async () => {
  //     if (session?.user.accessToken) {
  //       const data = await ListAllNotifications(
  //         session?.user.accessToken as string
  //       );
  //       setNotifications(data.data);
  //       const unread = notifications?.find(checkunread);
  //       if (unread) {
  //         setNewNotificationsCount((prevCount) => prevCount + 1);
  //       }
  //     }
  //   };
  //   Noti();
  // }, [session]);
  function checkUnread(notification: ResData): boolean {
    return notification.status === "unread";
  }

  useEffect(() => {
    const fetchNotifications = async () => {
      try {
        // Early return if no access token
        if (!session?.user.accessToken) return;

        // Fetch notifications
        const response = await ListAllNotifications(session.user.accessToken);

        // Update notifications state
        const fetchedNotifications = response.data || [];
        setNotifications(fetchedNotifications);

        // Count unread notifications more efficiently
        const unreadCount = fetchedNotifications.filter(checkUnread).length;
        setNewNotificationsCount(unreadCount);
      } catch (error) {
        // Error handling
        console.error("Failed to fetch notifications:", error);
        // Optionally, set an error state or show a user-friendly error message
      }
    };

    // Only fetch if session exists
    if (session?.user.accessToken) {
      fetchNotifications();
    }
  }, [session?.user.accessToken]); // More specific dependency

  useEffect(() => {
    socket.on("admin_notification", (data: ResData) => {
      setNewNotificationsCount((prevCount) => prevCount + 1);
      setNotifications((prevNotifications) =>
        prevNotifications ? [data, ...prevNotifications] : [data]
      );
    });
    return () => {
      socket.off("admin_notification");
    };
  }, []);

  const handleOpenChange = (open: boolean) => {
    setIsOpen(open);
    if (open) {
      setNewNotificationsCount(0);
    }
  };
  const handleRead = async (id: string) => {
    // Create a new array with the updated notification status
    const updatedNotifications =
      notifications?.map((notification) =>
        notification._id === id
          ? { ...notification, status: "read" as const }
          : notification
      ) || null;

    // Update the state with the new notifications array
    setNotifications(updatedNotifications);
    await updateNotificationRead(session?.user.accessToken as string, id);
  };

  return (
    <Popover open={isOpen} onOpenChange={handleOpenChange}>
      <PopoverTrigger asChild>
        <Button
          ref={bellRef}
          variant="ghost"
          size="icon"
          className="relative"
          aria-label={`Open notifications${
            newNotificationsCount > 0 ? `, ${newNotificationsCount} new` : ""
          }`}
        >
          <Bell className="h-5 w-5 text-[#be063f] fill-[#be063f]" />
          {newNotificationsCount > 0 && (
            <span className="absolute top-0 right-0 h-2 w-2 mt-1.5 mr-2 bg-red-500 rounded-full flex items-center justify-center text-white text-xs">
              {/* {newNotificationsCount} */}
            </span>
          )}
          <span className="sr-only">Open notifications</span>
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-80 p-0" align="end">
        <Card className="border-none">
          <CardHeader className=" p-4 mb-2">
            <CardTitle className="text-sm flex pb-2 justify-center border-b">
              Notifications
            </CardTitle>
          </CardHeader>
          <ScrollArea className="h-[300px] px-4">
            <CardContent className="space-y-4 p-0 pb-4">
              {notifications && notifications?.length <= 0 && (
                <div className="h-full flex items-center justify-center ">
                  No Notifications
                </div>
              )}
              {notifications?.map((notification: ResData) => (
                <Link
                  onClick={() => handleRead(notification._id)}
                  key={notification._id}
                  href={
                    notification.type === "urgent-requests"
                      ? `/${notification.type}?branchName=${notification.branchName}&productName=${notification.productName}`
                      : notification.type === "order"
                      ? `/order-management/${notification.data._id}`
                      : notification.type === "chat"
                      ? `/chat?branchId=${notification.data.branchId}`
                      : "/dashboard"
                  }
                >
                  <div
                    className={`last:pb-0 border-b border-white last:border-b-0 p-1 ${
                      notification.status === "read"
                        ? ""
                        : "bg-gray-200 rounded-md"
                    }`}
                  >
                    <h3
                      className={`${
                        notification.status === "read"
                          ? "font-medium"
                          : "font-semibold"
                      }`}
                    >
                      {notification.title}
                    </h3>
                    <p className={`text-sm text-muted-foreground pl-2`}>
                      {notification.body}
                    </p>
                    <div className="border border-b-1 mt-2 mb-2" />
                  </div>
                </Link>
              ))}
            </CardContent>
          </ScrollArea>
        </Card>
      </PopoverContent>
    </Popover>
  );
}
