import React, { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useQuery } from '@tanstack/react-query';
import { AlertTriangle, Clock, ListTodo, Coffee, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useTranslation } from 'react-i18next';
import { useADHDMode } from '../providers/ADHDModeProvider';
import type { Task } from '@shared/schema';

interface HyperfocusGuardProps {
  activeTaskId?: string;
  onTaskStart?: (taskId: string) => void;
}

export function HyperfocusGuard({ activeTaskId, onTaskStart }: HyperfocusGuardProps) {
  const { t } = useTranslation();
  const { isEnabled, settings } = useADHDMode();

  const [focusStartTime, setFocusStartTime] = useState<Date | null>(null);
  const [minutesOnTask, setMinutesOnTask] = useState(0);
  const [showWarning, setShowWarning] = useState(false);
  const [dismissed, setDismissed] = useState(false);

  const { data: tasks = [] } = useQuery<Task[]>({
    queryKey: ['/api/tasks'],
  });

  // Track when focus starts
  useEffect(() => {
    if (activeTaskId && !focusStartTime) {
      setFocusStartTime(new Date());
      setDismissed(false);
    } else if (!activeTaskId) {
      setFocusStartTime(null);
      setMinutesOnTask(0);
      setShowWarning(false);
      setDismissed(false);
    }
  }, [activeTaskId, focusStartTime]);

  // Timer to track focus duration
  useEffect(() => {
    if (!isEnabled || !settings.hyperfocusProtection || !focusStartTime || dismissed) {
      return;
    }

    const interval = setInterval(() => {
      const now = new Date();
      const diffMs = now.getTime() - focusStartTime.getTime();
      const diffMins = Math.floor(diffMs / 60000);
      setMinutesOnTask(diffMins);

      // Show warning at threshold
      if (diffMins >= settings.hyperfocusMaxMinutes && !showWarning) {
        setShowWarning(true);
      }
    }, 30000); // Check every 30 seconds

    return () => clearInterval(interval);
  }, [isEnabled, settings, focusStartTime, showWarning, dismissed]);

  // Count pending tasks
  const pendingTasks = tasks.filter(
    (t) => t.status !== 'done' && t.id !== activeTaskId
  );
  const urgentTasks = pendingTasks.filter(
    (t) => t.priority === 'high' || (t.dueDate && new Date(t.dueDate) < new Date(Date.now() + 24 * 60 * 60 * 1000))
  );

  const handleDismiss = () => {
    setShowWarning(false);
    setDismissed(true);
  };

  const handleTakeBreak = () => {
    setShowWarning(false);
    // Could trigger break reminder or navigate to break
  };

  const handleSwitchTask = (taskId: string) => {
    setShowWarning(false);
    setFocusStartTime(null);
    onTaskStart?.(taskId);
  };

  if (!isEnabled || !settings.hyperfocusProtection || !showWarning) {
    return null;
  }

  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0, y: 50 }}
        animate={{ opacity: 1, y: 0 }}
        exit={{ opacity: 0, y: 50 }}
        className="fixed bottom-4 left-1/2 -translate-x-1/2 z-50 w-full max-w-md px-4"
      >
        <div className="bg-amber-50 dark:bg-amber-950/90 border-2 border-amber-500/50 rounded-2xl shadow-xl p-5">
          {/* Header */}
          <div className="flex items-start gap-3 mb-4">
            <div className="flex items-center justify-center w-10 h-10 rounded-full bg-amber-500/20">
              <AlertTriangle className="h-5 w-5 text-amber-600 dark:text-amber-400" />
            </div>
            <div className="flex-1">
              <h4 className="font-semibold text-amber-900 dark:text-amber-100">
                {t('adhd.hyperfocus.title')}
              </h4>
              <p className="text-sm text-amber-700 dark:text-amber-300">
                {t('adhd.hyperfocus.message', { minutes: minutesOnTask })}
              </p>
            </div>
            <button
              onClick={handleDismiss}
              className="p-1 rounded-full hover:bg-amber-500/20 transition-colors"
            >
              <X className="h-4 w-4 text-amber-600 dark:text-amber-400" />
            </button>
          </div>

          {/* Stats */}
          <div className="flex gap-4 mb-4 text-sm">
            <div className="flex items-center gap-2 text-amber-700 dark:text-amber-300">
              <Clock className="h-4 w-4" />
              <span>{minutesOnTask} {t('adhd.hyperfocus.minutes')}</span>
            </div>
            {urgentTasks.length > 0 && (
              <div className="flex items-center gap-2 text-amber-700 dark:text-amber-300">
                <ListTodo className="h-4 w-4" />
                <span>{urgentTasks.length} {t('adhd.hyperfocus.urgentTasks')}</span>
              </div>
            )}
          </div>

          {/* Urgent tasks preview */}
          {urgentTasks.length > 0 && (
            <div className="mb-4 space-y-2">
              <p className="text-xs font-medium text-amber-800 dark:text-amber-200 mb-2">
                {t('adhd.hyperfocus.waitingTasks')}:
              </p>
              {urgentTasks.slice(0, 3).map((task) => (
                <button
                  key={task.id}
                  onClick={() => handleSwitchTask(task.id)}
                  className={`
                    w-full text-left p-2 rounded-lg
                    bg-amber-100 dark:bg-amber-900/50
                    hover:bg-amber-200 dark:hover:bg-amber-900
                    transition-colors text-sm
                    text-amber-900 dark:text-amber-100
                    truncate
                  `}
                >
                  {task.title}
                </button>
              ))}
            </div>
          )}

          {/* Actions */}
          <div className="flex gap-2">
            <Button
              variant="outline"
              onClick={handleTakeBreak}
              className="flex-1 border-amber-500/50 text-amber-700 dark:text-amber-300 hover:bg-amber-100 dark:hover:bg-amber-900/50"
            >
              <Coffee className="h-4 w-4 mr-2" />
              {t('adhd.hyperfocus.takeBreak')}
            </Button>
            <Button
              onClick={handleDismiss}
              className="flex-1 bg-amber-500 hover:bg-amber-600 text-white"
            >
              {t('adhd.hyperfocus.continue')}
            </Button>
          </div>

          {/* Gentle reminder */}
          <p className="text-xs text-center text-amber-600 dark:text-amber-400 mt-3 italic">
            {t('adhd.hyperfocus.gentle')}
          </p>
        </div>
      </motion.div>
    </AnimatePresence>
  );
}
