'use client';

import React, { useState, useEffect, createContext, useContext } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Box } from '@/ui/Box';
import { Text } from '@/ui/Text';
import { Stack } from '@/ui/Stack';
import { CheckCircle, AlertCircle, Info, X } from 'lucide-react';

interface Toast {
  id: string;
  message: string;
  variant: 'success' | 'error' | 'info';
}

interface ToastContextType {
  showToast: (message: string, variant: 'success' | 'error' | 'info') => void;
}

const ToastContext = createContext<ToastContextType | undefined>(undefined);

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

  const showToast = (message: string, variant: 'success' | 'error' | 'info') => {
    const id = Math.random().toString(36).substring(2, 9);
    setToasts((prev) => [...prev, { id, message, variant }]);
    setTimeout(() => {
      setToasts((prev) => prev.filter((t) => t.id !== id));
    }, 5000);
  };

  return (
    <ToastContext.Provider value={{ showToast }}>
      {children}
      <Box
        position="fixed"
        bottom={6}
        right={6}
        zIndex={50}
        className="pointer-events-none space-y-3"
      >
        <AnimatePresence>
          {toasts.map((toast) => (
            <ToastItem
              key={toast.id}
              toast={toast}
              onClose={() => setToasts((prev) => prev.filter((t) => t.id !== toast.id))}
            />
          ))}
        </AnimatePresence>
      </Box>
    </ToastContext.Provider>
  );
}

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

function ToastItem({ toast, onClose }: { toast: Toast; onClose: () => void }) {
  const variants = {
    success: {
      bg: 'bg-deep-graphite',
      border: 'border-performance-green/30',
      icon: CheckCircle,
      iconColor: 'text-performance-green',
    },
    error: {
      bg: 'bg-deep-graphite',
      border: 'border-racing-red/30',
      icon: AlertCircle,
      iconColor: 'text-racing-red',
    },
    info: {
      bg: 'bg-deep-graphite',
      border: 'border-primary-blue/30',
      icon: Info,
      iconColor: 'text-primary-blue',
    },
  };

  const config = variants[toast.variant];
  const Icon = config.icon;

  return (
    <motion.div
      initial={{ opacity: 0, y: 20, scale: 0.95 }}
      animate={{ opacity: 1, y: 0, scale: 1 }}
      exit={{ opacity: 0, scale: 0.95 }}
      className="pointer-events-auto"
    >
      <Box
        px={4}
        py={3}
        rounded="lg"
        bg={config.bg}
        border
        borderColor={config.border}
        shadow="xl"
        display="flex"
        alignItems="center"
        gap={3}
        minW="300px"
      >
        <Icon className={`w-5 h-5 ${config.iconColor}`} />
        <Text size="sm" color="text-white" flexGrow={1}>
          {toast.message}
        </Text>
        <button
          onClick={onClose}
          className="text-gray-500 hover:text-white transition-colors"
        >
          <X className="w-4 h-4" />
        </button>
      </Box>
    </motion.div>
  );
}
