'use client'

/**
 * AnnotationPanel
 *
 * Panel for viewing, editing, and managing annotations.
 * Shows a list of all annotations with options to edit text, change severity, or delete.
 */

import { useState } from 'react'
import type { Annotation, AnnotationType } from '../types'
import { ANNOTATION_COLORS } from '../types'

interface AnnotationPanelProps {
  annotations: Annotation[]
  selectedAnnotation: Annotation | null
  onSelectAnnotation: (annotation: Annotation | null) => void
  onUpdateAnnotation: (id: string, updates: Partial<Annotation>) => void
  onDeleteAnnotation: (id: string) => void
}

const SEVERITY_OPTIONS = [
  { value: 'minor', label: 'Leicht', color: '#fbbf24' },
  { value: 'major', label: 'Mittel', color: '#f97316' },
  { value: 'critical', label: 'Schwer', color: '#dc2626' },
] as const

const TYPE_LABELS: Record<AnnotationType, string> = {
  rechtschreibung: 'Rechtschreibung',
  grammatik: 'Grammatik',
  inhalt: 'Inhalt',
  struktur: 'Struktur',
  stil: 'Stil',
  comment: 'Kommentar',
  highlight: 'Markierung',
}

export default function AnnotationPanel({
  annotations,
  selectedAnnotation,
  onSelectAnnotation,
  onUpdateAnnotation,
  onDeleteAnnotation,
}: AnnotationPanelProps) {
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editText, setEditText] = useState('')
  const [editSuggestion, setEditSuggestion] = useState('')

  // Group annotations by type
  const groupedAnnotations = annotations.reduce(
    (acc, ann) => {
      if (!acc[ann.type]) {
        acc[ann.type] = []
      }
      acc[ann.type].push(ann)
      return acc
    },
    {} as Record<AnnotationType, Annotation[]>
  )

  const handleEdit = (annotation: Annotation) => {
    setEditingId(annotation.id)
    setEditText(annotation.text)
    setEditSuggestion(annotation.suggestion || '')
  }

  const handleSaveEdit = (id: string) => {
    onUpdateAnnotation(id, { text: editText, suggestion: editSuggestion || undefined })
    setEditingId(null)
    setEditText('')
    setEditSuggestion('')
  }

  const handleCancelEdit = () => {
    setEditingId(null)
    setEditText('')
    setEditSuggestion('')
  }

  if (annotations.length === 0) {
    return (
      <div className="p-4 text-center text-slate-500">
        <svg className="w-12 h-12 mx-auto mb-3 text-slate-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={1.5}
            d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z"
          />
        </svg>
        <p className="text-sm">Keine Annotationen vorhanden</p>
        <p className="text-xs mt-1">Waehlen Sie ein Werkzeug und markieren Sie Stellen im Dokument</p>
      </div>
    )
  }

  return (
    <div className="h-full overflow-auto">
      {/* Summary */}
      <div className="p-3 border-b border-slate-200 bg-slate-50">
        <div className="flex items-center justify-between text-sm">
          <span className="font-medium text-slate-700">{annotations.length} Annotationen</span>
          <div className="flex gap-2">
            {Object.entries(groupedAnnotations).map(([type, anns]) => (
              <span
                key={type}
                className="px-2 py-0.5 text-xs rounded-full text-white"
                style={{ backgroundColor: ANNOTATION_COLORS[type as AnnotationType] }}
              >
                {anns.length}
              </span>
            ))}
          </div>
        </div>
      </div>

      {/* Annotations list by type */}
      <div className="divide-y divide-slate-100">
        {(Object.entries(groupedAnnotations) as [AnnotationType, Annotation[]][]).map(([type, anns]) => (
          <div key={type}>
            {/* Type header */}
            <div
              className="px-3 py-2 text-xs font-semibold text-white"
              style={{ backgroundColor: ANNOTATION_COLORS[type] }}
            >
              {TYPE_LABELS[type]} ({anns.length})
            </div>

            {/* Annotations in this type */}
            {anns.map((annotation) => {
              const isSelected = selectedAnnotation?.id === annotation.id
              const isEditing = editingId === annotation.id
              const severityInfo = SEVERITY_OPTIONS.find((s) => s.value === annotation.severity)

              return (
                <div
                  key={annotation.id}
                  className={`p-3 cursor-pointer transition-colors ${
                    isSelected ? 'bg-blue-50 border-l-4 border-blue-500' : 'hover:bg-slate-50'
                  }`}
                  onClick={() => onSelectAnnotation(isSelected ? null : annotation)}
                >
                  {isEditing ? (
                    /* Edit mode */
                    <div className="space-y-2" onClick={(e) => e.stopPropagation()}>
                      <textarea
                        value={editText}
                        onChange={(e) => setEditText(e.target.value)}
                        placeholder="Kommentar..."
                        className="w-full p-2 text-sm border border-slate-300 rounded resize-none focus:ring-2 focus:ring-primary-500"
                        rows={2}
                        autoFocus
                      />

                      {(type === 'rechtschreibung' || type === 'grammatik') && (
                        <input
                          type="text"
                          value={editSuggestion}
                          onChange={(e) => setEditSuggestion(e.target.value)}
                          placeholder="Korrekturvorschlag..."
                          className="w-full p-2 text-sm border border-slate-300 rounded focus:ring-2 focus:ring-primary-500"
                        />
                      )}

                      <div className="flex gap-2">
                        <button
                          onClick={() => handleSaveEdit(annotation.id)}
                          className="flex-1 py-1 text-xs bg-primary-600 text-white rounded hover:bg-primary-700"
                        >
                          Speichern
                        </button>
                        <button
                          onClick={handleCancelEdit}
                          className="flex-1 py-1 text-xs bg-slate-200 text-slate-700 rounded hover:bg-slate-300"
                        >
                          Abbrechen
                        </button>
                      </div>
                    </div>
                  ) : (
                    /* View mode */
                    <>
                      {/* Severity badge */}
                      <div className="flex items-center justify-between mb-1">
                        <span
                          className="px-1.5 py-0.5 text-[10px] rounded text-white"
                          style={{ backgroundColor: severityInfo?.color || '#6b7280' }}
                        >
                          {severityInfo?.label || 'Unbekannt'}
                        </span>
                        <span className="text-[10px] text-slate-400">Seite {annotation.page}</span>
                      </div>

                      {/* Text */}
                      {annotation.text && <p className="text-sm text-slate-700 mb-1">{annotation.text}</p>}

                      {/* Suggestion */}
                      {annotation.suggestion && (
                        <p className="text-xs text-green-700 bg-green-50 px-2 py-1 rounded mb-1">
                          <span className="font-medium">Korrektur:</span> {annotation.suggestion}
                        </p>
                      )}

                      {/* Actions (only when selected) */}
                      {isSelected && (
                        <div className="flex gap-2 mt-2 pt-2 border-t border-slate-200">
                          <button
                            onClick={(e) => {
                              e.stopPropagation()
                              handleEdit(annotation)
                            }}
                            className="flex-1 py-1 text-xs bg-slate-100 text-slate-700 rounded hover:bg-slate-200"
                          >
                            Bearbeiten
                          </button>

                          {/* Severity buttons */}
                          <div className="flex gap-1">
                            {SEVERITY_OPTIONS.map((sev) => (
                              <button
                                key={sev.value}
                                onClick={(e) => {
                                  e.stopPropagation()
                                  onUpdateAnnotation(annotation.id, { severity: sev.value })
                                }}
                                className={`w-6 h-6 rounded text-xs text-white font-bold ${
                                  annotation.severity === sev.value ? 'ring-2 ring-offset-1 ring-slate-400' : ''
                                }`}
                                style={{ backgroundColor: sev.color }}
                                title={sev.label}
                              >
                                {sev.label[0]}
                              </button>
                            ))}
                          </div>

                          <button
                            onClick={(e) => {
                              e.stopPropagation()
                              if (confirm('Annotation loeschen?')) {
                                onDeleteAnnotation(annotation.id)
                              }
                            }}
                            className="px-2 py-1 text-xs bg-red-100 text-red-700 rounded hover:bg-red-200"
                          >
                            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                strokeWidth={2}
                                d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                              />
                            </svg>
                          </button>
                        </div>
                      )}
                    </>
                  )}
                </div>
              )
            })}
          </div>
        ))}
      </div>
    </div>
  )
}
