import { useState, useEffect } from 'react'
import { Icon, getWorkoutIconName } from '../components/Icons'

const API_URL = '/api'

// Workout color based on type - more subtle/muted palette
const getWorkoutColor = (name) => {
  const lower = name.toLowerCase()
  if (lower.includes('push') || lower.includes('bröst')) return 'var(--workout-push)'
  if (lower.includes('pull') || lower.includes('rygg')) return 'var(--workout-pull)'
  if (lower.includes('ben') || lower.includes('leg')) return 'var(--workout-legs)'
  if (lower.includes('axlar')) return 'var(--workout-shoulders)'
  if (lower.includes('överkropp') || lower.includes('upper')) return 'var(--workout-upper)'
  if (lower.includes('underkropp') || lower.includes('lower')) return 'var(--workout-lower)'
  return 'var(--workout-default)'
}

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}>
          <Icon name="arrowLeft" size={18} /> 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 iconName = getWorkoutIconName(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 name={iconName} size={28} />
                </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">
                    <Icon name="check" size={16} />
                  </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
