import React, { useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useADHDMode } from '../providers/ADHDModeProvider';
import { Sparkles, Heart, Star, Trophy, Sun } from 'lucide-react';
import { useTranslation } from 'react-i18next';

type EncouragementType = 'taskComplete' | 'returning' | 'struggling' | 'streakBroken' | 'milestone' | 'quickWin';

interface EncouragementToastProps {
  type: EncouragementType;
  visible: boolean;
  onDismiss: () => void;
  customMessage?: string;
  xpEarned?: number;
}

const icons: Record<EncouragementType, React.ComponentType<{ className?: string }>> = {
  taskComplete: Star,
  returning: Sun,
  struggling: Heart,
  streakBroken: Heart,
  milestone: Trophy,
  quickWin: Sparkles,
};

const colors: Record<EncouragementType, string> = {
  taskComplete: 'from-green-500/20 to-emerald-500/20 border-green-500/30',
  returning: 'from-blue-500/20 to-cyan-500/20 border-blue-500/30',
  struggling: 'from-purple-500/20 to-pink-500/20 border-purple-500/30',
  streakBroken: 'from-orange-500/20 to-amber-500/20 border-orange-500/30',
  milestone: 'from-yellow-500/20 to-amber-500/20 border-yellow-500/30',
  quickWin: 'from-primary/20 to-primary/10 border-primary/30',
};

export function EncouragementToast({
  type,
  visible,
  onDismiss,
  customMessage,
  xpEarned,
}: EncouragementToastProps) {
  const { t } = useTranslation();
  const { isEnabled, settings } = useADHDMode();

  const Icon = icons[type];
  const colorClass = colors[type];

  // Auto-dismiss after 4 seconds
  useEffect(() => {
    if (visible) {
      const timer = setTimeout(onDismiss, 4000);
      return () => clearTimeout(timer);
    }
  }, [visible, onDismiss]);

  // Don't show if ADHD mode is disabled or messaging is minimal
  if (!isEnabled || settings.positiveMessagingLevel === 'minimal') {
    return null;
  }

  const messages = t(`adhd.encouragements.${type}`, { returnObjects: true }) as string[];
  const message = customMessage || (Array.isArray(messages) ? messages[Math.floor(Math.random() * messages.length)] : messages);

  return (
    <AnimatePresence>
      {visible && (
        <motion.div
          initial={{ opacity: 0, y: 50, scale: 0.95 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{ opacity: 0, y: -20, scale: 0.95 }}
          transition={{
            type: 'spring',
            damping: 20,
            stiffness: 300,
            duration: settings.reducedAnimations ? 0 : undefined,
          }}
          onClick={onDismiss}
          className={`
            fixed bottom-6 left-1/2 -translate-x-1/2 z-50
            bg-gradient-to-r ${colorClass}
            backdrop-blur-md rounded-2xl border shadow-lg
            p-4 cursor-pointer
            max-w-md w-[calc(100vw-2rem)]
          `}
        >
          <div className="flex items-center gap-4">
            <div className="flex items-center justify-center w-12 h-12 rounded-full bg-background/50">
              <Icon className="h-6 w-6 text-primary" />
            </div>
            <div className="flex-1">
              <p className="font-medium text-foreground">{message}</p>
              {xpEarned && xpEarned > 0 && (
                <p className="text-sm text-muted-foreground mt-1">
                  +{xpEarned} XP
                </p>
              )}
            </div>
          </div>

          {/* Decorative sparkles for high messaging level */}
          {settings.positiveMessagingLevel === 'high' && !settings.reducedAnimations && (
            <>
              <motion.div
                initial={{ opacity: 0, scale: 0 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: 0.2 }}
                className="absolute -top-2 -right-2"
              >
                <Sparkles className="h-5 w-5 text-yellow-500" />
              </motion.div>
              <motion.div
                initial={{ opacity: 0, scale: 0 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: 0.3 }}
                className="absolute top-1/2 -left-2"
              >
                <Star className="h-4 w-4 text-primary/50" />
              </motion.div>
            </>
          )}
        </motion.div>
      )}
    </AnimatePresence>
  );
}

// Hook to manage encouragement state
export function useEncouragement() {
  const [visible, setVisible] = React.useState(false);
  const [type, setType] = React.useState<EncouragementType>('taskComplete');
  const [message, setMessage] = React.useState<string | undefined>();
  const [xp, setXp] = React.useState<number | undefined>();

  const show = React.useCallback((
    encouragementType: EncouragementType,
    customMessage?: string,
    xpEarned?: number
  ) => {
    setType(encouragementType);
    setMessage(customMessage);
    setXp(xpEarned);
    setVisible(true);
  }, []);

  const hide = React.useCallback(() => {
    setVisible(false);
  }, []);

  return { visible, type, message, xp, show, hide };
}
