'use client'

import React, { useState } from 'react'
import { DSFA, DSFA_LEGAL_BASES } from '@/lib/sdk/dsfa/types'

interface SectionProps {
  dsfa: DSFA
  onUpdate: (data: Record<string, unknown>) => Promise<void>
  isSubmitting: boolean
}

export function Section1Editor({ dsfa, onUpdate, isSubmitting }: SectionProps) {
  const [formData, setFormData] = useState({
    processing_description: dsfa.processing_description || '',
    processing_purpose: dsfa.processing_purpose || '',
    data_categories: dsfa.data_categories || [],
    data_subjects: dsfa.data_subjects || [],
    recipients: dsfa.recipients || [],
    legal_basis: dsfa.legal_basis || '',
    legal_basis_details: dsfa.legal_basis_details || '',
  })
  const [newCategory, setNewCategory] = useState('')
  const [newSubject, setNewSubject] = useState('')
  const [newRecipient, setNewRecipient] = useState('')

  const handleSave = () => {
    onUpdate(formData)
  }

  const addItem = (field: 'data_categories' | 'data_subjects' | 'recipients', value: string, setter: (v: string) => void) => {
    if (value.trim()) {
      setFormData(prev => ({
        ...prev,
        [field]: [...prev[field], value.trim()]
      }))
      setter('')
    }
  }

  const removeItem = (field: 'data_categories' | 'data_subjects' | 'recipients', index: number) => {
    setFormData(prev => ({
      ...prev,
      [field]: prev[field].filter((_, i) => i !== index)
    }))
  }

  return (
    <div className="space-y-6">
      {/* Processing Purpose */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Verarbeitungszweck *
        </label>
        <textarea
          value={formData.processing_purpose}
          onChange={(e) => setFormData(prev => ({ ...prev, processing_purpose: e.target.value }))}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          rows={3}
          placeholder="Beschreiben Sie den Zweck der Datenverarbeitung..."
        />
      </div>

      {/* Processing Description */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Beschreibung der Verarbeitung *
        </label>
        <textarea
          value={formData.processing_description}
          onChange={(e) => setFormData(prev => ({ ...prev, processing_description: e.target.value }))}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          rows={4}
          placeholder="Detaillierte Beschreibung der Verarbeitungsvorgaenge..."
        />
      </div>

      {/* Data Categories */}
      <TagListField
        label="Datenkategorien *"
        items={formData.data_categories}
        newValue={newCategory}
        onNewValueChange={setNewCategory}
        onAdd={() => addItem('data_categories', newCategory, setNewCategory)}
        onRemove={(idx) => removeItem('data_categories', idx)}
        placeholder="Kategorie hinzufuegen..."
        colorClass="bg-blue-100 text-blue-700"
        hoverClass="hover:text-blue-900"
      />

      {/* Data Subjects */}
      <TagListField
        label="Betroffene Personen *"
        items={formData.data_subjects}
        newValue={newSubject}
        onNewValueChange={setNewSubject}
        onAdd={() => addItem('data_subjects', newSubject, setNewSubject)}
        onRemove={(idx) => removeItem('data_subjects', idx)}
        placeholder="z.B. Kunden, Mitarbeiter..."
        colorClass="bg-green-100 text-green-700"
        hoverClass="hover:text-green-900"
      />

      {/* Recipients */}
      <TagListField
        label="Empfaenger"
        items={formData.recipients}
        newValue={newRecipient}
        onNewValueChange={setNewRecipient}
        onAdd={() => addItem('recipients', newRecipient, setNewRecipient)}
        onRemove={(idx) => removeItem('recipients', idx)}
        placeholder="Empfaenger hinzufuegen..."
        colorClass="bg-orange-100 text-orange-700"
        hoverClass="hover:text-orange-900"
      />

      {/* Legal Basis */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Rechtsgrundlage *
        </label>
        <select
          value={formData.legal_basis}
          onChange={(e) => setFormData(prev => ({ ...prev, legal_basis: e.target.value }))}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
        >
          <option value="">Bitte waehlen...</option>
          {Object.entries(DSFA_LEGAL_BASES).map(([key, label]) => (
            <option key={key} value={key}>{label}</option>
          ))}
        </select>
      </div>

      {/* Legal Basis Details */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Begruendung der Rechtsgrundlage
        </label>
        <textarea
          value={formData.legal_basis_details}
          onChange={(e) => setFormData(prev => ({ ...prev, legal_basis_details: e.target.value }))}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          rows={3}
          placeholder="Erlaeutern Sie, warum diese Rechtsgrundlage anwendbar ist..."
        />
      </div>

      {/* Save Button */}
      <div className="flex justify-end pt-4 border-t border-gray-200">
        <button
          onClick={handleSave}
          disabled={isSubmitting}
          className="px-6 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors"
        >
          {isSubmitting ? 'Speichern...' : 'Abschnitt speichern'}
        </button>
      </div>
    </div>
  )
}

/** Reusable tag-list input used for data_categories, data_subjects, recipients */
function TagListField({
  label,
  items,
  newValue,
  onNewValueChange,
  onAdd,
  onRemove,
  placeholder,
  colorClass,
  hoverClass,
}: {
  label: string
  items: string[]
  newValue: string
  onNewValueChange: (v: string) => void
  onAdd: () => void
  onRemove: (idx: number) => void
  placeholder: string
  colorClass: string
  hoverClass: string
}) {
  return (
    <div>
      <label className="block text-sm font-medium text-gray-700 mb-2">{label}</label>
      <div className="flex flex-wrap gap-2 mb-2">
        {items.map((item, idx) => (
          <span key={idx} className={`px-3 py-1 ${colorClass} rounded-full text-sm flex items-center gap-2`}>
            {item}
            <button onClick={() => onRemove(idx)} className={hoverClass}>
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </span>
        ))}
      </div>
      <div className="flex gap-2">
        <input
          type="text"
          value={newValue}
          onChange={(e) => onNewValueChange(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && onAdd()}
          className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
          placeholder={placeholder}
        />
        <button
          onClick={onAdd}
          className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700"
        >
          +
        </button>
      </div>
    </div>
  )
}
