import { useState, useEffect } from 'react'

const API_URL = '/api'

// Workout icons based on type/name
const getWorkoutIcon = (name) => {
  const lower = name.toLowerCase()
  if (lower.includes('push') || lower.includes('bröst') || lower.includes('chest')) return '💪'
  if (lower.includes('pull') || lower.includes('rygg') || lower.includes('back')) return '🏋️'
  if (lower.includes('ben') || lower.includes('leg') || lower.includes('lower')) return '🦵'
  if (lower.includes('axlar') || lower.includes('shoulder')) return '🎯'
  if (lower.includes('arm')) return '💪'
  if (lower.includes('core') || lower.includes('mage')) return '🔥'
  if (lower.includes('helkropp') || lower.includes('full')) return '⚡'
  if (lower.includes('överkropp') || lower.includes('upper')) return '💪'
  if (lower.includes('underkropp') || lower.includes('lower')) return '🦵'
  return '🏋️'
}

// Workout color based on type
const getWorkoutColor = (name) => {
  const lower = name.toLowerCase()
  if (lower.includes('push') || lower.includes('bröst')) return '#ef4444' // Red
  if (lower.includes('pull') || lower.includes('rygg')) return '#3b82f6' // Blue
  if (lower.includes('ben') || lower.includes('leg')) return '#8b5cf6' // Purple
  if (lower.includes('axlar')) return '#f59e0b' // Orange
  if (lower.includes('överkropp') || lower.includes('upper')) return '#10b981' // Green
  if (lower.includes('underkropp') || lower.includes('lower')) return '#6366f1' // Indigo
  return '#6366f1' // Default indigo
}

function WorkoutSelectPage({ onBack, onSelectWorkout }) {
  const [program, setProgram] = useState(null)
  const [loading, setLoading] = useState(true)
  const [selectedWorkout, setSelectedWorkout] = useState(null)

  useEffect(() => {
    fetchProgram()
  }, [])

  const fetchProgram = async () => {
    try {
      const res = await fetch(`${API_URL}/programs/1`)
      const data = await res.json()
      setProgram(data)
      setLoading(false)
    } catch (err) {
      console.error('Failed to fetch program:', err)
      setLoading(false)
    }
  }

  const handleSelect = (workout) => {
    setSelectedWorkout(workout)
  }

  const handleStart = () => {
    if (selectedWorkout) {
      onSelectWorkout(selectedWorkout)
    }
  }

  if (loading) {
    return (
      <div className="select-page loading">
        <div className="spinner"></div>
        <p>Laddar pass...</p>
      </div>
    )
  }

  return (
    <div className="select-page">
      <header className="page-header">
        <button className="back-btn" onClick={onBack}>← Tillbaka</button>
        <h1>Välj pass</h1>
        <div style={{ width: 40 }}></div>
      </header>

      <main className="select-main">
        <p className="select-intro">
          Vilken träning vill du köra idag?
        </p>

        <div className="workout-grid">
          {program?.days?.map((workout) => {
            const icon = getWorkoutIcon(workout.name)
            const color = getWorkoutColor(workout.name)
            const isSelected = selectedWorkout?.id === workout.id
            const exerciseCount = workout.exercises?.filter(e => e.name).length || 0
            
            return (
              <div 
                key={workout.id}
                className={`workout-select-card ${isSelected ? 'selected' : ''}`}
                style={{ '--workout-color': color }}
                onClick={() => handleSelect(workout)}
              >
                <div className="workout-icon" style={{ background: color }}>
                  {icon}
                </div>
                <div className="workout-details">
                  <h3>{workout.name}</h3>
                  <p className="workout-exercises-count">
                    {exerciseCount} övningar
                  </p>
                  <div className="workout-preview">
                    {workout.exercises?.filter(e => e.name).slice(0, 2).map((ex, i) => (
                      <span key={i} className="preview-exercise">{ex.name}</span>
                    ))}
                    {exerciseCount > 2 && (
                      <span className="preview-more">+{exerciseCount - 2} till</span>
                    )}
                  </div>
                </div>
                {isSelected && (
                  <div className="selected-indicator">✓</div>
                )}
              </div>
            )
          })}
        </div>

        {/* Selected workout action */}
        {selectedWorkout && (
          <div className="select-action">
            <button className="start-btn" onClick={handleStart}>
              Starta {selectedWorkout.name} →
            </button>
          </div>
        )}
      </main>
    </div>
  )
}

export default WorkoutSelectPage
