'use client'

// =============================================================================
// Step 2: Data Categories
// Data categories and data subjects selection
// =============================================================================

import React, { useState, useEffect } from 'react'
import { useTOMGenerator } from '@/lib/sdk/tom-generator'
import {
  DataProfile,
  DataCategory,
  DataSubject,
  DataVolume,
  DATA_CATEGORIES_METADATA,
  DATA_SUBJECTS_METADATA,
} from '@/lib/sdk/tom-generator/types'

// =============================================================================
// CONSTANTS
// =============================================================================

const DATA_VOLUMES: { value: DataVolume; label: string; description: string }[] = [
  { value: 'LOW', label: 'Niedrig', description: '< 1.000 Datensätze' },
  { value: 'MEDIUM', label: 'Mittel', description: '1.000 - 100.000 Datensätze' },
  { value: 'HIGH', label: 'Hoch', description: '100.000 - 1 Mio. Datensätze' },
  { value: 'VERY_HIGH', label: 'Sehr hoch', description: '> 1 Mio. Datensätze' },
]

// =============================================================================
// COMPONENT
// =============================================================================

export function DataCategoriesStep() {
  const { state, setDataProfile, completeCurrentStep } = useTOMGenerator()

  const [formData, setFormData] = useState<Partial<DataProfile>>({
    categories: [],
    subjects: [],
    hasSpecialCategories: false,
    processesMinors: false,
    dataVolume: 'MEDIUM',
    thirdCountryTransfers: false,
    thirdCountryList: [],
  })

  const [thirdCountryInput, setThirdCountryInput] = useState('')

  // Load existing data
  useEffect(() => {
    if (state.dataProfile) {
      setFormData(state.dataProfile)
    }
  }, [state.dataProfile])

  // Check for special categories
  useEffect(() => {
    const hasSpecial = formData.categories?.some((cat) => {
      const meta = DATA_CATEGORIES_METADATA.find((m) => m.id === cat)
      return meta?.isSpecialCategory
    })
    setFormData((prev) => ({ ...prev, hasSpecialCategories: hasSpecial || false }))
  }, [formData.categories])

  // Check for minors
  useEffect(() => {
    const hasMinors = formData.subjects?.includes('MINORS')
    setFormData((prev) => ({ ...prev, processesMinors: hasMinors || false }))
  }, [formData.subjects])

  // Handle category toggle
  const toggleCategory = (category: DataCategory) => {
    setFormData((prev) => {
      const current = prev.categories || []
      const updated = current.includes(category)
        ? current.filter((c) => c !== category)
        : [...current, category]
      return { ...prev, categories: updated }
    })
  }

  // Handle subject toggle
  const toggleSubject = (subject: DataSubject) => {
    setFormData((prev) => {
      const current = prev.subjects || []
      const updated = current.includes(subject)
        ? current.filter((s) => s !== subject)
        : [...current, subject]
      return { ...prev, subjects: updated }
    })
  }

  // Handle third country addition
  const addThirdCountry = () => {
    if (thirdCountryInput.trim()) {
      setFormData((prev) => ({
        ...prev,
        thirdCountryList: [...(prev.thirdCountryList || []), thirdCountryInput.trim()],
      }))
      setThirdCountryInput('')
    }
  }

  const removeThirdCountry = (index: number) => {
    setFormData((prev) => ({
      ...prev,
      thirdCountryList: (prev.thirdCountryList || []).filter((_, i) => i !== index),
    }))
  }

  // Handle submit
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()

    const profile: DataProfile = {
      categories: formData.categories || [],
      subjects: formData.subjects || [],
      hasSpecialCategories: formData.hasSpecialCategories || false,
      processesMinors: formData.processesMinors || false,
      dataVolume: formData.dataVolume || 'MEDIUM',
      thirdCountryTransfers: formData.thirdCountryTransfers || false,
      thirdCountryList: formData.thirdCountryList || [],
    }

    setDataProfile(profile)
    completeCurrentStep(profile)
  }

  const selectedSpecialCategories = (formData.categories || []).filter((cat) => {
    const meta = DATA_CATEGORIES_METADATA.find((m) => m.id === cat)
    return meta?.isSpecialCategory
  })

  return (
    <form onSubmit={handleSubmit} className="space-y-8">
      {/* Data Categories */}
      <div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">Datenkategorien</h3>
        <p className="text-sm text-gray-600 mb-4">
          Wählen Sie alle Kategorien personenbezogener Daten, die Sie verarbeiten.
        </p>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {DATA_CATEGORIES_METADATA.map((category) => (
            <label
              key={category.id}
              className={`relative flex items-start p-3 border rounded-lg cursor-pointer transition-all ${
                formData.categories?.includes(category.id)
                  ? category.isSpecialCategory
                    ? 'border-amber-500 bg-amber-50'
                    : 'border-blue-500 bg-blue-50'
                  : 'border-gray-200 hover:border-gray-300'
              }`}
            >
              <input
                type="checkbox"
                checked={formData.categories?.includes(category.id) || false}
                onChange={() => toggleCategory(category.id)}
                className="sr-only"
              />
              <div className="flex-1">
                <div className="flex items-center gap-2">
                  <span className="font-medium text-gray-900">{category.name.de}</span>
                  {category.isSpecialCategory && (
                    <span className="px-2 py-0.5 text-xs font-medium bg-amber-100 text-amber-800 rounded">
                      Art. 9
                    </span>
                  )}
                </div>
              </div>
              {formData.categories?.includes(category.id) && (
                <svg className="w-5 h-5 text-blue-500 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                </svg>
              )}
            </label>
          ))}
        </div>

        {/* Special Categories Warning */}
        {selectedSpecialCategories.length > 0 && (
          <div className="mt-4 bg-amber-50 border border-amber-200 rounded-lg p-4">
            <div className="flex gap-3">
              <svg className="w-5 h-5 text-amber-500 flex-shrink-0 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
              </svg>
              <div>
                <h4 className="font-medium text-amber-900">Besondere Kategorien nach Art. 9 DSGVO</h4>
                <p className="text-sm text-amber-700 mt-1">
                  Sie verarbeiten besonders schützenswerte Daten. Dies erfordert zusätzliche Schutzmaßnahmen
                  und möglicherweise eine Datenschutz-Folgenabschätzung (DSFA).
                </p>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Data Subjects */}
      <div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">Betroffene Personen</h3>
        <p className="text-sm text-gray-600 mb-4">
          Wählen Sie alle Personengruppen, deren Daten Sie verarbeiten.
        </p>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {DATA_SUBJECTS_METADATA.map((subject) => (
            <label
              key={subject.id}
              className={`relative flex items-start p-3 border rounded-lg cursor-pointer transition-all ${
                formData.subjects?.includes(subject.id)
                  ? subject.isVulnerable
                    ? 'border-red-500 bg-red-50'
                    : 'border-blue-500 bg-blue-50'
                  : 'border-gray-200 hover:border-gray-300'
              }`}
            >
              <input
                type="checkbox"
                checked={formData.subjects?.includes(subject.id) || false}
                onChange={() => toggleSubject(subject.id)}
                className="sr-only"
              />
              <div className="flex-1">
                <div className="flex items-center gap-2">
                  <span className="font-medium text-gray-900">{subject.name.de}</span>
                  {subject.isVulnerable && (
                    <span className="px-2 py-0.5 text-xs font-medium bg-red-100 text-red-800 rounded">
                      Schutzbedürftig
                    </span>
                  )}
                </div>
              </div>
              {formData.subjects?.includes(subject.id) && (
                <svg className="w-5 h-5 text-blue-500 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                </svg>
              )}
            </label>
          ))}
        </div>

        {/* Minors Warning */}
        {formData.subjects?.includes('MINORS') && (
          <div className="mt-4 bg-red-50 border border-red-200 rounded-lg p-4">
            <div className="flex gap-3">
              <svg className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
              </svg>
              <div>
                <h4 className="font-medium text-red-900">Verarbeitung von Minderjährigen-Daten</h4>
                <p className="text-sm text-red-700 mt-1">
                  Die Verarbeitung von Daten Minderjähriger erfordert besondere Schutzmaßnahmen nach Art. 8 DSGVO
                  und erhöhte Sorgfaltspflichten.
                </p>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Data Volume */}
      <div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">Datenvolumen</h3>
        <p className="text-sm text-gray-600 mb-4">
          Geschätzte Anzahl der Datensätze, die Sie verarbeiten.
        </p>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {DATA_VOLUMES.map((volume) => (
            <label
              key={volume.value}
              className={`relative flex flex-col items-center p-4 border rounded-lg cursor-pointer transition-all text-center ${
                formData.dataVolume === volume.value
                  ? 'border-blue-500 bg-blue-50'
                  : 'border-gray-200 hover:border-gray-300'
              }`}
            >
              <input
                type="radio"
                name="dataVolume"
                value={volume.value}
                checked={formData.dataVolume === volume.value}
                onChange={(e) => setFormData((prev) => ({ ...prev, dataVolume: e.target.value as DataVolume }))}
                className="sr-only"
              />
              <span className="font-medium text-gray-900">{volume.label}</span>
              <span className="text-xs text-gray-500 mt-1">{volume.description}</span>
            </label>
          ))}
        </div>
      </div>

      {/* Third Country Transfers */}
      <div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">Drittlandübermittlungen</h3>
        <p className="text-sm text-gray-600 mb-4">
          Werden Daten in Länder außerhalb der EU/EWR übermittelt?
        </p>

        <div className="space-y-4">
          <label className="flex items-center gap-3 cursor-pointer">
            <input
              type="checkbox"
              checked={formData.thirdCountryTransfers || false}
              onChange={(e) => setFormData((prev) => ({ ...prev, thirdCountryTransfers: e.target.checked }))}
              className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
            <span className="text-gray-700">
              Ja, wir übermitteln Daten in Drittländer
            </span>
          </label>

          {formData.thirdCountryTransfers && (
            <div className="pl-8">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Zielländer
              </label>
              <div className="flex gap-2">
                <input
                  type="text"
                  value={thirdCountryInput}
                  onChange={(e) => setThirdCountryInput(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), addThirdCountry())}
                  className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="z.B. USA, Schweiz, UK"
                />
                <button
                  type="button"
                  onClick={addThirdCountry}
                  className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200"
                >
                  Hinzufügen
                </button>
              </div>
              {formData.thirdCountryList && formData.thirdCountryList.length > 0 && (
                <div className="flex flex-wrap gap-2 mt-2">
                  {formData.thirdCountryList.map((country, index) => (
                    <span
                      key={index}
                      className="inline-flex items-center gap-1 px-3 py-1 bg-gray-100 text-gray-800 rounded-full text-sm"
                    >
                      {country}
                      <button
                        type="button"
                        onClick={() => removeThirdCountry(index)}
                        className="hover:text-gray-600"
                      >
                        <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>
              )}

              {formData.thirdCountryList?.includes('USA') && (
                <div className="mt-3 bg-yellow-50 border border-yellow-200 rounded-lg p-3">
                  <p className="text-sm text-yellow-800">
                    <strong>Hinweis:</strong> Für Übermittlungen in die USA ist seit dem EU-US Data Privacy Framework
                    ein Angemessenheitsbeschluss vorhanden. Prüfen Sie, ob Ihr US-Partner zertifiziert ist.
                  </p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </form>
  )
}

export default DataCategoriesStep
