'use client';

import { createContext, useCallback, useContext, useState } from 'react';
import * as Toast from '@radix-ui/react-toast';
import { cn } from '@/lib/utils';

type Variant = 'success' | 'error';

interface ToastMsg {
  id: string;
  message: string;
  variant: Variant;
}

type ShowToast = (message: string, variant?: Variant) => void;

const ToastCtx = createContext<ShowToast>(() => {});

export function useToast(): ShowToast {
  return useContext(ToastCtx);
}

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

  const show = useCallback<ShowToast>((message, variant = 'success') => {
    const id = Math.random().toString(36).slice(2);
    setToasts((prev) => [...prev, { id, message, variant }]);
  }, []);

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

  return (
    <ToastCtx.Provider value={show}>
      <Toast.Provider swipeDirection="right" duration={3500}>
        {children}
        {toasts.map((t) => (
          <Toast.Root
            key={t.id}
            open
            onOpenChange={(open) => { if (!open) dismiss(t.id); }}
            role={t.variant === 'error' ? 'alert' : 'status'}
            aria-live={t.variant === 'error' ? 'assertive' : 'polite'}
            aria-atomic="true"
            className={cn(
              'pointer-events-auto flex items-center justify-between gap-3 rounded-lg px-4 py-3 text-sm text-white shadow-lg',
              'data-[state=closed]:opacity-0 transition-opacity',
              t.variant === 'success' ? 'bg-success' : 'bg-danger',
            )}
          >
            <Toast.Title asChild>
              <span>{t.message}</span>
            </Toast.Title>
            <Toast.Close
              className="shrink-0 rounded p-0.5 opacity-70 hover:opacity-100 focus:outline-none"
              aria-label="Close"
            >
              ✕
            </Toast.Close>
          </Toast.Root>
        ))}
        <Toast.Viewport className="fixed bottom-4 end-4 z-[100] flex flex-col gap-2 w-72 max-w-[calc(100vw-2rem)] list-none outline-none" />
      </Toast.Provider>
    </ToastCtx.Provider>
  );
}
