'use client'

import { Lesson, QuizQuestion } from '@/lib/sdk/academy/types'

interface LessonsTabProps {
  sortedLessons: Lesson[]
  selectedLesson: Lesson | null
  onSelectLesson: (lesson: Lesson) => void
  quizAnswers: Record<string, number>
  onQuizAnswer: (answers: Record<string, number>) => void
  quizResult: any
  isSubmittingQuiz: boolean
  onSubmitQuiz: () => void
  onResetQuiz: () => void
  isEditing: boolean
  editTitle: string
  editContent: string
  onEditTitle: (v: string) => void
  onEditContent: (v: string) => void
  isSaving: boolean
  saveMessage: { type: 'success' | 'error'; text: string } | null
  onStartEdit: () => void
  onCancelEdit: () => void
  onSaveLesson: () => void
  onApproveLesson: () => void
}

export function LessonsTab({
  sortedLessons,
  selectedLesson,
  onSelectLesson,
  quizAnswers,
  onQuizAnswer,
  quizResult,
  isSubmittingQuiz,
  onSubmitQuiz,
  onResetQuiz,
  isEditing,
  editTitle,
  editContent,
  onEditTitle,
  onEditContent,
  isSaving,
  saveMessage,
  onStartEdit,
  onCancelEdit,
  onSaveLesson,
  onApproveLesson,
}: LessonsTabProps) {
  return (
    <div className="grid grid-cols-3 gap-6">
      {/* Lesson Navigation */}
      <div className="col-span-1 bg-white rounded-xl border border-gray-200 p-4">
        <h3 className="text-sm font-semibold text-gray-700 mb-3">Lektionen</h3>
        <div className="space-y-1">
          {sortedLessons.map((lesson, i) => (
            <button
              key={lesson.id}
              onClick={() => onSelectLesson(lesson)}
              className={`w-full text-left p-3 rounded-lg text-sm transition-colors ${
                selectedLesson?.id === lesson.id
                  ? 'bg-purple-50 text-purple-700 border border-purple-200'
                  : 'hover:bg-gray-50 text-gray-700'
              }`}
            >
              <div className="flex items-center gap-2">
                <span className="text-xs text-gray-400 w-4">{i + 1}.</span>
                <span className="truncate">{lesson.title}</span>
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* Lesson Content */}
      <div className="col-span-2 bg-white rounded-xl border border-gray-200 p-6">
        {selectedLesson ? (
          <div className="space-y-6">
            <div className="flex items-center justify-between">
              {isEditing ? (
                <input
                  type="text"
                  value={editTitle}
                  onChange={e => onEditTitle(e.target.value)}
                  className="text-xl font-semibold text-gray-900 border border-gray-300 rounded-lg px-3 py-1 flex-1 mr-3"
                />
              ) : (
                <h2 className="text-xl font-semibold text-gray-900">{selectedLesson.title}</h2>
              )}
              <div className="flex items-center gap-2">
                <span className={`px-3 py-1 text-xs rounded-full ${
                  selectedLesson.type === 'quiz' ? 'bg-yellow-100 text-yellow-700' :
                  selectedLesson.type === 'video' ? 'bg-blue-100 text-blue-700' :
                  'bg-gray-100 text-gray-600'
                }`}>
                  {selectedLesson.type === 'quiz' ? 'Quiz' : selectedLesson.type === 'video' ? 'Video' : 'Text'}
                </span>
                {selectedLesson.type !== 'quiz' && !isEditing && (
                  <>
                    <button onClick={onStartEdit} className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors">
                      Bearbeiten
                    </button>
                    <button onClick={onApproveLesson} disabled={isSaving} className="px-3 py-1 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50">
                      Freigeben
                    </button>
                  </>
                )}
                {isEditing && (
                  <>
                    <button onClick={onCancelEdit} className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors">
                      Abbrechen
                    </button>
                    <button onClick={onSaveLesson} disabled={isSaving} className="px-3 py-1 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50">
                      {isSaving ? 'Speichert...' : 'Speichern'}
                    </button>
                  </>
                )}
              </div>
            </div>

            {saveMessage && (
              <div className={`p-3 rounded-lg text-sm ${
                saveMessage.type === 'success' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'
              }`}>
                {saveMessage.text}
              </div>
            )}

            {selectedLesson.type === 'video' && selectedLesson.videoUrl && (
              <div className="aspect-video bg-gray-900 rounded-xl overflow-hidden">
                <video src={selectedLesson.videoUrl} controls className="w-full h-full" />
              </div>
            )}

            {isEditing && (selectedLesson.type === 'text' || selectedLesson.type === 'video') && (
              <div className="space-y-2">
                <label className="text-sm text-gray-500">Inhalt (Markdown)</label>
                <textarea
                  value={editContent}
                  onChange={e => onEditContent(e.target.value)}
                  rows={20}
                  className="w-full border border-gray-300 rounded-xl p-4 text-sm font-mono text-gray-800 leading-relaxed resize-y focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                  placeholder="Markdown-Inhalt der Lektion..."
                />
                <p className="text-xs text-gray-400">Unterstuetzt: # Ueberschrift, ## Unterueberschrift, - Aufzaehlung, **fett**</p>
              </div>
            )}

            {!isEditing && (selectedLesson.type === 'text' || selectedLesson.type === 'video') && selectedLesson.contentMarkdown && (
              <div className="prose prose-sm max-w-none">
                <div className="whitespace-pre-wrap text-gray-700 leading-relaxed">
                  {selectedLesson.contentMarkdown.split('\n').map((line, i) => {
                    if (line.startsWith('# ')) return <h1 key={i} className="text-2xl font-bold text-gray-900 mt-6 mb-3">{line.slice(2)}</h1>
                    if (line.startsWith('## ')) return <h2 key={i} className="text-xl font-semibold text-gray-900 mt-5 mb-2">{line.slice(3)}</h2>
                    if (line.startsWith('### ')) return <h3 key={i} className="text-lg font-medium text-gray-900 mt-4 mb-2">{line.slice(4)}</h3>
                    if (line.startsWith('- **')) {
                      const parts = line.slice(2).split('**')
                      return <li key={i} className="ml-4 list-disc"><strong>{parts[1]}</strong>{parts[2] || ''}</li>
                    }
                    if (line.startsWith('- ')) return <li key={i} className="ml-4 list-disc">{line.slice(2)}</li>
                    if (line.trim() === '') return <br key={i} />
                    return <p key={i} className="mb-2">{line}</p>
                  })}
                </div>
              </div>
            )}

            {selectedLesson.type === 'quiz' && selectedLesson.quizQuestions && (
              <div className="space-y-6">
                {selectedLesson.quizQuestions.map((q: QuizQuestion, qi: number) => (
                  <div key={q.id} className="bg-gray-50 rounded-xl p-5">
                    <h4 className="font-medium text-gray-900 mb-3">Frage {qi + 1}: {q.question}</h4>
                    <div className="space-y-2">
                      {q.options.map((option: string, oi: number) => {
                        const isSelected = quizAnswers[q.id] === oi
                        const showResult = quizResult && !quizResult.error
                        const isCorrect = showResult && quizResult.results?.[qi]?.correct
                        const wasSelected = showResult && isSelected

                        let bgClass = 'bg-white border-gray-200 hover:border-purple-300'
                        if (isSelected && !showResult) bgClass = 'bg-purple-50 border-purple-500'
                        if (showResult && oi === q.correctOptionIndex) bgClass = 'bg-green-50 border-green-500'
                        if (showResult && wasSelected && !isCorrect) bgClass = 'bg-red-50 border-red-500'

                        return (
                          <button
                            key={oi}
                            onClick={() => !quizResult && onQuizAnswer({ ...quizAnswers, [q.id]: oi })}
                            disabled={!!quizResult}
                            className={`w-full text-left p-3 rounded-lg border-2 transition-all ${bgClass}`}
                          >
                            <span className="text-sm text-gray-700">{String.fromCharCode(65 + oi)}) {option}</span>
                          </button>
                        )
                      })}
                    </div>
                    {quizResult && !quizResult.error && quizResult.results?.[qi] && (
                      <div className={`mt-3 p-3 rounded-lg text-sm ${
                        quizResult.results[qi].correct ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'
                      }`}>
                        {quizResult.results[qi].correct ? 'Richtig!' : 'Falsch.'} {q.explanation}
                      </div>
                    )}
                  </div>
                ))}

                {!quizResult ? (
                  <button
                    onClick={onSubmitQuiz}
                    disabled={isSubmittingQuiz || Object.keys(quizAnswers).length < (selectedLesson.quizQuestions?.length || 0)}
                    className="w-full py-3 bg-purple-600 text-white rounded-xl hover:bg-purple-700 transition-colors disabled:opacity-50 font-medium"
                  >
                    {isSubmittingQuiz ? 'Wird ausgewertet...' : 'Quiz auswerten'}
                  </button>
                ) : quizResult.error ? (
                  <div className="bg-red-50 border border-red-200 rounded-xl p-4 text-sm text-red-700">{quizResult.error}</div>
                ) : (
                  <div className={`rounded-xl p-6 text-center ${quizResult.passed ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'}`}>
                    <div className={`text-3xl font-bold ${quizResult.passed ? 'text-green-600' : 'text-red-600'}`}>
                      {quizResult.score}%
                    </div>
                    <div className={`text-sm mt-1 ${quizResult.passed ? 'text-green-700' : 'text-red-700'}`}>
                      {quizResult.passed ? 'Bestanden!' : 'Nicht bestanden'} — {quizResult.correctAnswers}/{quizResult.totalQuestions} richtig
                    </div>
                    <button onClick={onResetQuiz} className="mt-4 px-4 py-2 text-sm bg-white rounded-lg border hover:bg-gray-50">
                      Quiz wiederholen
                    </button>
                  </div>
                )}
              </div>
            )}
          </div>
        ) : (
          <p className="text-gray-500 text-center py-10">Waehlen Sie eine Lektion aus.</p>
        )}
      </div>
    </div>
  )
}
