import { useEffect, useState } from 'react'
import { CheckCircle, XCircle, Info, AlertCircle, X } from 'lucide-react'
import clsx from 'clsx'

export interface ToastAction {
  label: string
  onClick: () => void
}

export interface Toast {
  id: string
  type: 'success' | 'error' | 'info' | 'warning'
  title: string
  message?: string
  duration?: number
  action?: ToastAction
}

// Global toast state (in production, use Zustand or Context)
let toastListeners: ((toasts: Toast[]) => void)[] = []
let toastList: Toast[] = []

export const toast = {
  success: (title: string, message?: string, action?: ToastAction) =>
    addToast('success', title, message, 5000, action),
  error: (title: string, message?: string, action?: ToastAction) =>
    addToast('error', title, message, 5000, action),
  info: (title: string, message?: string, action?: ToastAction) =>
    addToast('info', title, message, 5000, action),
  warning: (title: string, message?: string, action?: ToastAction) =>
    addToast('warning', title, message, 5000, action),
}

function addToast(
  type: Toast['type'],
  title: string,
  message?: string,
  duration = 5000,
  action?: ToastAction
) {
  const id = Date.now().toString() + Math.random().toString(36).slice(2, 6)
  const newToast: Toast = { id, type, title, message, duration, action }
  toastList = [...toastList, newToast]
  toastListeners.forEach(listener => listener(toastList))

  // Auto-remove after duration. Toasts with an action get a longer window
  // so the user has time to actually click Undo.
  const removeAfter = action ? Math.max(duration, 8000) : duration
  setTimeout(() => {
    removeToast(id)
  }, removeAfter)
}

function removeToast(id: string) {
  toastList = toastList.filter(t => t.id !== id)
  toastListeners.forEach(listener => listener(toastList))
}

export function ToastContainer() {
  const [toasts, setToasts] = useState<Toast[]>([])

  useEffect(() => {
    const listener = (newToasts: Toast[]) => setToasts(newToasts)
    toastListeners.push(listener)
    return () => {
      toastListeners = toastListeners.filter(l => l !== listener)
    }
  }, [])

  // Subdued icons — smaller and muted so the toast reads as a
  // background notification rather than a modal. The colored tint
  // comes from the border-left accent, not a filled background.
  const icons = {
    success: <CheckCircle className="h-3.5 w-3.5 text-pick" />,
    error: <XCircle className="h-3.5 w-3.5 text-reject" />,
    info: <Info className="h-3.5 w-3.5 text-primary" />,
    warning: <AlertCircle className="h-3.5 w-3.5 text-star" />,
  }

  // Single thin left accent bar per type instead of a full-border +
  // tinted fill. Keeps the toast visually quiet — the user can still
  // glance it but it doesn't compete with the rest of the UI.
  const accents = {
    success: 'border-l-pick',
    error: 'border-l-reject',
    info: 'border-l-primary',
    warning: 'border-l-star',
  }

  return (
    <div className="pointer-events-none fixed bottom-4 left-4 z-50 flex flex-col gap-1.5">
      {toasts.map((toast) => (
        <div
          key={toast.id}
          className={clsx(
            'pointer-events-auto flex items-start gap-2 rounded-md border border-border border-l-2 bg-surface/80 px-2.5 py-1.5 text-xs shadow-md backdrop-blur-md transition-all duration-300',
            'animate-slide-up',
            accents[toast.type]
          )}
          style={{ minWidth: '220px', maxWidth: '320px' }}
        >
          <div className="mt-0.5 flex-shrink-0">{icons[toast.type]}</div>
          <div className="min-w-0 flex-1">
            <div className="truncate font-medium text-text">{toast.title}</div>
            {toast.message && (
              <div className="mt-0.5 truncate text-[11px] text-text-muted">
                {toast.message}
              </div>
            )}
          </div>
          {toast.action && (
            <button
              onClick={() => {
                toast.action!.onClick()
                removeToast(toast.id)
              }}
              className="pointer-events-auto self-center rounded border border-border bg-surface px-1.5 py-0.5 text-[11px] font-medium text-text hover:bg-surface-2"
            >
              {toast.action.label}
            </button>
          )}
          <button
            onClick={() => removeToast(toast.id)}
            className="pointer-events-auto rounded p-0.5 text-text-faint hover:bg-surface-offset hover:text-text"
          >
            <X className="h-3 w-3" />
          </button>
        </div>
      ))}
    </div>
  )
}