'use client'

import React, { useState, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import { useSDK } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
import { DocumentUploadSection, type UploadedDocument } from '@/components/sdk'

// =============================================================================
// TYPES
// =============================================================================

interface ProcessingActivity {
  id: string
  name: string
  description: string
  purpose: string
  legalBasis: string
  dataCategories: string[]
  dataSubjects: string[]
  recipients: string[]
  thirdCountryTransfers: boolean
  retentionPeriod: string
  toms: string[]
  status: 'active' | 'draft' | 'archived'
  lastUpdated: Date
  responsible: string
}

// =============================================================================
// MOCK DATA
// =============================================================================

const mockActivities: ProcessingActivity[] = [
  {
    id: 'vvt-1',
    name: 'Personalverwaltung',
    description: 'Verarbeitung von Mitarbeiterdaten fuer HR-Zwecke',
    purpose: 'Durchfuehrung des Beschaeftigungsverhaeltnisses',
    legalBasis: 'Art. 6 Abs. 1 lit. b, Art. 88 DSGVO i.V.m. BDSG',
    dataCategories: ['Stammdaten', 'Kontaktdaten', 'Gehaltsdaten', 'Bankverbindung'],
    dataSubjects: ['Mitarbeiter', 'Bewerber'],
    recipients: ['Lohnbuero', 'Finanzamt', 'Sozialversicherungstraeger'],
    thirdCountryTransfers: false,
    retentionPeriod: '10 Jahre nach Ende des Beschaeftigungsverhaeltnisses',
    toms: ['Zugriffskontrolle', 'Verschluesselung', 'Protokollierung'],
    status: 'active',
    lastUpdated: new Date('2024-01-15'),
    responsible: 'HR-Abteilung',
  },
  {
    id: 'vvt-2',
    name: 'Kundenverwaltung (CRM)',
    description: 'Verwaltung von Kundenbeziehungen und Vertriebsaktivitaeten',
    purpose: 'Vertragserfuellung und Kundenbetreuung',
    legalBasis: 'Art. 6 Abs. 1 lit. b DSGVO',
    dataCategories: ['Kontaktdaten', 'Kaufhistorie', 'Kommunikationsverlauf'],
    dataSubjects: ['Kunden', 'Interessenten'],
    recipients: ['Vertrieb', 'Kundenservice'],
    thirdCountryTransfers: true,
    retentionPeriod: '3 Jahre nach letzter Interaktion',
    toms: ['Zugriffskontrolle', 'Backups', 'Verschluesselung'],
    status: 'active',
    lastUpdated: new Date('2024-01-10'),
    responsible: 'Vertriebsleitung',
  },
  {
    id: 'vvt-3',
    name: 'Newsletter-Marketing',
    description: 'Versand von Marketing-E-Mails und Newslettern',
    purpose: 'Direktmarketing und Kundenbindung',
    legalBasis: 'Art. 6 Abs. 1 lit. a DSGVO (Einwilligung)',
    dataCategories: ['E-Mail-Adresse', 'Name', 'Interaktionsdaten'],
    dataSubjects: ['Newsletter-Abonnenten'],
    recipients: ['Marketing-Abteilung', 'E-Mail-Dienstleister'],
    thirdCountryTransfers: true,
    retentionPeriod: 'Bis zum Widerruf der Einwilligung',
    toms: ['Double-Opt-In', 'Abmeldelink', 'Protokollierung'],
    status: 'active',
    lastUpdated: new Date('2024-01-20'),
    responsible: 'Marketing',
  },
  {
    id: 'vvt-4',
    name: 'KI-gestuetztes Recruiting',
    description: 'Automatisierte Vorauswahl von Bewerbungen',
    purpose: 'Effiziente Bewerberauswahl',
    legalBasis: 'Art. 6 Abs. 1 lit. b, Art. 22 Abs. 2 lit. a DSGVO',
    dataCategories: ['Bewerbungsunterlagen', 'Qualifikationen', 'Berufserfahrung'],
    dataSubjects: ['Bewerber'],
    recipients: ['HR-Abteilung', 'Fachabteilungen'],
    thirdCountryTransfers: false,
    retentionPeriod: '6 Monate nach Absage',
    toms: ['Menschliche Aufsicht', 'Erklaerbarkeit', 'Bias-Pruefung'],
    status: 'draft',
    lastUpdated: new Date('2024-01-22'),
    responsible: 'HR-Abteilung',
  },
  {
    id: 'vvt-5',
    name: 'Website-Analyse',
    description: 'Analyse des Nutzerverhaltens auf der Website',
    purpose: 'Verbesserung der Website und Nutzererfahrung',
    legalBasis: 'Art. 6 Abs. 1 lit. a DSGVO (Einwilligung via Cookie-Banner)',
    dataCategories: ['IP-Adresse', 'Seitenaufrufe', 'Verweildauer', 'Geraetedaten'],
    dataSubjects: ['Website-Besucher'],
    recipients: ['Marketing', 'Webentwicklung'],
    thirdCountryTransfers: true,
    retentionPeriod: '14 Monate',
    toms: ['IP-Anonymisierung', 'Cookie-Einwilligung', 'Opt-Out'],
    status: 'active',
    lastUpdated: new Date('2024-01-05'),
    responsible: 'Webmaster',
  },
]

// =============================================================================
// COMPONENTS
// =============================================================================

function ActivityCard({ activity }: { activity: ProcessingActivity }) {
  const statusColors = {
    active: 'bg-green-100 text-green-700',
    draft: 'bg-yellow-100 text-yellow-700',
    archived: 'bg-gray-100 text-gray-500',
  }

  const statusLabels = {
    active: 'Aktiv',
    draft: 'Entwurf',
    archived: 'Archiviert',
  }

  return (
    <div className={`bg-white rounded-xl border-2 p-6 ${
      activity.status === 'active' ? 'border-gray-200' :
      activity.status === 'draft' ? 'border-yellow-200' : 'border-gray-300'
    }`}>
      <div className="flex items-start justify-between">
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-2">
            <span className={`px-2 py-1 text-xs rounded-full ${statusColors[activity.status]}`}>
              {statusLabels[activity.status]}
            </span>
            {activity.thirdCountryTransfers && (
              <span className="px-2 py-1 text-xs bg-orange-100 text-orange-700 rounded-full">
                Drittlandtransfer
              </span>
            )}
          </div>
          <h3 className="text-lg font-semibold text-gray-900">{activity.name}</h3>
          <p className="text-sm text-gray-500 mt-1">{activity.description}</p>
        </div>
      </div>

      <div className="mt-4 space-y-2 text-sm">
        <div>
          <span className="text-gray-500">Zweck: </span>
          <span className="text-gray-700">{activity.purpose}</span>
        </div>
        <div>
          <span className="text-gray-500">Rechtsgrundlage: </span>
          <span className="text-gray-700">{activity.legalBasis}</span>
        </div>
        <div>
          <span className="text-gray-500">Aufbewahrung: </span>
          <span className="text-gray-700">{activity.retentionPeriod}</span>
        </div>
      </div>

      <div className="mt-3">
        <span className="text-sm text-gray-500">Datenkategorien:</span>
        <div className="flex flex-wrap gap-1 mt-1">
          {activity.dataCategories.map(cat => (
            <span key={cat} className="px-2 py-0.5 text-xs bg-blue-50 text-blue-600 rounded">
              {cat}
            </span>
          ))}
        </div>
      </div>

      <div className="mt-3">
        <span className="text-sm text-gray-500">Betroffene:</span>
        <div className="flex flex-wrap gap-1 mt-1">
          {activity.dataSubjects.map(subj => (
            <span key={subj} className="px-2 py-0.5 text-xs bg-purple-50 text-purple-600 rounded">
              {subj}
            </span>
          ))}
        </div>
      </div>

      <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between text-sm">
        <div className="text-gray-500">
          Verantwortlich: {activity.responsible} | Aktualisiert: {activity.lastUpdated.toLocaleDateString('de-DE')}
        </div>
        <div className="flex items-center gap-2">
          <button className="px-3 py-1 text-purple-600 hover:bg-purple-50 rounded-lg transition-colors">
            Bearbeiten
          </button>
          <button className="px-3 py-1 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
            Exportieren
          </button>
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// MAIN PAGE
// =============================================================================

export default function VVTPage() {
  const router = useRouter()
  const { state } = useSDK()
  const [activities] = useState<ProcessingActivity[]>(mockActivities)
  const [filter, setFilter] = useState<string>('all')
  const [searchQuery, setSearchQuery] = useState('')

  // Handle uploaded document
  const handleDocumentProcessed = useCallback((doc: UploadedDocument) => {
    console.log('[VVT Page] Document processed:', doc)
  }, [])

  // Open document in workflow editor
  const handleOpenInEditor = useCallback((doc: UploadedDocument) => {
    router.push(`/compliance/workflow?documentType=vvt&documentId=${doc.id}&mode=change`)
  }, [router])

  const filteredActivities = activities.filter(activity => {
    const matchesFilter = filter === 'all' || activity.status === filter
    const matchesSearch = searchQuery === '' ||
      activity.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      activity.purpose.toLowerCase().includes(searchQuery.toLowerCase())
    return matchesFilter && matchesSearch
  })

  const activeCount = activities.filter(a => a.status === 'active').length
  const thirdCountryCount = activities.filter(a => a.thirdCountryTransfers).length
  const totalDataCategories = [...new Set(activities.flatMap(a => a.dataCategories))].length

  const stepInfo = STEP_EXPLANATIONS['vvt']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="vvt"
        title={stepInfo.title}
        description={stepInfo.description}
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      >
        <div className="flex items-center gap-2">
          <button className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
            Exportieren
          </button>
          <button className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            Neue Verarbeitung
          </button>
        </div>
      </StepHeader>

      {/* Document Upload Section */}
      <DocumentUploadSection
        documentType="vvt"
        onDocumentProcessed={handleDocumentProcessed}
        onOpenInEditor={handleOpenInEditor}
      />

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <div className="text-sm text-gray-500">Verarbeitungen</div>
          <div className="text-3xl font-bold text-gray-900">{activities.length}</div>
        </div>
        <div className="bg-white rounded-xl border border-green-200 p-6">
          <div className="text-sm text-green-600">Aktiv</div>
          <div className="text-3xl font-bold text-green-600">{activeCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-orange-200 p-6">
          <div className="text-sm text-orange-600">Mit Drittlandtransfer</div>
          <div className="text-3xl font-bold text-orange-600">{thirdCountryCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-blue-200 p-6">
          <div className="text-sm text-blue-600">Datenkategorien</div>
          <div className="text-3xl font-bold text-blue-600">{totalDataCategories}</div>
        </div>
      </div>

      {/* Search and Filter */}
      <div className="flex items-center gap-4">
        <div className="flex-1 relative">
          <svg className="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Verarbeitungen durchsuchen..."
            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          />
        </div>
        <div className="flex items-center gap-2">
          {['all', 'active', 'draft', 'archived'].map(f => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-3 py-1 text-sm rounded-full transition-colors ${
                filter === f
                  ? 'bg-purple-600 text-white'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              {f === 'all' ? 'Alle' :
               f === 'active' ? 'Aktiv' :
               f === 'draft' ? 'Entwurf' : 'Archiviert'}
            </button>
          ))}
        </div>
      </div>

      {/* Activities List */}
      <div className="space-y-4">
        {filteredActivities.map(activity => (
          <ActivityCard key={activity.id} activity={activity} />
        ))}
      </div>

      {filteredActivities.length === 0 && (
        <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
          <div className="w-16 h-16 mx-auto bg-gray-100 rounded-full flex items-center justify-center mb-4">
            <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">Keine Verarbeitungen gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie die Suche oder den Filter an.</p>
        </div>
      )}
    </div>
  )
}
