'use client'

/**
 * AWOOOI Toast - 全局通知提示
 * ============================
 * Nothing.tech 設計語言
 *
 * 用法:
 * import { toast, ToastContainer } from '@/components/ui/toast'
 * toast.success('操作成功')
 * toast.error('操作失敗')
 * toast.info('K8s 指令發送中...')
 *
 * Phase 19: 使用 Z_INDEX.TOAST (60) 避免與 Terminal (52) 衝突
 * @see lib/constants/z-index.ts
 */

import { useState, useEffect, useCallback, createContext, useContext } from 'react'
import { cn } from '@/lib/utils'
import { CheckCircle2, XCircle, AlertCircle, Loader2 } from 'lucide-react'
import { Z_INDEX } from '@/lib/constants/z-index'

// =============================================================================
// Types
// =============================================================================

type ToastType = 'success' | 'error' | 'info' | 'loading'

interface ToastItem {
  id: string
  type: ToastType
  message: string
  duration?: number
}

interface ToastContextType {
  toasts: ToastItem[]
  addToast: (type: ToastType, message: string, duration?: number) => string
  removeToast: (id: string) => void
}

// =============================================================================
// Context
// =============================================================================

const ToastContext = createContext<ToastContextType | null>(null)

export function ToastProvider({ children }: { children: React.ReactNode }) {
  const [toasts, setToasts] = useState<ToastItem[]>([])

  const addToast = useCallback((type: ToastType, message: string, duration = 4000) => {
    const id = `toast-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
    setToasts((prev) => [...prev, { id, type, message, duration }])

    if (duration > 0 && type !== 'loading') {
      setTimeout(() => {
        setToasts((prev) => prev.filter((t) => t.id !== id))
      }, duration)
    }

    return id
  }, [])

  const removeToast = useCallback((id: string) => {
    setToasts((prev) => prev.filter((t) => t.id !== id))
  }, [])

  return (
    <ToastContext.Provider value={{ toasts, addToast, removeToast }}>
      {children}
      <ToastContainer />
    </ToastContext.Provider>
  )
}

export function useToast() {
  const context = useContext(ToastContext)
  if (!context) {
    throw new Error('useToast must be used within ToastProvider')
  }
  return context
}

// =============================================================================
// Toast Container
// =============================================================================

function ToastContainer() {
  const context = useContext(ToastContext)
  if (!context) return null

  const { toasts, removeToast } = context

  return (
    <div
      className="fixed bottom-4 right-4 flex flex-col gap-2"
      style={{ zIndex: Z_INDEX.TOAST }}
    >
      {toasts.map((toast) => (
        <ToastItem key={toast.id} toast={toast} onClose={() => removeToast(toast.id)} />
      ))}
    </div>
  )
}

// =============================================================================
// Toast Item
// =============================================================================

const TOAST_CONFIG: Record<ToastType, { icon: typeof CheckCircle2; bg: string; border: string; text: string }> = {
  success: {
    icon: CheckCircle2,
    bg: 'bg-status-healthy/10',
    border: 'border-status-healthy/30',
    text: 'text-status-healthy',
  },
  error: {
    icon: XCircle,
    bg: 'bg-status-critical/10',
    border: 'border-status-critical/30',
    text: 'text-status-critical',
  },
  info: {
    icon: AlertCircle,
    bg: 'bg-status-thinking/10',
    border: 'border-status-thinking/30',
    text: 'text-status-thinking',
  },
  loading: {
    icon: Loader2,
    bg: 'bg-nothing-gray-100',
    border: 'border-nothing-gray-300',
    text: 'text-nothing-gray-700',
  },
}

function ToastItem({ toast, onClose }: { toast: ToastItem; onClose: () => void }) {
  const config = TOAST_CONFIG[toast.type]
  const Icon = config.icon

  return (
    <div
      className={cn(
        'flex items-center gap-3 px-4 py-3 rounded-xl border shadow-lg backdrop-blur-md',
        'animate-slide-in-up min-w-[280px] max-w-[400px]',
        config.bg,
        config.border
      )}
      onClick={onClose}
    >
      <Icon
        className={cn(
          'w-5 h-5 flex-shrink-0',
          config.text,
          toast.type === 'loading' && 'animate-spin'
        )}
      />
      <p className={cn('font-body text-sm', config.text)}>{toast.message}</p>
    </div>
  )
}

// =============================================================================
// Global Toast API (for use outside React components)
// =============================================================================

let globalAddToast: ((type: ToastType, message: string, duration?: number) => string) | null = null
let globalRemoveToast: ((id: string) => void) | null = null

export function setGlobalToast(
  addFn: (type: ToastType, message: string, duration?: number) => string,
  removeFn: (id: string) => void
) {
  globalAddToast = addFn
  globalRemoveToast = removeFn
}

export const toast = {
  success: (message: string, duration?: number) => globalAddToast?.('success', message, duration),
  error: (message: string, duration?: number) => globalAddToast?.('error', message, duration),
  info: (message: string, duration?: number) => globalAddToast?.('info', message, duration),
  loading: (message: string) => globalAddToast?.('loading', message, 0),
  dismiss: (id: string) => globalRemoveToast?.(id),
}

// =============================================================================
// Toast Initializer (放在 layout 中)
// =============================================================================

export function ToastInitializer() {
  const { addToast, removeToast } = useToast()

  useEffect(() => {
    setGlobalToast(addToast, removeToast)
  }, [addToast, removeToast])

  return null
}
