// §15.2 — the inbox panel.
//
// One mental space across every RFC the contributor has any relationship
// to. Filter chips (Unread only, RFC: …, Category: personal-direct /
// structural / churn) are AND-combined. The bundle toggle collapses
// rows by (RFC, event_kind) per §15.2's per-bundle markable surface.
//
// The header badge in App.jsx subscribes to the same SSE stream and so
// stays in lockstep with the inbox per §15.3.

import { useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import {
  acceptContributionRequest,
  acceptJoinRequest,
  declineContributionRequest,
  declineJoinRequest,
  listNotifications,
  markNotificationRead,
  markNotificationsReadByFilter,
} from '../api.js'
import { entryPath, entryPrPath, useProjectId } from '../lib/entryPaths'
import './Inbox.css'

const CATEGORIES = [
  { value: '', label: 'All categories' },
  { value: 'personal-direct', label: 'Personal' },
  { value: 'structural', label: 'Structural' },
  { value: 'churn', label: 'Churn' },
]

export default function Inbox({ onClose, lastChangeTick }) {
  const [items, setItems] = useState([])
  const [unreadCount, setUnreadCount] = useState(0)
  const [filters, setFilters] = useState({
    unread: false, rfcSlug: '', category: '', bundled: false,
  })
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    setLoading(true)
    listNotifications({
      unread: filters.unread,
      rfcSlug: filters.rfcSlug || undefined,
      category: filters.category || undefined,
      bundled: filters.bundled,
    })
      .then(r => {
        setItems(r.items || [])
        setUnreadCount(r.unread_count || 0)
      })
      .finally(() => setLoading(false))
  }, [filters, lastChangeTick])

  const rfcOptions = useMemo(() => {
    const seen = new Map()
    for (const it of items) {
      if (it.rfc_slug && !seen.has(it.rfc_slug)) {
        seen.set(it.rfc_slug, it.rfc_title || it.rfc_slug)
      }
    }
    return Array.from(seen.entries())
  }, [items])

  async function markOneRead(item) {
    if (item.read_at) return
    await markNotificationRead(item.id)
    setItems(prev => prev.map(p => p.id === item.id ? { ...p, read_at: new Date().toISOString() } : p))
    setUnreadCount(c => Math.max(0, c - 1))
  }

  async function handleRowClick(item) {
    await markOneRead(item)
  }

  async function markAllUnderFilter() {
    await markNotificationsReadByFilter({
      rfc_slug: filters.rfcSlug || undefined,
      category: filters.category || undefined,
    })
    setItems(prev => prev.map(p => ({ ...p, read_at: p.read_at || new Date().toISOString() })))
    setUnreadCount(0)
  }

  return (
    <div className="inbox-overlay" onClick={onClose}>
      <div className="inbox-panel" onClick={e => e.stopPropagation()}>
        <header className="inbox-header">
          <h2>Inbox</h2>
          <button className="btn-link" onClick={onClose}>Close</button>
        </header>

        <div className="inbox-filters">
          <label className="chip">
            <input
              type="checkbox"
              checked={filters.unread}
              onChange={e => setFilters(f => ({ ...f, unread: e.target.checked }))}
            />
            Unread only
          </label>

          <select
            value={filters.rfcSlug}
            onChange={e => setFilters(f => ({ ...f, rfcSlug: e.target.value }))}
            className="chip"
          >
            <option value="">All RFCs</option>
            {rfcOptions.map(([slug, title]) => (
              <option key={slug} value={slug}>{title}</option>
            ))}
          </select>

          <select
            value={filters.category}
            onChange={e => setFilters(f => ({ ...f, category: e.target.value }))}
            className="chip"
          >
            {CATEGORIES.map(c => (
              <option key={c.value} value={c.value}>{c.label}</option>
            ))}
          </select>

          <label className="chip">
            <input
              type="checkbox"
              checked={filters.bundled}
              onChange={e => setFilters(f => ({ ...f, bundled: e.target.checked }))}
            />
            Bundle by RFC
          </label>

          <button
            className="btn-link inbox-mark-all"
            onClick={markAllUnderFilter}
            disabled={items.every(i => i.read_at)}
            title="Mark every notification matching the current filter as read"
          >
            Mark all read
          </button>
        </div>

        <div className="inbox-body">
          {loading && <p className="inbox-state muted">Loading your inbox…</p>}
          {!loading && items.length === 0 && (
            <div className="inbox-empty">
              <p className="inbox-empty-title">You're all caught up.</p>
              <p className="muted">
                {filters.unread || filters.rfcSlug || filters.category
                  ? 'Nothing matches the current filters. Clear them to see everything.'
                  : 'New activity on RFCs you follow will show up here.'}
              </p>
            </div>
          )}
          <ul className="inbox-list">
            {items.map(item => (
              <InboxRow
                key={item.id}
                item={item}
                onClick={handleRowClick}
                onMarkRead={markOneRead}
                onClose={onClose}
              />
            ))}
          </ul>
        </div>
      </div>
    </div>
  )
}

// #28 Part 3: the contribute-request row is the first actionable inbox
// kind — it renders the requester's who/why/use-case inline and an
// Accept/Decline pair that fire the owner's decision (accept reuses #12's
// invite flow on the backend).
function ContributionRequestRow({ item, onMarkRead }) {
  const unread = !item.read_at
  const x = item.extras || {}
  const [outcome, setOutcome] = useState(null)   // 'accepted' | 'declined'
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState(null)

  async function act(accept) {
    if (busy || outcome) return
    setBusy(true)
    setError(null)
    try {
      if (accept) await acceptContributionRequest(item.rfc_slug, x.request_id)
      else await declineContributionRequest(item.rfc_slug, x.request_id)
      setOutcome(accept ? 'accepted' : 'declined')
      await onMarkRead(item)
    } catch (err) {
      setError(err.message || 'Action failed.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <li className={`inbox-row inbox-row-action ${unread ? 'unread' : 'read'}`}>
      <div className="inbox-row-main">
        <span className="inbox-unread-dot" aria-hidden />
        <span className={`inbox-cat cat-${item.category || 'unknown'}`}>{item.category || '·'}</span>
        <span className="inbox-summary">{item.summary}</span>
        <span className="inbox-when">{formatWhen(item.created_at)}</span>
      </div>
      <div className="inbox-request-detail">
        {x.who_i_am && <p><strong>Who:</strong> {x.who_i_am}</p>}
        {x.why && <p><strong>Why:</strong> {x.why}</p>}
        {x.use_case && <p><strong>Use case:</strong> {x.use_case}</p>}
      </div>
      {error && <p className="field-error">{error}</p>}
      {outcome ? (
        <p className="inbox-request-outcome muted">
          {outcome === 'accepted'
            ? 'Accepted — an invitation has been sent.'
            : 'Declined.'}
        </p>
      ) : (
        <div className="inbox-request-actions">
          <button type="button" className="btn-primary" disabled={busy || !x.request_id} onClick={() => act(true)}>
            Accept
          </button>
          <button type="button" className="btn-secondary" disabled={busy || !x.request_id} onClick={() => act(false)}>
            Decline
          </button>
        </div>
      )}
    </li>
  )
}

// §22.8: the cross-collection inbox row — a request to join a scope, surfaced
// to that scope's Owners across the subtree. Mirrors ContributionRequestRow:
// the requester's role + message inline, an Accept/Decline pair that writes (or
// refuses) the membership grant.
function JoinRequestRow({ item, onMarkRead }) {
  const unread = !item.read_at
  const x = item.extras || {}
  const [outcome, setOutcome] = useState(null)   // 'accepted' | 'declined'
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState(null)

  async function act(accept) {
    if (busy || outcome) return
    setBusy(true)
    setError(null)
    try {
      if (accept) await acceptJoinRequest(x.scope_type, x.scope_id, x.request_id)
      else await declineJoinRequest(x.scope_type, x.scope_id, x.request_id)
      setOutcome(accept ? 'accepted' : 'declined')
      await onMarkRead(item)
    } catch (err) {
      setError(err.message || 'Action failed.')
    } finally {
      setBusy(false)
    }
  }

  const roleLabel = x.requested_role === 'owner' ? 'Owner' : 'RFC Contributor'

  return (
    <li className={`inbox-row inbox-row-action ${unread ? 'unread' : 'read'}`}>
      <div className="inbox-row-main">
        <span className="inbox-unread-dot" aria-hidden />
        <span className={`inbox-cat cat-${item.category || 'unknown'}`}>{item.category || '·'}</span>
        <span className="inbox-summary">{item.summary}</span>
        <span className="inbox-when">{formatWhen(item.created_at)}</span>
      </div>
      <div className="inbox-request-detail">
        <p><strong>Requested role:</strong> {roleLabel}</p>
        {x.message && <p><strong>Message:</strong> {x.message}</p>}
      </div>
      {error && <p className="field-error">{error}</p>}
      {outcome ? (
        <p className="inbox-request-outcome muted">
          {outcome === 'accepted'
            ? `Accepted — they're now a member as ${roleLabel}.`
            : 'Declined.'}
        </p>
      ) : (
        <div className="inbox-request-actions">
          <button type="button" className="btn-primary" disabled={busy || !x.request_id} onClick={() => act(true)}>
            Accept
          </button>
          <button type="button" className="btn-secondary" disabled={busy || !x.request_id} onClick={() => act(false)}>
            Decline
          </button>
        </div>
      )}
    </li>
  )
}

function InboxRow({ item, onClick, onMarkRead, onClose }) {
  const pid = useProjectId()
  if (item.event_kind === 'contribution_request_on_pending_rfc') {
    return <ContributionRequestRow item={item} onMarkRead={onMarkRead} />
  }
  if (item.event_kind === 'join_request_on_scope') {
    return <JoinRequestRow item={item} onMarkRead={onMarkRead} />
  }
  const unread = !item.read_at
  const target = deepLink(item, pid)
  const handle = async () => {
    await onClick(item)
    if (target) onClose?.()
  }
  const handleMarkRead = async (e) => {
    // Don't let the row's Link fire — this affordance only marks read,
    // it never navigates.
    e.preventDefault()
    e.stopPropagation()
    await onMarkRead(item)
  }
  return (
    <li className={`inbox-row ${unread ? 'unread' : 'read'}`}>
      <Link to={target || '#'} onClick={handle} className="inbox-row-link">
        <span className="inbox-unread-dot" aria-hidden />
        <span className={`inbox-cat cat-${item.category || 'unknown'}`}>{item.category || '·'}</span>
        <span className="inbox-summary">{item.summary}</span>
        {item.bundled_count > 1 && (
          <span className="inbox-bundle-count">+{item.bundled_count - 1}</span>
        )}
        <span className="inbox-when">{formatWhen(item.created_at)}</span>
      </Link>
      {unread && (
        <button
          type="button"
          className="inbox-row-dismiss"
          onClick={handleMarkRead}
          aria-label="Mark as read"
          title="Mark as read"
        >
          {/* check glyph — dependency-free inline SVG */}
          <svg
            width="14" height="14" viewBox="0 0 24 24"
            fill="none" stroke="currentColor" strokeWidth="2.25"
            strokeLinecap="round" strokeLinejoin="round" aria-hidden
          >
            <path d="m5 13 4 4 10-11" />
          </svg>
        </button>
      )}
    </li>
  )
}

function deepLink(item, pid) {
  if (item.rfc_slug && item.pr_number) return entryPrPath(pid, item.rfc_slug, item.pr_number)
  if (item.rfc_slug && item.branch_name) return `${entryPath(pid, item.rfc_slug)}?branch=${item.branch_name}`
  if (item.rfc_slug) return entryPath(pid, item.rfc_slug)
  return ''
}

function formatWhen(iso) {
  if (!iso) return ''
  const dt = new Date(iso.replace(' ', 'T') + (iso.endsWith('Z') ? '' : 'Z'))
  if (Number.isNaN(dt.getTime())) return iso
  const diffMs = Date.now() - dt.getTime()
  const m = Math.floor(diffMs / 60000)
  if (m < 1) return 'just now'
  if (m < 60) return `${m}m`
  const h = Math.floor(m / 60)
  if (h < 24) return `${h}h`
  const d = Math.floor(h / 24)
  return `${d}d`
}
