import type { Location, Profile, CombatState } from './types'
import { useState, useEffect } from 'react'

interface MovementControlsProps {
  location: Location
  profile: Profile
  combatState: CombatState | null
  movementCooldown: number
  interactableCooldowns: Record<string, number>
  onMove: (direction: string) => void
  onInteract?: (interactableId: string, actionId: string) => void
}

function MovementControls({
  location,
  profile,
  combatState,
  movementCooldown,
  interactableCooldowns,
  onMove,
  onInteract
}: MovementControlsProps) {
  // Force re-render every second to update cooldown timers
  const [, forceUpdate] = useState(0)
  
  useEffect(() => {
    const timer = setInterval(() => {
      forceUpdate(prev => prev + 1)
    }, 1000)
    return () => clearInterval(timer)
  }, [])
  
  // Helper function to get direction details
  const getDirectionDetail = (direction: string) => {
    if (!location.directions_detailed) return null
    return location.directions_detailed.find(d => d.direction === direction)
  }

  // Helper function to get stamina cost for a direction
  const getStaminaCost = (direction: string): number => {
    const detail = getDirectionDetail(direction)
    return detail ? detail.stamina_cost : 5
  }

  // Helper function to get destination name for a direction
  const getDestinationName = (direction: string): string => {
    const detail = getDirectionDetail(direction)
    return detail ? (detail.destination_name || detail.destination) : ''
  }
  
  // Helper function to get distance for a direction
  const getDistance = (direction: string): number => {
    const detail = getDirectionDetail(direction)
    return detail ? detail.distance : 0
  }

  // Helper function to check if direction is available
  const hasDirection = (direction: string): boolean => {
    return location.directions.includes(direction)
  }

  // Helper function to render compass button
  const renderCompassButton = (direction: string, arrow: string, className: string) => {
    const available = hasDirection(direction)
    const stamina = getStaminaCost(direction)
    const destination = getDestinationName(direction)
    const distance = getDistance(direction)
    const insufficientStamina = profile ? profile.stamina < stamina : false
    const disabled = !available || !!combatState || movementCooldown > 0 || insufficientStamina || (profile?.is_dead ?? false)
    
    // Build detailed tooltip text
    const tooltipText = profile?.is_dead ? 'You are dead' :
      movementCooldown > 0 ? `Wait ${movementCooldown}s before moving` :
      combatState ? 'Cannot travel during combat' :
      insufficientStamina ? `Not enough stamina (need ${stamina}, have ${profile?.stamina ?? 0})` :
      available ? `${destination}\nDistance: ${distance}m\nStamina: ${stamina}` : 
      `Cannot go ${direction}`
    
    return (
      <button
        onClick={() => onMove(direction)}
        disabled={disabled}
        className={`compass-btn ${className} ${disabled ? 'disabled' : ''}`}
        title={tooltipText}
      >
        <span className="compass-arrow">{arrow}</span>
        {available && movementCooldown > 0 ? (
          <span className="compass-cost">⏳{movementCooldown}s</span>
        ) : available && (
          <span className="compass-cost">⚡{stamina}</span>
        )}
      </button>
    )
  }

  return (
    <>
    <div className="movement-controls">
      <h3>🧭 Travel</h3>
      <div className="compass-grid">
        {/* Top row */}
        {renderCompassButton('northwest', '↖️', 'nw')}
        {renderCompassButton('north', '⬆️', 'n')}
        {renderCompassButton('northeast', '↗️', 'ne')}
        
        {/* Middle row */}
        {renderCompassButton('west', '⬅️', 'w')}
        <div className="compass-center">
          <div className="compass-icon">🧭</div>
        </div>
        {renderCompassButton('east', '➡️', 'e')}
        
        {/* Bottom row */}
        {renderCompassButton('southwest', '↙️', 'sw')}
        {renderCompassButton('south', '⬇️', 's')}
        {renderCompassButton('southeast', '↘️', 'se')}
      </div>
      
      {/* Cooldown indicator */}
      {movementCooldown > 0 && (
        <div className="cooldown-indicator">
          ⏳ Wait {movementCooldown}s before moving
        </div>
      )}
      
      {/* Special movements */}
      <div className="special-moves">
        {location.directions.includes('up') && (
          <button 
            onClick={() => onMove('up')} 
            className="special-btn" 
            disabled={!!combatState || movementCooldown > 0} 
            title={movementCooldown > 0 ? `Wait ${movementCooldown}s before moving` : combatState ? 'Cannot travel during combat' : `Go up\nStamina: ${getStaminaCost('up')}`}
          >
            ⬆️ Up <span className="compass-cost">{movementCooldown > 0 ? `⏳${movementCooldown}s` : `⚡${getStaminaCost('up')}`}</span>
          </button>
        )}
        {location.directions.includes('down') && (
          <button 
            onClick={() => onMove('down')} 
            className="special-btn" 
            disabled={!!combatState || movementCooldown > 0} 
            title={movementCooldown > 0 ? `Wait ${movementCooldown}s before moving` : combatState ? 'Cannot travel during combat' : `Go down\nStamina: ${getStaminaCost('down')}`}
          >
            ⬇️ Down <span className="compass-cost">{movementCooldown > 0 ? `⏳${movementCooldown}s` : `⚡${getStaminaCost('down')}`}</span>
          </button>
        )}
        {location.directions.includes('enter') && (
          <button 
            onClick={() => onMove('enter')} 
            className="special-btn" 
            disabled={!!combatState || movementCooldown > 0} 
            title={movementCooldown > 0 ? `Wait ${movementCooldown}s before moving` : combatState ? 'Cannot travel during combat' : `Enter\nStamina: ${getStaminaCost('enter')}`}
          >
            🚪 Enter <span className="compass-cost">{movementCooldown > 0 ? `⏳${movementCooldown}s` : `⚡${getStaminaCost('enter')}`}</span>
          </button>
        )}
        {location.directions.includes('inside') && (
          <button 
            onClick={() => onMove('inside')} 
            className="special-btn" 
            disabled={!!combatState || movementCooldown > 0} 
            title={movementCooldown > 0 ? `Wait ${movementCooldown}s before moving` : combatState ? 'Cannot travel during combat' : `Go inside\nStamina: ${getStaminaCost('inside')}`}
          >
            🚪 Inside <span className="compass-cost">{movementCooldown > 0 ? `⏳${movementCooldown}s` : `⚡${getStaminaCost('inside')}`}</span>
          </button>
        )}
        {location.directions.includes('exit') && (
          <button 
            onClick={() => onMove('exit')} 
            className="special-btn" 
            disabled={!!combatState || movementCooldown > 0} 
            title={movementCooldown > 0 ? `Wait ${movementCooldown}s before moving` : combatState ? 'Cannot travel during combat' : 'Exit'}
          >
            🚪 Exit
          </button>
        )}
        {location.directions.includes('outside') && (
          <button 
            onClick={() => onMove('outside')} 
            className="special-btn" 
            disabled={!!combatState || movementCooldown > 0} 
            title={movementCooldown > 0 ? `Wait ${movementCooldown}s before moving` : combatState ? 'Cannot travel during combat' : `Go outside\nStamina: ${getStaminaCost('outside')}`}
          >
            🚪 Outside <span className="compass-cost">{movementCooldown > 0 ? `⏳${movementCooldown}s` : `⚡${getStaminaCost('outside')}`}</span>
          </button>
        )}
      </div>
    </div>
    
    {/* Surroundings - outside movement controls */}
    {location.interactables && location.interactables.length > 0 && (
      <div className="interactables-section">
        <h3>🌿 Surroundings</h3>
        {location.interactables.map((interactable: any) => (
          <div key={interactable.instance_id} className="interactable-card">
            {interactable.image_path && (
              <div className="interactable-image-container">
                <img 
                  src={`/${interactable.image_path}`} 
                  alt={interactable.name}
                  className="interactable-image"
                  onError={(e: any) => {
                    e.currentTarget.style.display = 'none'
                  }}
                />
              </div>
            )}
            <div className="interactable-content">
              <div className="interactable-header">
                <span className="interactable-name">{interactable.name}</span>
              </div>
              {interactable.actions && interactable.actions.length > 0 && (
                <div className="interactable-actions">
                  {interactable.actions.map((action: any) => {
                    const cooldownKey = `${interactable.instance_id}:${action.id}`
                    const cooldownExpiry = interactableCooldowns[cooldownKey]
                    const now = Date.now() / 1000
                    const cooldownRemaining = cooldownExpiry && cooldownExpiry > now 
                      ? Math.ceil(cooldownExpiry - now) 
                      : 0
                    
                    return (
                      <button
                        key={action.id}
                        className="interact-btn"
                        disabled={!!combatState || cooldownRemaining > 0}
                        onClick={() => onInteract && onInteract(interactable.instance_id, action.id)}
                        title={
                          combatState 
                            ? 'Cannot interact during combat' 
                            : cooldownRemaining > 0 
                              ? `Wait ${cooldownRemaining}s` 
                              : action.description
                        }
                      >
                        {action.name} 
                        <span className="stamina-cost">
                          {cooldownRemaining > 0 ? `⏳${cooldownRemaining}s` : `⚡${action.stamina_cost}`}
                        </span>
                      </button>
                    )
                  })}
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    )}
  </>
  )
}

export default MovementControls
