import type { Location, Profile, CombatState } from './types'
import { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { getAssetPath } from '../../utils/assetPath'
import { getTranslatedText } from '../../utils/i18nUtils'
import { GameTooltip } from '../common/GameTooltip'
import { GameButton } from '../common/GameButton'

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) {
  const { t } = useTranslation()
  // 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 ? getTranslatedText(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 ? t('messages.youAreDead') :
      movementCooldown > 0 ? t('messages.waitBeforeMoving', { seconds: movementCooldown }) :
        combatState ? t('messages.cannotTravelCombat') :
          insufficientStamina ? t('messages.notEnoughStamina', { need: stamina, have: profile?.stamina ?? 0 }) :
            available ? (
              <div className="movement-tooltip">
                <div className="tooltip-title">{destination}</div>
                <div className="tooltip-stat">📏 {t('game.distance')}: {distance}m</div>
                <div className="tooltip-stat">⚡ {t('game.stamina')}: {stamina}</div>
              </div>
            ) : t('messages.cannotGo', { direction: t('directions.' + direction) })

    return (
      <GameTooltip key={direction} content={tooltipText}>
        <button
          className={`compass-btn ${className} ${disabled ? 'disabled' : ''} ${combatState ? 'in-combat' : ''}`}
          onClick={() => onMove(direction)}
          disabled={disabled}
        >
          <span className="compass-arrow">{arrow}</span>
          {available && movementCooldown > 0 ? (
            <span className="compass-cost">⏳{movementCooldown}s</span>
          ) : available && (
            <span className="compass-cost">⚡{stamina}</span>
          )}
        </button>
      </GameTooltip>
    )
  }

  // Helper function to render center button (compass center or action)
  const renderCenterButton = () => {
    // Check for special directions that should go in the center
    const insideDir = location.directions.includes('inside') ? 'inside' : null;
    const outsideDir = location.directions.includes('outside') ? 'outside' : null;
    const enterDir = location.directions.includes('enter') ? 'enter' : null;
    const exitDir = location.directions.includes('exit') ? 'exit' : null;
    const upDir = location.directions.includes('up') ? 'up' : null;
    const downDir = location.directions.includes('down') ? 'down' : null;

    // Priority: Inside/Outside (usually mutually exclusive) > Enter/Exit
    const centerDirection = insideDir || outsideDir || enterDir || exitDir || upDir || downDir;

    if (!centerDirection) {
      // Default Compass Icon
      return (
        <div className="compass-center">
          <div className="compass-icon">🧭</div>
        </div>
      );
    }

    // Action Button Logic
    const stamina = getStaminaCost(centerDirection);
    const destination = getDestinationName(centerDirection);
    const insufficientStamina = profile ? profile.stamina < stamina : false;
    const disabled = !!combatState || movementCooldown > 0 || insufficientStamina || (profile?.is_dead ?? false);

    // Labels and Icons
    let label = t('directions.' + centerDirection);
    let icon = '🚪';
    if (centerDirection === 'inside') icon = '🏠';
    if (centerDirection === 'outside') icon = '🌳';
    if (centerDirection === 'up') icon = '⬆️';
    if (centerDirection === 'down') icon = '⬇️';

    const tooltipText = profile?.is_dead ? t('messages.youAreDead') :
      movementCooldown > 0 ? t('messages.waitBeforeMoving', { seconds: movementCooldown }) :
        combatState ? t('messages.cannotTravelCombat') :
          insufficientStamina ? t('messages.notEnoughStamina', { need: stamina, have: profile?.stamina ?? 0 }) :
            (
              <div className="movement-tooltip">
                <div className="tooltip-title">{label}</div>
                <div className="tooltip-stat">⚡ {t('game.stamina')}: {stamina}</div>
                {destination && <div className="tooltip-desc">{destination}</div>}
              </div>
            );

    return (
      <div className="compass-center">
        <GameTooltip content={tooltipText}>
          <button
            className="compass-center-btn"
            onClick={() => onMove(centerDirection)}
            disabled={disabled}
          >
            <span className="center-btn-icon" key={`icon-${centerDirection}`}>{icon}</span>
            <span className="center-btn-label" key={`label-${centerDirection}`}>{label}</span>
            {movementCooldown > 0 ? (
              <span className="compass-cost" key="cost-timer">⏳{movementCooldown}s</span>
            ) : (
              <span className="compass-cost" key="cost-stamina">⚡{stamina}</span>
            )}
          </button>
        </GameTooltip>
      </div>
    );
  };

  return (
    <>
      <div className="movement-controls">

        <div className="compass-grid">
          {/* Top row */}
          {renderCompassButton('northwest', '↖️', 'nw')}
          {renderCompassButton('north', '⬆️', 'n')}
          {renderCompassButton('northeast', '↗️', 'ne')}

          {/* Middle row */}
          {renderCompassButton('west', '⬅️', 'w')}
          {renderCenterButton()}
          {renderCompassButton('east', '➡️', 'e')}

          {/* Bottom row */}
          {renderCompassButton('southwest', '↙️', 'sw')}
          {renderCompassButton('south', '⬇️', 's')}
          {renderCompassButton('southeast', '↘️', 'se')}
        </div>

      </div>

      {/* Surroundings - outside movement controls */}
      {location.interactables && location.interactables.length > 0 && (
        <div className="interactables-section">
          {location.interactables.map((interactable: any) => (
            <div key={interactable.instance_id} className="interactable-card">
              {interactable.image_path && (
                <div className="interactable-image-container">
                  <img
                    src={getAssetPath(interactable.image_path)}
                    alt={getTranslatedText(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">{getTranslatedText(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
                      const staminaCost = action.stamina_cost || 1
                      const insufficientStamina = profile ? profile.stamina < staminaCost : false

                      return (
                        <GameTooltip key={action.id} content={
                          profile?.is_dead
                            ? t('messages.youAreDead')
                            : combatState
                              ? t('messages.cannotInteractInCombat')
                              : insufficientStamina
                                ? t('messages.notEnoughStamina', { need: staminaCost, have: profile?.stamina ?? 0 })
                                : cooldownRemaining > 0
                                  ? t('messages.interactionCooldown', { seconds: cooldownRemaining })
                                  : getTranslatedText(action.description)
                        }>
                          <GameButton
                            className={`interact-btn ${insufficientStamina ? 'disabled' : ''}`}
                            variant="primary"
                            size="sm"
                            disabled={!!combatState || cooldownRemaining > 0 || insufficientStamina || (profile?.is_dead ?? false)}
                            onClick={() => onInteract && onInteract(interactable.instance_id, action.id)}
                            style={{ width: '100%', justifyContent: 'space-between' }}
                          >
                            {getTranslatedText(action.name)}
                            <span className="stamina-cost">
                              {cooldownRemaining > 0 ? `⏳${cooldownRemaining}s` : `⚡${staminaCost}`}
                            </span>
                          </GameButton>
                        </GameTooltip>
                      )
                    })}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </>
  )
}

export default MovementControls
