"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Bell,
  Zap,
  BookOpen,
  Crown,
  ShoppingBag,
  MessageCircle,
  Trophy,
  Users,
  X,
  CheckCheck,
} from "lucide-react";

interface NotificationItem {
  id: string;
  type: string;
  title: string;
  body: string | null;
  data: string | null;
  read: boolean;
  createdAt: string;
}

interface NotificationPanelProps {
  token: string | null;
  onClose: () => void;
  onCountChange: (count: number) => void;
}

const typeIcons: Record<string, { icon: typeof Bell; color: string }> = {
  streak_reminder: { icon: Zap, color: "text-yellow-400" },
  daily_verse: { icon: BookOpen, color: "text-emerald-400" },
  premium_expiring: { icon: Crown, color: "text-amber-400" },
  new_listing: { icon: ShoppingBag, color: "text-blue-400" },
  forum_reply: { icon: MessageCircle, color: "text-purple-400" },
  achievement: { icon: Trophy, color: "text-yellow-500" },
  referral_bonus: { icon: Users, color: "text-green-400" },
};

function timeAgo(dateStr: string): string {
  const now = Date.now();
  const then = new Date(dateStr).getTime();
  const diffMs = now - then;
  const mins = Math.floor(diffMs / 60000);
  if (mins < 1) return "just now";
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  if (days < 7) return `${days}d ago`;
  return new Date(dateStr).toLocaleDateString();
}

export default function NotificationPanel({
  token,
  onClose,
  onCountChange,
}: NotificationPanelProps) {
  const [notifications, setNotifications] = useState<NotificationItem[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchNotifications = useCallback(async () => {
    if (!token) return;
    try {
      const res = await fetch("/api/notifications", {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        setNotifications(data.notifications);
      }
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }, [token]);

  useEffect(() => {
    fetchNotifications();
  }, [fetchNotifications]);

  const markAsRead = async (id: string) => {
    if (!token) return;
    try {
      const res = await fetch("/api/notifications", {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ id }),
      });
      if (res.ok) {
        setNotifications((prev) =>
          prev.map((n) => (n.id === id ? { ...n, read: true } : n))
        );
        await refreshCount();
      }
    } catch {
      // ignore
    }
  };

  const markAllAsRead = async () => {
    if (!token) return;
    try {
      const res = await fetch("/api/notifications", {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ all: true }),
      });
      if (res.ok) {
        setNotifications((prev) =>
          prev.map((n) => ({ ...n, read: true }))
        );
        onCountChange(0);
      }
    } catch {
      // ignore
    }
  };

  const refreshCount = async () => {
    if (!token) return;
    try {
      const res = await fetch("/api/notifications/unread-count", {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        onCountChange(data.count);
      }
    } catch {
      // ignore
    }
  };

  const unreadCount = notifications.filter((n) => !n.read).length;

  return (
    <div className="absolute top-full right-0 mt-2 w-80 sm:w-96 max-h-[70vh] bg-[#12121a] border border-gray-800/60 rounded-xl shadow-2xl shadow-black/50 z-50 overflow-hidden">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-gray-800/60">
        <h3 className="text-sm font-semibold text-gray-200">Notifications</h3>
        <div className="flex items-center gap-2">
          {unreadCount > 0 && (
            <button
              onClick={markAllAsRead}
              className="flex items-center gap-1 text-xs text-gray-400 hover:text-gray-200 transition-colors"
            >
              <CheckCheck size={14} />
              Mark all read
            </button>
          )}
          <button
            onClick={onClose}
            className="p-1 rounded-full hover:bg-gray-800/60 transition-colors text-gray-500 hover:text-gray-300"
          >
            <X size={16} />
          </button>
        </div>
      </div>

      {/* List */}
      <div className="overflow-y-auto max-h-[calc(70vh-52px)]">
        {loading ? (
          <div className="flex items-center justify-center py-12">
            <div className="w-6 h-6 border-2 border-[#D4AF37] border-t-transparent rounded-full animate-spin" />
          </div>
        ) : notifications.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 text-gray-500">
            <Bell size={32} className="mb-2 opacity-50" />
            <p className="text-sm">No notifications yet</p>
          </div>
        ) : (
          notifications.map((notif) => {
            const iconConfig = typeIcons[notif.type] || { icon: Bell, color: "text-gray-400" };
            const IconComponent = iconConfig.icon;

            return (
              <button
                key={notif.id}
                onClick={() => !notif.read && markAsRead(notif.id)}
                className={`w-full text-left px-4 py-3 transition-colors border-b border-gray-800/40 last:border-b-0 hover:bg-gray-800/40 ${
                  !notif.read ? "bg-gray-800/20" : ""
                }`}
              >
                <div className="flex items-start gap-3">
                  <div className={`mt-0.5 ${iconConfig.color}`}>
                    <IconComponent size={18} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between gap-2">
                      <p
                        className={`text-sm ${
                          !notif.read ? "font-semibold text-gray-100" : "text-gray-300"
                        }`}
                      >
                        {notif.title}
                      </p>
                      <span className="text-[10px] text-gray-500 whitespace-nowrap mt-0.5">
                        {timeAgo(notif.createdAt)}
                      </span>
                    </div>
                    {notif.body && (
                      <p className="text-xs text-gray-500 mt-1 line-clamp-2">
                        {notif.body}
                      </p>
                    )}
                  </div>
                  {!notif.read && (
                    <div className="w-2 h-2 bg-[#D4AF37] rounded-full mt-2 flex-shrink-0" />
                  )}
                </div>
              </button>
            );
          })
        )}
      </div>
    </div>
  );
}
