import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  Bell, Send, PlayCircle, CheckCircle, XCircle, Image, AlertTriangle, CheckCheck,
} from 'lucide-react'
import { clsx } from 'clsx'
import {
  getNotifications, markAsRead, markOneAsRead,
  type Notification,
} from '../api/notifications'

const ACTION_CONFIG: Record<string, { icon: typeof Bell; label: (d: Record<string, unknown> | null) => string; color: string }> = {
  'order.submitted': { icon: Send, label: (d) => `Order ${d?.order_number ?? '?'} submitted`, color: 'text-blue-500' },
  'order.processing': { icon: PlayCircle, label: (d) => `Order ${d?.order_number ?? '?'} is processing`, color: 'text-yellow-500' },
  'order.completed': { icon: CheckCircle, label: (d) => `Order ${d?.order_number ?? '?'} completed`, color: 'text-status-success-text' },
  'order.rejected': { icon: XCircle, label: (d) => `Order ${d?.order_number ?? '?'} was rejected`, color: 'text-red-500' },
  'render.completed': { icon: Image, label: (d) => `Render done: ${d?.product_name ?? 'unknown'} — ${d?.output_type ?? ''}`, color: 'text-status-success-text' },
  'render.failed': { icon: AlertTriangle, label: (d) => `Render failed: ${d?.product_name ?? 'unknown'} — ${d?.output_type ?? ''}`, color: 'text-red-500' },
  'excel.import_warnings': { icon: AlertTriangle, label: (d) => `Excel '${d?.filename ?? '?'}' had ${d?.warning_count ?? '?'} warning(s)`, color: 'text-amber-500' },
  'excel.import_error': { icon: XCircle, label: (d) => `Excel parse failed: ${d?.filename ?? '?'}`, color: 'text-red-500' },
  'excel.finalize_error': { icon: XCircle, label: (d) => `Order creation failed: ${d?.filename ?? '?'}`, color: 'text-red-500' },
}

function formatTime(ts: string): string {
  const d = new Date(ts)
  const diff = Date.now() - d.getTime()
  const seconds = Math.floor(diff / 1000)
  if (seconds < 60) return 'just now'
  const minutes = Math.floor(seconds / 60)
  if (minutes < 60) return `${minutes}m ago`
  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}h ago`
  return d.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })
}

const PAGE_SIZE = 30

export default function NotificationsPage() {
  const [unreadOnly, setUnreadOnly] = useState(false)
  const [offset, setOffset] = useState(0)
  const navigate = useNavigate()
  const qc = useQueryClient()

  const { data, isLoading } = useQuery({
    queryKey: ['notifications', 'page', offset, unreadOnly],
    queryFn: () => getNotifications({ limit: PAGE_SIZE, offset, unread_only: unreadOnly }),
    staleTime: 5_000,
  })

  const markAllMutation = useMutation({
    mutationFn: () => markAsRead(),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['notifications'] }),
  })

  const markOneMutation = useMutation({
    mutationFn: (id: string) => markOneAsRead(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['notifications'] }),
  })

  function handleClick(n: Notification) {
    if (!n.read_at) markOneMutation.mutate(n.id)
    if (n.entity_type === 'order' && n.entity_id) {
      navigate(`/orders/${n.entity_id}`)
    }
  }

  const items = data?.items ?? []
  const total = data?.total ?? 0
  const unreadCount = data?.unread_count ?? 0
  const hasMore = offset + PAGE_SIZE < total

  return (
    <div className="p-6 max-w-3xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-semibold text-content">Notifications</h1>
          <p className="text-sm text-content-muted mt-0.5">{unreadCount} unread</p>
        </div>
        <div className="flex items-center gap-3">
          <div className="flex bg-surface-muted rounded-md p-0.5">
            <button
              onClick={() => { setUnreadOnly(false); setOffset(0) }}
              className={clsx(
                'px-3 py-1.5 text-xs font-medium rounded',
                !unreadOnly ? 'bg-surface shadow text-content' : 'text-content-muted',
              )}
            >
              All
            </button>
            <button
              onClick={() => { setUnreadOnly(true); setOffset(0) }}
              className={clsx(
                'px-3 py-1.5 text-xs font-medium rounded',
                unreadOnly ? 'bg-surface shadow text-content' : 'text-content-muted',
              )}
            >
              Unread
            </button>
          </div>
          {unreadCount > 0 && (
            <button
              onClick={() => markAllMutation.mutate()}
              className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-accent border border-accent rounded-md hover:bg-accent-light transition-colors"
            >
              <CheckCheck size={14} />
              Mark all as read
            </button>
          )}
        </div>
      </div>

      <div className="bg-surface rounded-lg border border-border-default divide-y divide-border-light">
        {isLoading && (
          <div className="py-12 text-center text-sm text-content-muted">Loading...</div>
        )}
        {!isLoading && !items.length && (
          <div className="py-12 text-center text-sm text-content-muted">
            {unreadOnly ? 'No unread notifications' : 'No notifications yet'}
          </div>
        )}
        {items.map((n) => {
          const cfg = ACTION_CONFIG[n.action] ?? {
            icon: Bell,
            label: () => n.action,
            color: 'text-content-muted',
          }
          const Icon = cfg.icon
          return (
            <button
              key={n.id}
              onClick={() => handleClick(n)}
              className={clsx(
                'w-full flex items-start gap-3 px-5 py-4 text-left hover:bg-surface-hover transition-colors',
                !n.read_at && 'bg-status-info-bg',
              )}
            >
              <div className={clsx('mt-0.5 p-1.5 rounded-full bg-surface-muted', cfg.color)}>
                <Icon size={16} />
              </div>
              <div className="flex-1 min-w-0">
                <p className={clsx('text-sm', !n.read_at ? 'font-medium text-content' : 'text-content-secondary')}>
                  {cfg.label(n.details)}
                </p>
                <p className="text-xs text-content-muted mt-1">{formatTime(n.timestamp)}</p>
                {n.action === 'excel.import_warnings' && !!n.details?.warnings && (
                  <ul className="mt-1.5 text-xs text-content-secondary list-disc list-inside space-y-0.5">
                    {(n.details.warnings as string[]).slice(0, 3).map((w, i) => (
                      <li key={i}>{w}</li>
                    ))}
                  </ul>
                )}
                {!!n.details?.error && (
                  <p className="mt-1.5 text-xs text-red-600 font-mono bg-red-50 rounded px-2 py-1 whitespace-pre-wrap break-all">
                    {String(n.details.error)}
                  </p>
                )}
              </div>
              {!n.read_at && (
                <span className="mt-2 w-2 h-2 rounded-full bg-blue-500 shrink-0" />
              )}
            </button>
          )
        })}
      </div>

      {/* Pagination */}
      {total > PAGE_SIZE && (
        <div className="flex items-center justify-between mt-4">
          <button
            onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}
            disabled={offset === 0}
            className="px-3 py-1.5 text-sm border rounded-md disabled:opacity-40"
          >
            Previous
          </button>
          <span className="text-sm text-content-muted">
            {offset + 1}&ndash;{Math.min(offset + PAGE_SIZE, total)} of {total}
          </span>
          <button
            onClick={() => setOffset(offset + PAGE_SIZE)}
            disabled={!hasMore}
            className="px-3 py-1.5 text-sm border rounded-md disabled:opacity-40"
          >
            Next
          </button>
        </div>
      )}
    </div>
  )
}
