import { createContext, useContext, useState, useCallback, type ReactNode } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, CheckCircle, AlertCircle, Info, AlertTriangle } from 'lucide-react';
import { cn } from '@/lib/cn';

type ToastVariant = 'success' | 'error' | 'info' | 'warning';

interface Toast {
  id: string;
  message: string;
  variant: ToastVariant;
  duration?: number;
}

interface ToastContextValue {
  toast: (message: string, variant?: ToastVariant, duration?: number) => void;
}

const ToastContext = createContext<ToastContextValue>({ toast: () => {} });
export function useToast() { return useContext(ToastContext); }

const variantConfig: Record<ToastVariant, { icon: ReactNode; accent: string; bar: string; border: string }> = {
  success: {
    icon: <CheckCircle className="w-5 h-5 text-emerald-400" />,
    accent: 'border-l-emerald-500',
    bar: 'bg-emerald-500',
    border: 'border-emerald-500/20',
  },
  error: {
    icon: <AlertCircle className="w-5 h-5 text-red-400" />,
    accent: 'border-l-red-500',
    bar: 'bg-red-500',
    border: 'border-red-500/20',
  },
  info: {
    icon: <Info className="w-5 h-5 text-[#6366f1]" />,
    accent: 'border-l-[#6366f1]',
    bar: 'bg-[#6366f1]',
    border: 'border-[#6366f1]/20',
  },
  warning: {
    icon: <AlertTriangle className="w-5 h-5 text-amber-400" />,
    accent: 'border-l-amber-500',
    bar: 'bg-amber-500',
    border: 'border-amber-500/20',
  },
};

function ToastItem({ toast, onDismiss }: { toast: Toast; onDismiss: (id: string) => void }) {
  const duration = toast.duration || 5000;
  const config = variantConfig[toast.variant];

  return (
    <motion.div
      layout
      initial={{ opacity: 0, x: 100, scale: 0.95 }}
      animate={{ opacity: 1, x: 0, scale: 1 }}
      exit={{ opacity: 0, x: 100, scale: 0.95 }}
      transition={{ type: 'spring', stiffness: 300, damping: 22 }}
      className={cn(
        'relative flex items-start gap-3 p-4 bg-[#0d0d14] border border-[#1e1e30] border-l-[3px] rounded-xl shadow-[0_12px_40px_rgba(0,0,0,0.5)] min-w-[320px] max-w-[420px] overflow-hidden',
        config.accent
      )}
    >
      <div className="flex-shrink-0 mt-0.5">{config.icon}</div>
      <p className="flex-1 text-sm text-[#f0f0f5] font-medium">{toast.message}</p>
      <button
        onClick={() => onDismiss(toast.id)}
        className="flex-shrink-0 p-0.5 text-[#5a5a72] hover:text-[#f0f0f5] transition-colors"
      >
        <X className="w-4 h-4" />
      </button>
      <motion.div
        initial={{ scaleX: 1 }}
        animate={{ scaleX: 0 }}
        transition={{ duration: duration / 1000, ease: 'linear' }}
        onAnimationComplete={() => onDismiss(toast.id)}
        className={cn('absolute bottom-0 left-0 right-0 h-0.5 origin-left', config.bar)}
      />
    </motion.div>
  );
}

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

  const addToast = useCallback((message: string, variant: ToastVariant = 'info', duration?: number) => {
    const id = Math.random().toString(36).slice(2);
    setToasts((prev) => [...prev, { id, message, variant, duration }]);
  }, []);

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

  return (
    <ToastContext.Provider value={{ toast: addToast }}>
      {children}
      <div className="fixed bottom-6 right-6 z-[200] flex flex-col gap-3">
        <AnimatePresence mode="popLayout">
          {toasts.map((t) => (
            <ToastItem key={t.id} toast={t} onDismiss={dismissToast} />
          ))}
        </AnimatePresence>
      </div>
    </ToastContext.Provider>
  );
}
