import { useState, useEffect } from 'react'
import { api } from '../utils/api'

/**
 * TrainingTypeSelect - Two-level dropdown for training type selection
 *
 * @param {number|null} value - Selected training_type_id
 * @param {function} onChange - Callback (training_type_id, category, subcategory) => void
 * @param {boolean} required - Is selection required?
 */
export default function TrainingTypeSelect({ value, onChange, required = false }) {
  const [types, setTypes] = useState({})         // Grouped by category
  const [categories, setCategories] = useState({}) // Category metadata
  const [selectedCategory, setSelectedCategory] = useState('')
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    Promise.all([
      api.listTrainingTypes(),
      api.getTrainingCategories()
    ]).then(([typesData, catsData]) => {
      setTypes(typesData)
      setCategories(catsData)

      // If value is set, find and select the category
      if (value) {
        for (const cat in typesData) {
          const found = typesData[cat].find(t => t.id === value)
          if (found) {
            setSelectedCategory(cat)
            break
          }
        }
      }

      setLoading(false)
    }).catch(err => {
      console.error('Failed to load training types:', err)
      setLoading(false)
    })
  }, [value])

  const handleCategoryChange = (cat) => {
    setSelectedCategory(cat)
    // Auto-select first subcategory if available
    if (types[cat] && types[cat].length > 0) {
      const firstType = types[cat][0]
      onChange(firstType.id, firstType.category, firstType.subcategory)
    } else {
      onChange(null, null, null)
    }
  }

  const handleTypeChange = (typeId) => {
    const type = Object.values(types)
      .flat()
      .find(t => t.id === parseInt(typeId))

    if (type) {
      onChange(type.id, type.category, type.subcategory)
    }
  }

  if (loading) {
    return <div style={{fontSize:13, color:'var(--text3)'}}>Lade Trainingstypen...</div>
  }

  const availableCategories = Object.keys(categories)
  const availableTypes = selectedCategory ? (types[selectedCategory] || []) : []

  return (
    <div style={{display:'flex', gap:8, flexDirection:'column'}}>
      {/* Category dropdown */}
      <div>
        <label className="form-label">Kategorie</label>
        <select
          className="form-input"
          value={selectedCategory}
          onChange={(e) => handleCategoryChange(e.target.value)}
          required={required}
          style={{width:'100%', boxSizing:'border-box'}}
        >
          <option value="">-- Wähle Kategorie --</option>
          {availableCategories.map(cat => (
            <option key={cat} value={cat}>
              {categories[cat].icon} {categories[cat].name_de}
            </option>
          ))}
        </select>
      </div>

      {/* Subcategory dropdown (conditional) */}
      {selectedCategory && availableTypes.length > 0 && (
        <div>
          <label className="form-label">Untertyp</label>
          <select
            className="form-input"
            value={value || ''}
            onChange={(e) => handleTypeChange(e.target.value)}
            required={required}
            style={{width:'100%', boxSizing:'border-box'}}
          >
            <option value="">-- Wähle Untertyp --</option>
            {availableTypes.map(type => (
              <option key={type.id} value={type.id}>
                {type.icon} {type.name_de}
              </option>
            ))}
          </select>
        </div>
      )}
    </div>
  )
}
