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 [customWorkouts, setCustomWorkouts] = useState([])
  const [loading, setLoading] = useState(true)
  const [selectedWorkout, setSelectedWorkout] = useState(null)
  const [resetConfirm, setResetConfirm] = useState(null)
  const [resetting, setResetting] = useState(false)
  const [successMessage, setSuccessMessage] = useState(null)

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

  // Auto-clear success message after 3 seconds
  useEffect(() => {
    if (successMessage) {
      const timer = setTimeout(() => setSuccessMessage(null), 3000)
      return () => clearTimeout(timer)
    }
  }, [successMessage])

  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 fetchCustomWorkouts = async () => {
    try {
      const token = localStorage.getItem('token')
      if (!token) return
      const res = await fetch(`${API_URL}/custom-workouts`, {
        headers: { 'Authorization': `Bearer ${token}` }
      })
      const data = await res.json()
      setCustomWorkouts(data || [])
    } catch (err) {
      console.error('Failed to fetch custom workouts:', err)
    }
  }

  const getCustomWorkoutId = (programDayId) => {
    const customWorkout = customWorkouts.find(cw => cw.source_program_day_id === programDayId)
    return customWorkout?.id
  }

  const isWorkoutCustom = (programDayId) => {
    return customWorkouts.some(cw => cw.source_program_day_id === programDayId)
  }

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

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

  const handleResetClick = (e, workoutId) => {
    e.stopPropagation()
    setResetConfirm(workoutId)
  }

  const handleConfirmReset = async () => {
    if (!resetConfirm) return

    setResetting(true)
    try {
      const token = localStorage.getItem('token')
      const res = await fetch(`${API_URL}/custom-workouts/${resetConfirm}`, {
        method: 'DELETE',
        headers: { 'Authorization': `Bearer ${token}` }
      })

      if (res.ok) {
        // Refresh custom workouts list
        await fetchCustomWorkouts()
        setSuccessMessage('Passet återställdes till original')
        setSelectedWorkout(null)
        setResetConfirm(null)
      } else {
        console.error('Failed to reset workout:', res.status)
      }
    } catch (err) {
      console.error('Error resetting workout:', err)
    } finally {
      setResetting(false)
    }
  }

  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>

        {successMessage && (
          <div className="success-message">
            <Icon name="check" size={18} />
            {successMessage}
          </div>
        )}

        <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
            const isCustom = isWorkoutCustom(workout.id)
            const customWorkoutId = getCustomWorkoutId(workout.id)

            return (
              <div
                key={workout.id}
                className={`workout-select-card ${isSelected ? 'selected' : ''}`}
                style={{ '--workout-color': color }}
                onClick={() => handleSelect(workout)}
              >
                <div className="workout-badge-container">
                  <div className="workout-icon" style={{ background: color }}>
                    <Icon name={iconName} size={28} />
                  </div>
                  <span className={`workout-badge ${isCustom ? 'custom' : 'program'}`}>
                    {isCustom ? 'Anpassad' : 'Program'}
                  </span>
                  {isCustom && (
                    <button
                      className="reset-btn"
                      title="Återställ till original"
                      onClick={(e) => handleResetClick(e, customWorkoutId)}
                      aria-label="Återställ workout"
                    >
                      <Icon name="refresh" size={16} />
                    </button>
                  )}
                </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>

      {/* Reset confirmation dialog */}
      {resetConfirm && (
        <div className="modal-overlay" onClick={() => setResetConfirm(null)}>
          <div className="modal-dialog" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h2>Återställ till original?</h2>
            </div>
            <div className="modal-body">
              <p>Är du säker? Dina ändringar kommer att försvinna och passet återställs till programversionen.</p>
            </div>
            <div className="modal-footer">
              <button
                className="modal-btn cancel"
                onClick={() => setResetConfirm(null)}
                disabled={resetting}
              >
                Avbryt
              </button>
              <button
                className="modal-btn confirm"
                onClick={handleConfirmReset}
                disabled={resetting}
              >
                {resetting ? 'Återställer...' : 'Återställ'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default WorkoutSelectPage
