'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 RetentionPolicy {
  id: string
  dataCategory: string
  description: string
  retentionPeriod: string
  legalBasis: string
  startEvent: string
  deletionMethod: string
  status: 'active' | 'review-needed' | 'expired'
  lastReview: Date
  nextReview: Date
  recordCount: number | null
}

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

const mockPolicies: RetentionPolicy[] = [
  {
    id: 'ret-1',
    dataCategory: 'Personalakten',
    description: 'Beschaeftigtendaten und Gehaltsabrechnungen',
    retentionPeriod: '10 Jahre',
    legalBasis: 'Steuerrecht, Sozialversicherungsrecht',
    startEvent: 'Ende des Beschaeftigungsverhaeltnisses',
    deletionMethod: 'Automatische Loeschung nach Ablauf',
    status: 'active',
    lastReview: new Date('2024-01-01'),
    nextReview: new Date('2025-01-01'),
    recordCount: 245,
  },
  {
    id: 'ret-2',
    dataCategory: 'Buchhaltungsbelege',
    description: 'Rechnungen, Kontoauszuege, Buchungsbelege',
    retentionPeriod: '10 Jahre',
    legalBasis: 'HGB, AO',
    startEvent: 'Ende des Kalenderjahres',
    deletionMethod: 'Manuelle Pruefung und Vernichtung',
    status: 'active',
    lastReview: new Date('2024-01-15'),
    nextReview: new Date('2025-01-15'),
    recordCount: 12450,
  },
  {
    id: 'ret-3',
    dataCategory: 'Bewerbungsunterlagen',
    description: 'Lebenslaeufe, Anschreiben, Zeugnisse',
    retentionPeriod: '6 Monate',
    legalBasis: 'Berechtigtes Interesse (AGG-Frist)',
    startEvent: 'Absage oder Stellenbesetzung',
    deletionMethod: 'Automatische Loeschung',
    status: 'active',
    lastReview: new Date('2024-01-10'),
    nextReview: new Date('2024-07-10'),
    recordCount: 89,
  },
  {
    id: 'ret-4',
    dataCategory: 'Marketing-Einwilligungen',
    description: 'Newsletter-Abonnements und Werbeeinwilligungen',
    retentionPeriod: 'Bis Widerruf',
    legalBasis: 'Einwilligung Art. 6 Abs. 1 lit. a DSGVO',
    startEvent: 'Widerruf der Einwilligung',
    deletionMethod: 'Sofortige Loeschung bei Widerruf',
    status: 'active',
    lastReview: new Date('2023-12-01'),
    nextReview: new Date('2024-06-01'),
    recordCount: 5623,
  },
  {
    id: 'ret-5',
    dataCategory: 'Webserver-Logs',
    description: 'IP-Adressen, Zugriffszeiten, User-Agents',
    retentionPeriod: '7 Tage',
    legalBasis: 'Berechtigtes Interesse (IT-Sicherheit)',
    startEvent: 'Zeitpunkt des Zugriffs',
    deletionMethod: 'Automatische Rotation',
    status: 'active',
    lastReview: new Date('2024-01-20'),
    nextReview: new Date('2024-04-20'),
    recordCount: null,
  },
  {
    id: 'ret-6',
    dataCategory: 'Kundenstammdaten',
    description: 'Name, Adresse, Kontaktdaten von Kunden',
    retentionPeriod: '3 Jahre nach letzter Interaktion',
    legalBasis: 'Vertragserfuellung, Berechtigtes Interesse',
    startEvent: 'Letzte Kundeninteraktion',
    deletionMethod: 'Pruefung und manuelle Loeschung',
    status: 'review-needed',
    lastReview: new Date('2023-06-01'),
    nextReview: new Date('2024-01-01'),
    recordCount: 8920,
  },
]

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

function PolicyCard({ policy }: { policy: RetentionPolicy }) {
  const statusColors = {
    active: 'bg-green-100 text-green-700 border-green-200',
    'review-needed': 'bg-yellow-100 text-yellow-700 border-yellow-200',
    expired: 'bg-red-100 text-red-700 border-red-200',
  }

  const statusLabels = {
    active: 'Aktiv',
    'review-needed': 'Pruefung erforderlich',
    expired: 'Abgelaufen',
  }

  const isReviewDue = policy.nextReview <= new Date()

  return (
    <div className={`bg-white rounded-xl border-2 p-6 ${
      policy.status === 'review-needed' || isReviewDue ? 'border-yellow-200' : 'border-gray-200'
    }`}>
      <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[policy.status]}`}>
              {statusLabels[policy.status]}
            </span>
            <span className="px-2 py-1 text-xs bg-purple-100 text-purple-700 rounded-full">
              {policy.retentionPeriod}
            </span>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">{policy.dataCategory}</h3>
          <p className="text-sm text-gray-500 mt-1">{policy.description}</p>
        </div>
      </div>

      <div className="mt-4 grid grid-cols-2 gap-4 text-sm">
        <div>
          <span className="text-gray-500">Rechtsgrundlage: </span>
          <span className="text-gray-700">{policy.legalBasis}</span>
        </div>
        <div>
          <span className="text-gray-500">Startereignis: </span>
          <span className="text-gray-700">{policy.startEvent}</span>
        </div>
        <div>
          <span className="text-gray-500">Loeschmethode: </span>
          <span className="text-gray-700">{policy.deletionMethod}</span>
        </div>
        <div>
          <span className="text-gray-500">Datensaetze: </span>
          <span className="text-gray-700">{policy.recordCount ? policy.recordCount.toLocaleString('de-DE') : 'N/A'}</span>
        </div>
      </div>

      <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between text-sm">
        <div className={isReviewDue ? 'text-yellow-600' : 'text-gray-500'}>
          Naechste Pruefung: {policy.nextReview.toLocaleDateString('de-DE')}
          {isReviewDue && ' (faellig)'}
        </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">
            Loeschvorgang starten
          </button>
        </div>
      </div>
    </div>
  )
}

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

export default function LoeschfristenPage() {
  const router = useRouter()
  const { state } = useSDK()
  const [policies] = useState<RetentionPolicy[]>(mockPolicies)
  const [filter, setFilter] = useState<string>('all')

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

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

  const filteredPolicies = filter === 'all'
    ? policies
    : policies.filter(p => p.status === filter)

  const activeCount = policies.filter(p => p.status === 'active').length
  const reviewNeededCount = policies.filter(p => p.status === 'review-needed' || p.nextReview <= new Date()).length
  const totalRecords = policies.reduce((sum, p) => sum + (p.recordCount || 0), 0)

  const stepInfo = STEP_EXPLANATIONS['loeschfristen']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="loeschfristen"
        title={stepInfo.title}
        description={stepInfo.description}
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      >
        <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>
          Loeschfrist hinzufuegen
        </button>
      </StepHeader>

      {/* Document Upload Section */}
      <DocumentUploadSection
        documentType="loeschfristen"
        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">Datenkategorien</div>
          <div className="text-3xl font-bold text-gray-900">{policies.length}</div>
        </div>
        <div className="bg-white rounded-xl border border-green-200 p-6">
          <div className="text-sm text-green-600">Aktive Regeln</div>
          <div className="text-3xl font-bold text-green-600">{activeCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-yellow-200 p-6">
          <div className="text-sm text-yellow-600">Pruefung erforderlich</div>
          <div className="text-3xl font-bold text-yellow-600">{reviewNeededCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-blue-200 p-6">
          <div className="text-sm text-blue-600">Betroffene Datensaetze</div>
          <div className="text-3xl font-bold text-blue-600">{totalRecords.toLocaleString('de-DE')}</div>
        </div>
      </div>

      {/* Info Box */}
      <div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
        <div className="flex items-start gap-3">
          <svg className="w-5 h-5 text-blue-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <div>
            <h4 className="font-medium text-blue-800">Hinweis zur Datenspeicherung</h4>
            <p className="text-sm text-blue-600 mt-1">
              Nach Art. 5 Abs. 1 lit. e DSGVO duerfen personenbezogene Daten nur so lange gespeichert werden,
              wie es fuer die Zwecke, fuer die sie verarbeitet werden, erforderlich ist (Speicherbegrenzung).
            </p>
          </div>
        </div>
      </div>

      {/* Filter */}
      <div className="flex items-center gap-2">
        <span className="text-sm text-gray-500">Filter:</span>
        {['all', 'active', 'review-needed'].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' : 'Pruefung erforderlich'}
          </button>
        ))}
      </div>

      {/* Policies List */}
      <div className="space-y-4">
        {filteredPolicies.map(policy => (
          <PolicyCard key={policy.id} policy={policy} />
        ))}
      </div>

      {filteredPolicies.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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">Keine Loeschfristen gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie den Filter an oder fuegen Sie neue Loeschfristen hinzu.</p>
        </div>
      )}
    </div>
  )
}
