'use client'

/**
 * Datenpunktkatalog Seite
 *
 * Zeigt den vollstaendigen Katalog aller personenbezogenen Daten,
 * die vom Unternehmen verarbeitet werden.
 */

import { useState, useEffect } from 'react'
import { useSDK } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
import { DataPointCatalog } from '@/components/sdk/einwilligungen'
import {
  EinwilligungenProvider,
  useEinwilligungen,
} from '@/lib/sdk/einwilligungen/context'
import {
  PREDEFINED_DATA_POINTS,
  RETENTION_MATRIX,
} from '@/lib/sdk/einwilligungen/catalog/loader'
import {
  DataPoint,
  SupportedLanguage,
  CATEGORY_METADATA,
  RISK_LEVEL_STYLING,
  LEGAL_BASIS_INFO,
} from '@/lib/sdk/einwilligungen/types'
import {
  Plus,
  Download,
  Upload,
  Filter,
  BarChart3,
  Shield,
  FileText,
  Cookie,
  Clock,
  ChevronRight,
} from 'lucide-react'
import Link from 'next/link'

// =============================================================================
// CATALOG CONTENT COMPONENT
// =============================================================================

function CatalogContent() {
  const { state } = useSDK()
  const {
    allDataPoints,
    selectedDataPointsData,
    categoryStats,
    riskStats,
    legalBasisStats,
    toggleDataPoint,
    setActiveTab,
    state: einwilligungenState,
  } = useEinwilligungen()

  const [language, setLanguage] = useState<SupportedLanguage>('de')
  const [selectedIds, setSelectedIds] = useState<string[]>(
    allDataPoints.map((dp) => dp.id)
  )

  // Stats
  const totalDataPoints = allDataPoints.length
  const customDataPoints = allDataPoints.filter((dp) => dp.isCustom).length
  const highRiskCount = riskStats.HIGH || 0
  const consentRequiredCount = allDataPoints.filter((dp) => dp.requiresExplicitConsent).length

  const handleToggle = (id: string) => {
    setSelectedIds((prev) =>
      prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id]
    )
  }

  const handleSelectAll = () => {
    setSelectedIds(allDataPoints.map((dp) => dp.id))
  }

  const handleDeselectAll = () => {
    setSelectedIds([])
  }

  const stepInfo = STEP_EXPLANATIONS['einwilligungen'] || {
    title: 'Datenpunktkatalog',
    description: 'Verwalten Sie alle personenbezogenen Daten, die Ihr Unternehmen verarbeitet.',
    explanation: 'Der Datenpunktkatalog ist die Grundlage fuer Ihre Datenschutzerklaerung, den Cookie-Banner und die Loeschfristen.',
    tips: [],
  }

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="einwilligungen"
        title="Datenpunktkatalog"
        description="Verwalten Sie alle personenbezogenen Daten, die Ihr Unternehmen verarbeitet."
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      >
        <div className="flex items-center gap-2">
          <button className="flex items-center gap-2 px-4 py-2 border border-slate-300 rounded-lg text-sm font-medium text-slate-700 hover:bg-slate-50">
            <Upload className="w-4 h-4" />
            Importieren
          </button>
          <button className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg text-sm font-medium hover:bg-indigo-700">
            <Download className="w-4 h-4" />
            Exportieren
          </button>
        </div>
      </StepHeader>

      {/* Navigation Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Link
          href="/sdk/einwilligungen/privacy-policy"
          className="bg-white rounded-xl border border-slate-200 p-4 hover:border-indigo-300 hover:shadow-md transition-all group"
        >
          <div className="flex items-center justify-between">
            <div className="p-2 rounded-lg bg-indigo-100">
              <FileText className="w-5 h-5 text-indigo-600" />
            </div>
            <ChevronRight className="w-5 h-5 text-slate-400 group-hover:text-indigo-600 transition-colors" />
          </div>
          <div className="mt-3">
            <div className="font-semibold text-slate-900">Datenschutzerklaerung</div>
            <div className="text-sm text-slate-500">DSI aus Katalog generieren</div>
          </div>
        </Link>

        <Link
          href="/sdk/cookie-banner"
          className="bg-white rounded-xl border border-slate-200 p-4 hover:border-indigo-300 hover:shadow-md transition-all group"
        >
          <div className="flex items-center justify-between">
            <div className="p-2 rounded-lg bg-amber-100">
              <Cookie className="w-5 h-5 text-amber-600" />
            </div>
            <ChevronRight className="w-5 h-5 text-slate-400 group-hover:text-indigo-600 transition-colors" />
          </div>
          <div className="mt-3">
            <div className="font-semibold text-slate-900">Cookie-Banner</div>
            <div className="text-sm text-slate-500">Banner konfigurieren</div>
          </div>
        </Link>

        <Link
          href="/sdk/einwilligungen/retention"
          className="bg-white rounded-xl border border-slate-200 p-4 hover:border-indigo-300 hover:shadow-md transition-all group"
        >
          <div className="flex items-center justify-between">
            <div className="p-2 rounded-lg bg-purple-100">
              <Clock className="w-5 h-5 text-purple-600" />
            </div>
            <ChevronRight className="w-5 h-5 text-slate-400 group-hover:text-indigo-600 transition-colors" />
          </div>
          <div className="mt-3">
            <div className="font-semibold text-slate-900">Loeschfristen</div>
            <div className="text-sm text-slate-500">Retention Matrix anzeigen</div>
          </div>
        </Link>

        <Link
          href="/sdk/einwilligungen"
          className="bg-white rounded-xl border border-slate-200 p-4 hover:border-indigo-300 hover:shadow-md transition-all group"
        >
          <div className="flex items-center justify-between">
            <div className="p-2 rounded-lg bg-green-100">
              <Shield className="w-5 h-5 text-green-600" />
            </div>
            <ChevronRight className="w-5 h-5 text-slate-400 group-hover:text-indigo-600 transition-colors" />
          </div>
          <div className="mt-3">
            <div className="font-semibold text-slate-900">Consent-Tracking</div>
            <div className="text-sm text-slate-500">Einwilligungen verwalten</div>
          </div>
        </Link>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <div className="bg-white rounded-xl border border-slate-200 p-4">
          <div className="text-sm text-slate-500">Datenpunkte gesamt</div>
          <div className="text-2xl font-bold text-slate-900">{totalDataPoints}</div>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 p-4">
          <div className="text-sm text-slate-500">Ausgewaehlt</div>
          <div className="text-2xl font-bold text-indigo-600">{selectedIds.length}</div>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 p-4">
          <div className="text-sm text-slate-500">Benutzerdefiniert</div>
          <div className="text-2xl font-bold text-purple-600">{customDataPoints}</div>
        </div>
        <div className="bg-white rounded-xl border border-red-200 p-4">
          <div className="text-sm text-red-600">Hohes Risiko</div>
          <div className="text-2xl font-bold text-red-600">{highRiskCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-amber-200 p-4">
          <div className="text-sm text-amber-600">Einwilligung erforderlich</div>
          <div className="text-2xl font-bold text-amber-600">{consentRequiredCount}</div>
        </div>
      </div>

      {/* Add Custom Data Point Button */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <select
            value={language}
            onChange={(e) => setLanguage(e.target.value as SupportedLanguage)}
            className="px-3 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
          >
            <option value="de">Deutsch</option>
            <option value="en">English</option>
          </select>
        </div>
        <button className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg text-sm font-medium hover:bg-indigo-700">
          <Plus className="w-4 h-4" />
          Datenpunkt hinzufuegen
        </button>
      </div>

      {/* Catalog */}
      <DataPointCatalog
        dataPoints={allDataPoints}
        selectedIds={selectedIds}
        onToggle={handleToggle}
        onSelectAll={handleSelectAll}
        onDeselectAll={handleDeselectAll}
        language={language}
        showFilters={true}
        readOnly={false}
      />
    </div>
  )
}

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

export default function CatalogPage() {
  return (
    <EinwilligungenProvider>
      <CatalogContent />
    </EinwilligungenProvider>
  )
}
