import { create } from 'zustand'
import { cn } from '../../lib/utils'

export interface ToastData {
  id: number
  title: string
  description?: string
  variant?: 'default' | 'success' | 'error'
}

let nextId = 1

interface ToastStore {
  toasts: ToastData[]
  add: (toast: Omit<ToastData, 'id'>) => void
  remove: (id: number) => void
}

export const useToastStore = create<ToastStore>((set) => ({
  toasts: [],
  add: (toast) => {
    const id = nextId++
    set((state) => ({ toasts: [...state.toasts, { ...toast, id }] }))
    setTimeout(() => {
      set((state) => ({ toasts: state.toasts.filter((t) => t.id !== id) }))
    }, 4000)
  },
  remove: (id) => set((state) => ({ toasts: state.toasts.filter((t) => t.id !== id) })),
}))

export function useToast() {
  const add = useToastStore((s) => s.add)
  return {
    toast: (props: Omit<ToastData, 'id'>) => add(props),
    success: (title: string, description?: string) => add({ title, description, variant: 'success' }),
    error: (title: string, description?: string) => add({ title, description, variant: 'error' }),
  }
}

export function Toaster() {
  const toasts = useToastStore((s) => s.toasts)
  const remove = useToastStore((s) => s.remove)

  return (
    <div className="fixed bottom-4 right-4 z-[60] flex flex-col gap-2">
      {toasts.map((toast) => (
        <div
          key={toast.id}
          className={cn(
            'flex items-start gap-3 rounded-lg border bg-paper p-4 shadow-lg',
            toast.variant === 'success' && 'border-green',
            toast.variant === 'error' && 'border-red',
          )}
        >
          <div className="flex-1">
            <p className="text-sm font-medium text-ink">{toast.title}</p>
            {toast.description && <p className="mt-0.5 text-sm text-body">{toast.description}</p>}
          </div>
          <button
            onClick={() => remove(toast.id)}
            className="text-muted transition hover:text-ink"
            aria-label="Dismiss"
          >
            <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M18 6 6 18M6 6l12 12" strokeLinecap="round" />
            </svg>
          </button>
        </div>
      ))}
    </div>
  )
}