"use client";

import { useEffect, useRef, useState } from "react";
import { Bell, FileText, Send, XCircle, User, Info, BarChart2 } from "lucide-react";
import { cn } from "@/lib/utils/cn";
import type { NotificationItem } from "@/lib/queries/notification-queries";

const STORAGE_KEY = "ss_notif_last_read";

function timeAgo(date: Date): string {
  const diff = Math.floor((Date.now() - new Date(date).getTime()) / 1000);
  if (diff < 60) return "just now";
  if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
  if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`;
  return new Date(date).toLocaleDateString();
}

function NotifIcon({ icon }: { icon: NotificationItem["icon"] }) {
  const base = "flex h-8 w-8 shrink-0 items-center justify-center rounded-full";
  switch (icon) {
    case "survey":
      return <div className={cn(base, "bg-[#EFF6FF] text-primary")}><FileText className="h-3.5 w-3.5" /></div>;
    case "publish":
      return <div className={cn(base, "bg-[#F0FDF4] text-success")}><Send className="h-3.5 w-3.5" /></div>;
    case "close":
      return <div className={cn(base, "bg-[#FEE2E2] text-danger")}><XCircle className="h-3.5 w-3.5" /></div>;
    case "profile":
      return <div className={cn(base, "bg-[#F3F4F6] text-[#374151]")}><User className="h-3.5 w-3.5" /></div>;
    case "billing":
      return <div className={cn(base, "bg-[#FDF4FF] text-[#A21CAF]")}><BarChart2 className="h-3.5 w-3.5" /></div>;
    default:
      return <div className={cn(base, "bg-[#F1F5F9] text-muted")}><Info className="h-3.5 w-3.5" /></div>;
  }
}

interface NotificationBellProps {
  notifications: NotificationItem[];
}

export function NotificationBell({ notifications }: NotificationBellProps) {
  const [open, setOpen] = useState(false);
  const [lastRead, setLastRead] = useState<number>(0);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) setLastRead(parseInt(stored, 10));
  }, []);

  // Count items newer than lastRead
  const unreadCount = notifications.filter(
    (n) => new Date(n.createdAt).getTime() > lastRead
  ).length;

  function handleOpen() {
    setOpen((o) => !o);
  }

  function markAllRead() {
    const now = Date.now();
    localStorage.setItem(STORAGE_KEY, String(now));
    setLastRead(now);
  }

  // Close on outside click
  useEffect(() => {
    function handler(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    if (open) document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  return (
    <div className="relative" ref={ref}>
      <button
        type="button"
        onClick={handleOpen}
        aria-label="Notifications"
        className={cn(
          "relative flex h-8 w-8 items-center justify-center rounded-[8px] border border-border transition-colors",
          open ? "bg-[#EFF6FF] border-primary/30" : "bg-white hover:bg-[#F8FAFC]"
        )}
      >
        <Bell className={cn("h-[15px] w-[15px]", open ? "text-primary" : "text-navy")} />
        {unreadCount > 0 && (
          <span className="absolute -right-1 -top-1 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-danger px-[3px] text-[9px] font-bold text-white shadow">
            {unreadCount > 99 ? "99+" : unreadCount}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute right-0 top-full z-50 mt-2 w-[340px] overflow-hidden rounded-[12px] border border-border bg-white shadow-lg">
          {/* Header */}
          <div className="flex items-center justify-between border-b border-border px-4 py-3">
            <div>
              <h3 className="text-[13.5px] font-bold text-navy">Notifications</h3>
              {unreadCount > 0 && (
                <p className="text-[11px] text-muted">{unreadCount} unread</p>
              )}
            </div>
            {unreadCount > 0 && (
              <button
                type="button"
                onClick={markAllRead}
                className="text-[11.5px] font-semibold text-primary hover:text-primary-dark hover:underline"
              >
                Mark all read
              </button>
            )}
          </div>

          {/* List */}
          <div className="max-h-[360px] overflow-y-auto">
            {notifications.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-10 text-center">
                <Bell className="mb-2 h-8 w-8 text-border" />
                <p className="text-[13px] font-semibold text-muted">No notifications yet</p>
                <p className="text-[11.5px] text-muted/70">
                  Activity like surveys published and responses received will show here.
                </p>
              </div>
            ) : (
              notifications.map((n) => {
                const isUnread = new Date(n.createdAt).getTime() > lastRead;
                return (
                  <div
                    key={n.id}
                    className={cn(
                      "flex gap-3 border-b border-border px-4 py-3 last:border-b-0",
                      isUnread ? "bg-[#F8FAFF]" : "bg-white"
                    )}
                  >
                    <NotifIcon icon={n.icon} />
                    <div className="min-w-0 flex-1">
                      <div className="flex items-start justify-between gap-2">
                        <p className={cn(
                          "text-[12.5px]",
                          isUnread ? "font-semibold text-navy" : "font-medium text-navy/80"
                        )}>
                          {n.title}
                        </p>
                        <span className="shrink-0 text-[10.5px] text-muted">
                          {timeAgo(n.createdAt)}
                        </span>
                      </div>
                      <p className="mt-0.5 text-[11.5px] text-muted">
                        {n.description}
                      </p>
                    </div>
                    {isUnread && (
                      <span className="mt-1 h-2 w-2 shrink-0 rounded-full bg-primary" />
                    )}
                  </div>
                );
              })
            )}
          </div>

          {/* Footer */}
          {notifications.length > 0 && (
            <div className="border-t border-border px-4 py-2.5 text-center">
              <p className="text-[11px] text-muted">
                Showing last {notifications.length} activities
              </p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
