import React, { useState, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { api } from '../lib/api'
import { AlertCircle, Play, Square } from 'lucide-react'

const IDLE_TIMEOUT = 5 * 60 * 1000 // 5 minutes

export const IdleDetector = () => {
  const queryClient = useQueryClient()
  const [isIdle, setIsIdle] = useState(false)
  const [timer, setTimer] = useState<NodeJS.Timeout | null>(null)

  const { data: runningEntry } = useQuery({
    queryKey: ['running-entry'],
    queryFn: () => api.getRunningTimeEntry(),
    refetchInterval: 30000,
  })

  const stopMutation = useMutation({
    mutationFn: (id: string) => api.stopTimeEntry(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['running-entry'] })
      setIsIdle(false)
    },
  })

  const resetIdleTimer = () => {
    if (timer) clearTimeout(timer)
    setIsIdle(false)
    
    const newTimer = setTimeout(() => {
      setIsIdle(true)
    }, IDLE_TIMEOUT)
    
    setTimer(newTimer)
  }

  useEffect(() => {
    const events = ['mousemove', 'mousedown', 'keydown', 'scroll', 'touchstart']
    
    const handleActivity = () => resetIdleTimer()

    events.forEach(event => window.addEventListener(event, handleActivity))
    resetIdleTimer()

    return () => {
      events.forEach(event => window.removeEventListener(event, handleActivity))
      if (timer) clearTimeout(timer)
    }
  }, [])

  // Only show modal if user is idle AND a timer is actually running
  if (!isIdle || !runningEntry) return null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 backdrop-blur-sm p-4">
      <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl shadow-xl max-w-md w-full p-6 animate-in fade-in zoom-in duration-200">
        <div className="flex items-start gap-4">
          <div className="p-2 bg-amber-100 dark:bg-amber-900/30 rounded-full">
            <AlertCircle className="w-6 h-6 text-amber-600 dark:text-amber-400" />
          </div>
          <div className="flex-1">
            <h3 className="text-lg font-semibold text-slate-900 dark:text-white">
              Are you still there?
            </h3>
            <p className="text-sm text-slate-500 dark:text-slate-400 mt-1">
              You've been inactive for 5 minutes. Should we stop the timer for <span className="font-medium text-slate-700 dark:text-slate-200">"{runningEntry.description || 'this entry'}"</span>?
            </p>
          </div>
        </div>

        <div className="mt-6 flex gap-3 justify-end">
          <button
            onClick={() => {
              resetIdleTimer()
              setIsIdle(false)
            }}
            className="px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-md transition-colors flex items-center gap-2"
          >
            <Play className="w-3 h-3 fill-current" />
            Keep running
          </button>
          <button
            onClick={() => stopMutation.mutate(runningEntry.id)}
            disabled={stopMutation.isPending}
            className="px-4 py-2 text-sm font-medium bg-red-600 hover:bg-red-700 text-white rounded-md transition-colors flex items-center gap-2 disabled:opacity-50"
          >
            <Square className="w-3 h-3 fill-current" />
            Stop timer
          </button>
        </div>
      </div>
    </div>
  )
}