"use client";

import { useEffect, useRef, useState } from "react";
import { Bell } from "lucide-react";
import { useNotifications } from "@/hooks/useNotifications";
import i18n from "@/lib/i18n";
import { timeAgo } from "@/lib/format";

export function NotificationDropdown() {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const { notifications, isLoading, fetchNotifications, markAsRead, unreadCount } = useNotifications();

  // Fetch on mount
  useEffect(() => {
    fetchNotifications();
  }, [fetchNotifications]);

  // Refetch whenever the dropdown opens
  useEffect(() => {
    if (isOpen) {
      fetchNotifications();
    }
  }, [isOpen, fetchNotifications]);

  // Close on outside click
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="relative h-9 w-9 inline-flex items-center justify-center rounded-lg hover:bg-muted transition"
      >
        <Bell className="h-[18px] w-[18px] text-muted-foreground" />
        {unreadCount > 0 && (
          <span className="absolute top-1.5 right-1.5 flex h-2 w-2">
            <span className="absolute inline-flex h-full w-full rounded-full bg-destructive opacity-70 animate-ping" />
            <span className="relative inline-flex h-2 w-2 rounded-full bg-destructive" />
          </span>
        )}
      </button>

      {isOpen && (
        <div className="absolute ltr:right-0 rtl:left-0 top-full mt-2 w-80 rounded-xl border border-border bg-card shadow-lg z-50 overflow-hidden">
          <div className="flex items-center justify-between p-4 border-b border-border bg-muted/20">
            <h3 className="font-semibold text-sm">{i18n.t("components.notification-dropdown.title")}</h3>
            {unreadCount > 0 && (
              <span className="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded-full font-medium">
                {i18n.t("components.notification-dropdown.new", { count: unreadCount })}
              </span>
            )}
          </div>

          <div className="max-h-[400px] overflow-y-auto">
            {isLoading ? (
              <div className="p-8 text-center text-sm text-muted-foreground">
                {i18n.t("components.notification-dropdown.loading")}
              </div>
            ) : notifications.length === 0 ? (
              <div className="p-8 text-center text-sm text-muted-foreground">
                {i18n.t("components.notification-dropdown.empty")}
              </div>
            ) : (
              <div className="flex flex-col">
                {notifications.map((notification) => {
                  const isUnread = notification.status !== "read" && !notification.read_at;
                  return (
                    <div
                      key={notification.id}
                      onClick={() => { if (isUnread) markAsRead(notification.id); }}
                      className={`p-4 border-b border-border/50 hover:bg-muted/30 cursor-pointer transition flex gap-3 ${isUnread ? "bg-primary/5" : ""}`}
                    >
                      <div className={`mt-1 h-2 w-2 rounded-full flex-shrink-0 ${isUnread ? "bg-primary" : "bg-transparent"}`} />
                      <div className="flex flex-col gap-1 w-full">
                        <div className="flex justify-between items-start gap-2">
                          <span className={`text-sm ${isUnread ? "font-semibold text-foreground" : "font-medium text-foreground/80"}`}>
                            {notification.title || i18n.t("components.notification-dropdown.default_title")}
                          </span>
                          <span className="text-[10px] text-muted-foreground flex-shrink-0 whitespace-nowrap">
                            {timeAgo(notification.created_at)}
                          </span>
                        </div>
                        <p className={`text-xs ${isUnread ? "text-foreground/90" : "text-muted-foreground"} line-clamp-2 leading-relaxed`}>
                          {notification.body}
                        </p>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
