'use client';

import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import {
  Bell,
  CheckCheck,
  Trash2,
  Trophy,
  Wallet,
  Swords,
  Shield,
  Sparkles,
} from 'lucide-react';
import { apiRequest } from '../lib/api';

type Notif = {
  _id: string;
  title: string;
  message: string;
  type: string;
  isRead: boolean;
  metadata?: { href?: string };
  createdAt: string;
};

function typeIcon(type: string) {
  switch (type) {
    case 'FANTASY':
      return <Sparkles className="h-4 w-4 text-amber-500" />;
    case 'CONTEST':
      return <Swords className="h-4 w-4 text-d11-red" />;
    case 'WALLET':
      return <Wallet className="h-4 w-4 text-emerald-500" />;
    case 'MATCH':
      return <Trophy className="h-4 w-4 text-amber-600" />;
    case 'KYC':
      return <Shield className="h-4 w-4 text-sky-500" />;
    default:
      return <Bell className="h-4 w-4 text-gray-400" />;
  }
}

function timeAgo(iso: string) {
  const s = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
  if (s < 60) return 'Just now';
  if (s < 3600) return `${Math.floor(s / 60)}m ago`;
  if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
  return `${Math.floor(s / 86400)}d ago`;
}

export function NotificationBell() {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [items, setItems] = useState<Notif[]>([]);
  const [unread, setUnread] = useState(0);
  const [loading, setLoading] = useState(false);
  const panelRef = useRef<HTMLDivElement>(null);

  const loadUnread = useCallback(async () => {
    try {
      const res = await apiRequest('/notifications/unread-count');
      setUnread(res.data?.unreadCount || 0);
    } catch {
      /* ignore */
    }
  }, []);

  const loadList = useCallback(async () => {
    setLoading(true);
    try {
      const res = await apiRequest('/notifications?limit=20');
      setItems(res.data?.items || []);
      setUnread(res.data?.unreadCount || 0);
    } catch {
      /* ignore */
    } finally {
      setLoading(false);
    }
  }, []);

  // Lightweight poll — count only (not full list)
  useEffect(() => {
    loadUnread();
    const t = setInterval(loadUnread, 60_000);
    return () => clearInterval(t);
  }, [loadUnread]);

  useEffect(() => {
    if (!open) return;
    loadList();
    const onDoc = (e: MouseEvent) => {
      if (panelRef.current && !panelRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open, loadList]);

  const markRead = async (id: string) => {
    try {
      await apiRequest(`/notifications/${id}/read`, { method: 'PATCH', body: '{}' });
      setItems((prev) => prev.map((n) => (n._id === id ? { ...n, isRead: true } : n)));
      setUnread((u) => Math.max(0, u - 1));
    } catch {
      /* ignore */
    }
  };

  const markAll = async () => {
    try {
      await apiRequest('/notifications/read-all', { method: 'POST', body: '{}' });
      setItems((prev) => prev.map((n) => ({ ...n, isRead: true })));
      setUnread(0);
    } catch {
      /* ignore */
    }
  };

  const remove = async (id: string) => {
    try {
      await apiRequest(`/notifications/${id}`, { method: 'DELETE' });
      setItems((prev) => {
        const n = prev.find((x) => x._id === id);
        if (n && !n.isRead) setUnread((u) => Math.max(0, u - 1));
        return prev.filter((x) => x._id !== id);
      });
    } catch {
      /* ignore */
    }
  };

  const openItem = async (n: Notif) => {
    if (!n.isRead) await markRead(n._id);
    setOpen(false);
    const href = n.metadata?.href || '/fantasy';
    router.push(href);
  };

  return (
    <div className="relative" ref={panelRef}>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="relative flex h-9 w-9 items-center justify-center rounded-full bg-black/25 ring-1 ring-white/10 transition hover:bg-black/35"
        aria-label={unread ? `${unread} unread notifications` : 'Notifications'}
        aria-expanded={open}
      >
        <Bell className="h-4 w-4" />
        {unread > 0 && (
          <span className="notif-pulse absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-amber-400 px-1 text-[9px] font-extrabold text-d11-ink">
            {unread > 9 ? '9+' : unread}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute right-0 z-50 mt-2 w-[min(100vw-2rem,22rem)] overflow-hidden rounded-2xl border border-gray-200 bg-white text-d11-ink shadow-xl">
          <div className="flex items-center justify-between border-b border-gray-100 px-3.5 py-3">
            <div>
              <p className="text-sm font-bold">Notifications</p>
              <p className="text-[11px] text-d11-muted">
                {unread ? `${unread} unread` : 'You are all caught up'}
              </p>
            </div>
            {unread > 0 && (
              <button
                type="button"
                onClick={markAll}
                className="inline-flex items-center gap-1 rounded-lg px-2 py-1.5 text-[11px] font-bold text-d11-red hover:bg-d11-soft"
              >
                <CheckCheck className="h-3.5 w-3.5" />
                Read all
              </button>
            )}
          </div>

          <div className="max-h-80 overflow-y-auto">
            {loading && items.length === 0 ? (
              <p className="px-4 py-8 text-center text-xs text-d11-muted">Loading…</p>
            ) : items.length === 0 ? (
              <div className="px-4 py-10 text-center">
                <Bell className="mx-auto mb-2 h-8 w-8 text-gray-300" />
                <p className="text-sm font-semibold text-gray-600">No notifications yet</p>
                <p className="mt-1 text-[11px] text-d11-muted">Create a team or join a contest</p>
              </div>
            ) : (
              <ul>
                {items.map((n) => (
                  <li
                    key={n._id}
                    className={`group border-b border-gray-50 last:border-0 ${
                      n.isRead ? 'bg-white' : 'bg-d11-soft/60'
                    }`}
                  >
                    <div className="flex gap-2 px-3 py-3">
                      <button
                        type="button"
                        onClick={() => openItem(n)}
                        className="flex min-w-0 flex-1 gap-2.5 text-left"
                      >
                        <span className="mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-gray-50">
                          {typeIcon(n.type)}
                        </span>
                        <span className="min-w-0 flex-1">
                          <span className="flex items-center gap-1.5">
                            <span className="truncate text-sm font-bold text-d11-ink">{n.title}</span>
                            {!n.isRead && (
                              <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-d11-red" />
                            )}
                          </span>
                          <span className="mt-0.5 line-clamp-2 block text-[11px] leading-snug text-d11-muted">
                            {n.message}
                          </span>
                          <span className="mt-1 block text-[10px] font-medium text-gray-400">
                            {timeAgo(n.createdAt)}
                          </span>
                        </span>
                      </button>
                      <div className="flex flex-col gap-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100">
                        {!n.isRead && (
                          <button
                            type="button"
                            title="Mark read"
                            onClick={() => markRead(n._id)}
                            className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-emerald-600"
                          >
                            <CheckCheck className="h-3.5 w-3.5" />
                          </button>
                        )}
                        <button
                          type="button"
                          title="Dismiss"
                          onClick={() => remove(n._id)}
                          className="rounded-lg p-1.5 text-gray-400 hover:bg-rose-50 hover:text-rose-500"
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </button>
                      </div>
                    </div>
                  </li>
                ))}
              </ul>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
