'use client'

import { useState, useEffect, useCallback, createContext, useContext, ReactNode } from 'react'
import { X, CheckCircle, AlertTriangle, Info, XCircle, Image as ImageIcon } from 'lucide-react'

type ToastType = 'success' | 'error' | 'warning' | 'info' | 'compressing'

interface Toast {
  id: string
  type: ToastType
  title: string
  message?: string
  duration?: number // ms, 0 = persistent
}

interface ToastContextType {
  showToast: (toast: Omit<Toast, 'id'>) => string
  dismissToast: (id: string) => void
  updateToast: (id: string, updates: Partial<Omit<Toast, 'id'>>) => void
}

const ToastContext = createContext<ToastContextType | null>(null)

export function useToast() {
  const ctx = useContext(ToastContext)
  if (!ctx) {
    throw new Error('useToast must be used within a ToastProvider')
  }
  return ctx
}

function ToastItem({ toast, onDismiss }: { toast: Toast; onDismiss: (id: string) => void }) {
  const [exiting, setExiting] = useState(false)

  useEffect(() => {
    if (toast.duration === 0) return // persistent

    const duration = toast.duration || (toast.type === 'error' ? 6000 : 4000)
    const timer = setTimeout(() => {
      setExiting(true)
      setTimeout(() => onDismiss(toast.id), 300)
    }, duration)

    return () => clearTimeout(timer)
  }, [toast, onDismiss])

  const icon = {
    success: <CheckCircle className="w-5 h-5 text-green-400 flex-shrink-0" />,
    error: <XCircle className="w-5 h-5 text-red-400 flex-shrink-0" />,
    warning: <AlertTriangle className="w-5 h-5 text-yellow-400 flex-shrink-0" />,
    info: <Info className="w-5 h-5 text-blue-400 flex-shrink-0" />,
    compressing: <ImageIcon className="w-5 h-5 text-purple-400 flex-shrink-0 animate-pulse" />,
  }[toast.type]

  const borderColor = {
    success: 'border-green-500/30',
    error: 'border-red-500/30',
    warning: 'border-yellow-500/30',
    info: 'border-blue-500/30',
    compressing: 'border-purple-500/30',
  }[toast.type]

  return (
    <div
      className={`
        flex items-start gap-3 px-4 py-3 rounded-xl
        bg-gray-900/95 backdrop-blur-xl border ${borderColor}
        shadow-2xl shadow-black/40
        transition-all duration-300 ease-out
        ${exiting ? 'opacity-0 translate-x-8' : 'opacity-100 translate-x-0'}
        max-w-sm w-full
      `}
    >
      {toast.type === 'compressing' ? (
        <div className="relative flex-shrink-0">
          {icon}
          <div className="absolute inset-0 animate-ping">
            <ImageIcon className="w-5 h-5 text-purple-400 opacity-30" />
          </div>
        </div>
      ) : (
        icon
      )}
      <div className="flex-1 min-w-0">
        <p className="text-white text-sm font-medium">{toast.title}</p>
        {toast.message && (
          <p className="text-white/60 text-xs mt-0.5 leading-relaxed">{toast.message}</p>
        )}
      </div>
      {toast.duration !== 0 && (
        <button
          onClick={() => {
            setExiting(true)
            setTimeout(() => onDismiss(toast.id), 300)
          }}
          className="flex-shrink-0 p-0.5 hover:bg-white/10 rounded transition-colors"
        >
          <X className="w-3.5 h-3.5 text-white/40" />
        </button>
      )}
    </div>
  )
}

export function ToastProvider({ children }: { children: ReactNode }) {
  const [toasts, setToasts] = useState<Toast[]>([])

  const showToast = useCallback((toast: Omit<Toast, 'id'>): string => {
    const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 6)
    setToasts(prev => [...prev, { ...toast, id }])
    return id
  }, [])

  const dismissToast = useCallback((id: string) => {
    setToasts(prev => prev.filter(t => t.id !== id))
  }, [])

  const updateToast = useCallback((id: string, updates: Partial<Omit<Toast, 'id'>>) => {
    setToasts(prev =>
      prev.map(t => (t.id === id ? { ...t, ...updates } : t))
    )
  }, [])

  return (
    <ToastContext.Provider value={{ showToast, dismissToast, updateToast }}>
      {children}
      {/* Toast container */}
      <div className="fixed top-4 right-4 z-[9999] flex flex-col gap-2 pointer-events-none">
        {toasts.map(toast => (
          <div key={toast.id} className="pointer-events-auto">
            <ToastItem toast={toast} onDismiss={dismissToast} />
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  )
}
