'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { toast } from 'sonner'
import { ackWarning, getAckedWarnings } from '@/lib/ack'
import type { Trip, TripWarning } from '@/types/db'

const SEV_STYLES = {
  danger: 'bg-red-50 text-red-700 ring-red-200',
  warning: 'bg-amber-50 text-amber-800 ring-amber-200',
  info: 'bg-blue-50 text-blue-700 ring-blue-200',
} as const
const SEV_LABELS = { danger: 'Urgent', warning: 'Warning', info: 'Review' } as const

/**
 * Alerts list with per-user acknowledge (Task 10): the green checkmark hides
 * the warning for THIS user only — other participants still see it.
 */
export function AlertsList({
  warnings,
  trips,
  userId,
}: {
  warnings: TripWarning[]
  trips: Trip[]
  userId: string
}) {
  const [acked, setAcked] = useState<Set<string>>(new Set())
  const [tick, setTick] = useState(0)
  useEffect(() => setAcked(getAckedWarnings(userId)), [userId, tick])

  const visible = warnings.filter((w) => !acked.has(w.id))

  if (visible.length === 0) {
    return (
      <div className="rounded-2xl border border-dashed p-10 text-center text-sm text-neutral-500">
        No active alerts. Warnings appear here as permits are uploaded and processed.
      </div>
    )
  }

  return (
    <div className="space-y-2.5">
      {visible.map((w) => {
        const trip = trips.find((t) => t.id === w.trip_id)
        return (
          <div
            key={w.id}
            className="flex flex-wrap items-center justify-between gap-3 rounded-xl border bg-white p-4"
          >
            <div className="flex min-w-0 items-center gap-3">
              <span
                className={`shrink-0 rounded-full px-2.5 py-1 text-[10px] font-bold uppercase ring-1 ring-inset ${SEV_STYLES[w.severity]}`}
              >
                {SEV_LABELS[w.severity]}
              </span>
              <div className="min-w-0">
                <p className="text-sm font-bold">{w.message}</p>
                <p className="truncate text-xs text-neutral-500">
                  {trip ? `${trip.origin || '?'} → ${trip.destination || '?'} · ${trip.commodity || trip.ref_code}` : ''}
                </p>
              </div>
            </div>
            <div className="flex shrink-0 items-center gap-2">
              <Link
                href={`/trips/${w.trip_id}`}
                className="rounded-lg bg-[#0f1b2d] px-3 py-1.5 text-xs font-bold text-white hover:opacity-90"
              >
                Open Trip
              </Link>
              <button
                onClick={() => {
                  ackWarning(userId, w.id)
                  setTick((t) => t + 1)
                  toast.success('Acknowledged — hidden for you')
                }}
                className="rounded-lg border px-2.5 py-1.5 text-sm font-bold text-green-600 hover:bg-green-50"
                title="Acknowledge — hides this warning for you only"
              >
                ✓
              </button>
            </div>
          </div>
        )
      })}
    </div>
  )
}
