'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';

type NotificationType =
  | 'rare_grade'
  | 'cascade'
  | 'steam'
  | 'morning_results'
  | 'line_movement'
  | 'injury'
  | 'system';

type Notification = {
  id: string;
  type: NotificationType;
  title: string;
  body?: string | null;
  link?: string | null;
  read: boolean;
  created_at: string;
};

const TYPE_LABEL: Record<NotificationType, string> = {
  rare_grade: 'A+ ALERT',
  cascade: 'CASCADE',
  steam: 'STEAM',
  morning_results: 'RESULTS',
  line_movement: 'LINE',
  injury: 'INJURY',
  system: 'SYSTEM',
};

const TYPE_TINT: Record<NotificationType, string> = {
  rare_grade: 'var(--grade-aplus)',
  cascade: 'var(--grade-c)',
  steam: 'var(--grade-c)',
  morning_results: 'var(--grade-b)',
  line_movement: 'var(--grade-b)',
  injury: 'var(--grade-d)',
  system: 'var(--text-1)',
};

// Mock items used until /api/notifications is wired. The shape matches the
// future Supabase row exactly so the dropdown won't change when real data lands.
const MOCK: Notification[] = [
  {
    id: 'mock-1',
    type: 'rare_grade',
    title: 'Jokic Points Over 25.5 graded A+',
    body: 'Rare grade tonight. Phosphor confirmed.',
    link: '/dashboard',
    read: false,
    created_at: new Date(Date.now() - 8 * 60_000).toISOString(),
  },
  {
    id: 'mock-2',
    type: 'cascade',
    title: 'Murray OUT → Jokic usage +3.2%',
    body: 'Cascade recalibrated 4 props across DEN.',
    link: '/dashboard',
    read: false,
    created_at: new Date(Date.now() - 42 * 60_000).toISOString(),
  },
  {
    id: 'mock-3',
    type: 'morning_results',
    title: 'Last night: 2 of 3 graded A+ hit',
    body: 'Brunson, Edwards landed. Wilson missed by 1.',
    link: '/ledger',
    read: true,
    created_at: new Date(Date.now() - 13 * 60 * 60_000).toISOString(),
  },
];

function fmtTime(iso: string): string {
  const d = new Date(iso);
  const diff = (Date.now() - d.getTime()) / 1000;
  if (diff < 60) return `${Math.floor(diff)}s`;
  if (diff < 3600) return `${Math.floor(diff / 60)}m`;
  if (diff < 86_400) return `${Math.floor(diff / 3600)}h`;
  return d.toLocaleDateString([], { month: 'short', day: 'numeric' });
}

export default function NotificationBell() {
  const { user } = useAuth();
  const [open, setOpen] = useState(false);
  const [items, setItems] = useState<Notification[]>([]);
  const wrapRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!user) {
      setItems([]);
      return;
    }
    let alive = true;
    (async () => {
      try {
        const res = await fetch('/api/notifications', { cache: 'no-store' });
        if (!res.ok) throw new Error('not-yet');
        const data = (await res.json()) as { notifications?: Notification[] };
        if (alive) setItems(Array.isArray(data.notifications) ? data.notifications : MOCK);
      } catch {
        if (alive) setItems(MOCK);
      }
    })();
    return () => { alive = false; };
  }, [user]);

  useEffect(() => {
    if (!open) return;
    const onClick = (e: MouseEvent) => {
      if (!wrapRef.current?.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onClick);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onClick);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  const unread = useMemo(() => items.filter((n) => !n.read).length, [items]);

  const markAllRead = () => {
    setItems((prev) => prev.map((n) => ({ ...n, read: true })));
    void fetch('/api/notifications/read-all', { method: 'POST' }).catch(() => {});
  };

  if (!user) return null;

  return (
    <div ref={wrapRef} style={{ position: 'relative' }}>
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        aria-label={`Notifications${unread ? `, ${unread} unread` : ''}`}
        aria-haspopup="menu"
        aria-expanded={open}
        style={{
          width: 36,
          height: 36,
          borderRadius: 999,
          background: 'transparent',
          border: '1px solid var(--border)',
          color: 'var(--text-1)',
          cursor: 'pointer',
          display: 'inline-flex',
          alignItems: 'center',
          justifyContent: 'center',
          position: 'relative',
        }}
      >
        <BellIcon />
        {unread > 0 && (
          <span
            aria-hidden
            style={{
              position: 'absolute',
              top: 4,
              right: 4,
              minWidth: 16,
              height: 16,
              padding: '0 4px',
              borderRadius: 999,
              background: 'var(--grade-a)',
              color: '#062b22',
              fontSize: 10,
              fontWeight: 800,
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              boxShadow: '0 0 8px rgba(0, 212, 160, 0.7)',
              fontFamily: 'var(--ibm-mono)',
            }}
          >
            {unread > 9 ? '9+' : unread}
          </span>
        )}
      </button>

      {open && (
        <div
          role="menu"
          className="surface-elevated"
          style={{
            position: 'absolute',
            right: 0,
            top: 'calc(100% + 8px)',
            width: 320,
            maxHeight: 400,
            overflowY: 'auto',
            padding: 8,
            zIndex: 60,
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 8px 10px' }}>
            <span className="lbl" style={{ color: 'var(--text-1)' }}>ALERTS</span>
            {unread > 0 && (
              <button
                type="button"
                onClick={markAllRead}
                style={{ background: 'transparent', border: 'none', color: 'var(--grade-a)', fontSize: 12, cursor: 'pointer' }}
              >
                Mark all as read
              </button>
            )}
          </div>

          {items.length === 0 ? (
            <div style={{ padding: '24px 12px', textAlign: 'center', color: 'var(--text-1)' }}>
              <p style={{ fontSize: 13 }}>No new alerts.</p>
              <p style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 4 }}>
                We&apos;ll notify you when something moves.
              </p>
            </div>
          ) : (
            <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
              {items.map((n) => (
                <li key={n.id}>
                  <a
                    href={n.link || '#'}
                    onClick={() => setOpen(false)}
                    style={{
                      display: 'grid',
                      gap: 4,
                      padding: '10px 10px',
                      borderRadius: 8,
                      background: n.read ? 'transparent' : 'rgba(0, 212, 160, 0.05)',
                      borderLeft: `2px solid ${n.read ? 'var(--border)' : TYPE_TINT[n.type]}`,
                      textDecoration: 'none',
                    }}
                  >
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                      <span
                        style={{
                          fontFamily: 'var(--ibm-mono)',
                          fontSize: 10,
                          letterSpacing: '0.08em',
                          color: TYPE_TINT[n.type],
                          fontWeight: 700,
                        }}
                      >
                        {TYPE_LABEL[n.type]}
                      </span>
                      <span className="mono" style={{ fontSize: 10, color: 'var(--text-2)' }}>{fmtTime(n.created_at)}</span>
                    </div>
                    <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-0)', lineHeight: 1.35 }}>
                      {n.title}
                    </span>
                    {n.body ? (
                      <span style={{ fontSize: 12, color: 'var(--text-1)', lineHeight: 1.4 }}>{n.body}</span>
                    ) : null}
                  </a>
                </li>
              ))}
            </ul>
          )}
        </div>
      )}
    </div>
  );
}

function BellIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden>
      <path
        d="M6 9a6 6 0 1112 0c0 4 2 5 2 5H4s2-1 2-5z"
        stroke="currentColor"
        strokeWidth="1.6"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <path d="M10 18a2 2 0 004 0" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
    </svg>
  );
}
