'use client'

import { useState } from 'react'
import { Play, Clock, BookOpen, Users, ChevronDown, Info } from 'lucide-react'
import { LessonTemplate, PhaseDurations, Class } from '@/lib/companion/types'
import {
  SYSTEM_TEMPLATES,
  DEFAULT_PHASE_DURATIONS,
  PHASE_DISPLAY_NAMES,
  PHASE_ORDER,
  calculateTotalDuration,
  formatMinutes,
} from '@/lib/companion/constants'

interface LessonStartFormProps {
  onStart: (data: {
    classId: string
    subject: string
    topic?: string
    templateId?: string
  }) => void
  loading?: boolean
  availableClasses?: Class[]
}

// Mock classes for development
const MOCK_CLASSES: Class[] = [
  { id: 'c1', name: '9a', grade: '9', studentCount: 28 },
  { id: 'c2', name: '9b', grade: '9', studentCount: 26 },
  { id: 'c3', name: '10a', grade: '10', studentCount: 24 },
  { id: 'c4', name: 'Deutsch LK', grade: 'Q1', studentCount: 18 },
  { id: 'c5', name: 'Mathe GK', grade: 'Q2', studentCount: 22 },
]

const SUBJECTS = [
  'Deutsch',
  'Mathematik',
  'Englisch',
  'Biologie',
  'Physik',
  'Chemie',
  'Geschichte',
  'Geographie',
  'Politik',
  'Kunst',
  'Musik',
  'Sport',
  'Informatik',
  'Sonstiges',
]

export function LessonStartForm({
  onStart,
  loading,
  availableClasses = MOCK_CLASSES,
}: LessonStartFormProps) {
  const [selectedClass, setSelectedClass] = useState('')
  const [selectedSubject, setSelectedSubject] = useState('')
  const [topic, setTopic] = useState('')
  const [selectedTemplate, setSelectedTemplate] = useState<LessonTemplate | null>(
    SYSTEM_TEMPLATES[0] as LessonTemplate
  )
  const [showTemplateDetails, setShowTemplateDetails] = useState(false)

  const totalDuration = selectedTemplate
    ? calculateTotalDuration(selectedTemplate.durations)
    : calculateTotalDuration(DEFAULT_PHASE_DURATIONS)

  const canStart = selectedClass && selectedSubject

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!canStart) return

    onStart({
      classId: selectedClass,
      subject: selectedSubject,
      topic: topic || undefined,
      templateId: selectedTemplate?.templateId,
    })
  }

  return (
    <div className="bg-white border border-slate-200 rounded-xl p-6">
      <div className="flex items-center gap-3 mb-6">
        <div className="p-3 bg-blue-100 rounded-xl">
          <Play className="w-6 h-6 text-blue-600" />
        </div>
        <div>
          <h2 className="text-xl font-semibold text-slate-900">Neue Stunde starten</h2>
          <p className="text-sm text-slate-500">
            Waehlen Sie Klasse, Fach und Template
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Class Selection */}
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-2">
            <Users className="w-4 h-4 inline mr-2" />
            Klasse *
          </label>
          <select
            value={selectedClass}
            onChange={(e) => setSelectedClass(e.target.value)}
            className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white"
            required
          >
            <option value="">Klasse auswaehlen...</option>
            {availableClasses.map((cls) => (
              <option key={cls.id} value={cls.id}>
                {cls.name} ({cls.studentCount} Schueler)
              </option>
            ))}
          </select>
        </div>

        {/* Subject Selection */}
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-2">
            <BookOpen className="w-4 h-4 inline mr-2" />
            Fach *
          </label>
          <select
            value={selectedSubject}
            onChange={(e) => setSelectedSubject(e.target.value)}
            className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white"
            required
          >
            <option value="">Fach auswaehlen...</option>
            {SUBJECTS.map((subject) => (
              <option key={subject} value={subject}>
                {subject}
              </option>
            ))}
          </select>
        </div>

        {/* Topic (Optional) */}
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-2">
            Thema (optional)
          </label>
          <input
            type="text"
            value={topic}
            onChange={(e) => setTopic(e.target.value)}
            placeholder="z.B. Quadratische Funktionen, Gedichtanalyse..."
            className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          />
        </div>

        {/* Template Selection */}
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-2">
            <Clock className="w-4 h-4 inline mr-2" />
            Template
          </label>
          <div className="space-y-2">
            {SYSTEM_TEMPLATES.map((template) => {
              const tpl = template as LessonTemplate
              const isSelected = selectedTemplate?.templateId === tpl.templateId
              const total = calculateTotalDuration(tpl.durations)

              return (
                <button
                  key={tpl.templateId}
                  type="button"
                  onClick={() => setSelectedTemplate(tpl)}
                  className={`
                    w-full p-4 rounded-xl border text-left transition-all
                    ${isSelected
                      ? 'border-blue-500 bg-blue-50 ring-2 ring-blue-500/20'
                      : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'
                    }
                  `}
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <p className={`font-medium ${isSelected ? 'text-blue-900' : 'text-slate-900'}`}>
                        {tpl.name}
                      </p>
                      <p className="text-sm text-slate-500">{tpl.description}</p>
                    </div>
                    <span className={`text-sm font-medium ${isSelected ? 'text-blue-600' : 'text-slate-500'}`}>
                      {formatMinutes(total)}
                    </span>
                  </div>
                </button>
              )
            })}
          </div>

          {/* Template Details Toggle */}
          {selectedTemplate && (
            <button
              type="button"
              onClick={() => setShowTemplateDetails(!showTemplateDetails)}
              className="mt-3 flex items-center gap-2 text-sm text-slate-600 hover:text-slate-900"
            >
              <Info className="w-4 h-4" />
              Phasendauern anzeigen
              <ChevronDown className={`w-4 h-4 transition-transform ${showTemplateDetails ? 'rotate-180' : ''}`} />
            </button>
          )}

          {/* Template Details */}
          {showTemplateDetails && selectedTemplate && (
            <div className="mt-3 p-4 bg-slate-50 rounded-xl">
              <div className="grid grid-cols-5 gap-2">
                {PHASE_ORDER.map((phaseId) => (
                  <div key={phaseId} className="text-center">
                    <p className="text-xs text-slate-500">{PHASE_DISPLAY_NAMES[phaseId]}</p>
                    <p className="font-medium text-slate-900">
                      {selectedTemplate.durations[phaseId]} Min
                    </p>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Summary & Start Button */}
        <div className="pt-4 border-t border-slate-200">
          <div className="flex items-center justify-between mb-4">
            <div className="text-sm text-slate-600">
              Gesamtdauer: <span className="font-semibold">{formatMinutes(totalDuration)}</span>
            </div>
            {selectedClass && (
              <div className="text-sm text-slate-600">
                Klasse: <span className="font-semibold">
                  {availableClasses.find((c) => c.id === selectedClass)?.name}
                </span>
              </div>
            )}
          </div>

          <button
            type="submit"
            disabled={!canStart || loading}
            className={`
              w-full py-4 px-6 rounded-xl font-semibold text-lg
              flex items-center justify-center gap-3
              transition-all duration-200
              ${canStart && !loading
                ? 'bg-blue-600 hover:bg-blue-700 text-white shadow-lg shadow-blue-500/25'
                : 'bg-slate-200 text-slate-500 cursor-not-allowed'
              }
            `}
          >
            {loading ? (
              <>
                <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                Stunde wird gestartet...
              </>
            ) : (
              <>
                <Play className="w-5 h-5" />
                Stunde starten
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  )
}
