'use client'

import React, { useState, useEffect } from 'react'
import { useSDK } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'

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

interface LegalDocument {
  id: string
  type: 'privacy-policy' | 'terms' | 'cookie-policy' | 'imprint' | 'dpa'
  name: string
  version: string
  language: string
  status: 'draft' | 'active' | 'archived'
  lastUpdated: Date
  publishedAt: Date | null
  author: string
  changes: string[]
}

interface ApiDocument {
  id: string
  type: string
  name: string
  description: string
  mandatory: boolean
  created_at: string
  updated_at: string
}

// Map API document type to UI type
function mapDocumentType(apiType: string): LegalDocument['type'] {
  const mapping: Record<string, LegalDocument['type']> = {
    'privacy_policy': 'privacy-policy',
    'privacy-policy': 'privacy-policy',
    'terms': 'terms',
    'terms_of_service': 'terms',
    'cookie_policy': 'cookie-policy',
    'cookie-policy': 'cookie-policy',
    'imprint': 'imprint',
    'dpa': 'dpa',
    'avv': 'dpa',
  }
  return mapping[apiType] || 'terms'
}

// Transform API response to UI format
function transformApiDocument(doc: ApiDocument): LegalDocument {
  return {
    id: doc.id,
    type: mapDocumentType(doc.type),
    name: doc.name,
    version: '1.0',
    language: 'de',
    status: 'active',
    lastUpdated: new Date(doc.updated_at),
    publishedAt: new Date(doc.created_at),
    author: 'System',
    changes: doc.description ? [doc.description] : [],
  }
}

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

function DocumentCard({ document }: { document: LegalDocument }) {
  const typeColors = {
    'privacy-policy': 'bg-blue-100 text-blue-700',
    terms: 'bg-green-100 text-green-700',
    'cookie-policy': 'bg-yellow-100 text-yellow-700',
    imprint: 'bg-gray-100 text-gray-700',
    dpa: 'bg-purple-100 text-purple-700',
  }

  const typeLabels = {
    'privacy-policy': 'Datenschutz',
    terms: 'AGB',
    'cookie-policy': 'Cookie-Richtlinie',
    imprint: 'Impressum',
    dpa: 'AVV',
  }

  const statusColors = {
    draft: 'bg-yellow-100 text-yellow-700',
    active: 'bg-green-100 text-green-700',
    archived: 'bg-gray-100 text-gray-500',
  }

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

  return (
    <div className={`bg-white rounded-xl border-2 p-6 ${
      document.status === 'draft' ? '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 ${typeColors[document.type]}`}>
              {typeLabels[document.type]}
            </span>
            <span className={`px-2 py-1 text-xs rounded-full ${statusColors[document.status]}`}>
              {statusLabels[document.status]}
            </span>
            <span className="px-2 py-1 text-xs bg-gray-100 text-gray-600 rounded uppercase">
              {document.language}
            </span>
            <span className="px-2 py-1 text-xs bg-gray-100 text-gray-600 rounded">
              v{document.version}
            </span>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">{document.name}</h3>
        </div>
      </div>

      {document.changes.length > 0 && (
        <div className="mt-3">
          <span className="text-sm text-gray-500">Letzte Aenderungen:</span>
          <ul className="mt-1 text-sm text-gray-600 list-disc list-inside">
            {document.changes.slice(0, 2).map((change, i) => (
              <li key={i}>{change}</li>
            ))}
          </ul>
        </div>
      )}

      <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between text-sm">
        <div className="text-gray-500">
          <span>Autor: {document.author}</span>
          <span className="mx-2">|</span>
          <span>Aktualisiert: {document.lastUpdated.toLocaleDateString('de-DE')}</span>
        </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">
            Vorschau
          </button>
          {document.status === 'draft' && (
            <button className="px-3 py-1 bg-green-50 text-green-700 hover:bg-green-100 rounded-lg transition-colors">
              Veroeffentlichen
            </button>
          )}
        </div>
      </div>
    </div>
  )
}

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

export default function ConsentPage() {
  const { state } = useSDK()
  const [documents, setDocuments] = useState<LegalDocument[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [filter, setFilter] = useState<string>('all')

  useEffect(() => {
    loadDocuments()
  }, [])

  async function loadDocuments() {
    setLoading(true)
    setError(null)
    try {
      const token = localStorage.getItem('bp_admin_token')
      const res = await fetch('/api/admin/consent/documents', {
        headers: token ? { 'Authorization': `Bearer ${token}` } : {}
      })
      if (res.ok) {
        const data = await res.json()
        const apiDocs: ApiDocument[] = data.documents || []
        setDocuments(apiDocs.map(transformApiDocument))
      } else {
        setError('Fehler beim Laden der Dokumente')
      }
    } catch {
      setError('Verbindungsfehler zum Server')
    } finally {
      setLoading(false)
    }
  }

  const filteredDocuments = filter === 'all'
    ? documents
    : documents.filter(d => d.type === filter || d.status === filter)

  const activeCount = documents.filter(d => d.status === 'active').length
  const draftCount = documents.filter(d => d.status === 'draft').length

  const stepInfo = STEP_EXPLANATIONS['consent']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="consent"
        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>
          Neues Dokument
        </button>
      </StepHeader>

      {/* 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">Gesamt</div>
          <div className="text-3xl font-bold text-gray-900">{documents.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-yellow-200 p-6">
          <div className="text-sm text-yellow-600">Entwuerfe</div>
          <div className="text-3xl font-bold text-yellow-600">{draftCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-blue-200 p-6">
          <div className="text-sm text-blue-600">Sprachen</div>
          <div className="text-3xl font-bold text-blue-600">
            {[...new Set(documents.map(d => d.language))].length}
          </div>
        </div>
      </div>

      {/* Loading / Error */}
      {loading && (
        <div className="text-center py-8 text-gray-500">Lade Dokumente...</div>
      )}
      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
          {error}
        </div>
      )}

      {/* Quick Actions */}
      <div className="bg-gradient-to-r from-purple-50 to-blue-50 rounded-xl border border-purple-200 p-6">
        <h3 className="font-semibold text-gray-900 mb-4">Schnellaktionen</h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <button className="p-4 bg-white rounded-lg border border-gray-200 hover:border-purple-300 hover:shadow transition-all text-center">
            <svg className="w-8 h-8 mx-auto text-blue-600 mb-2" 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>
            <span className="text-sm font-medium">Datenschutz generieren</span>
          </button>
          <button className="p-4 bg-white rounded-lg border border-gray-200 hover:border-purple-300 hover:shadow transition-all text-center">
            <svg className="w-8 h-8 mx-auto text-green-600 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
            </svg>
            <span className="text-sm font-medium">AGB generieren</span>
          </button>
          <button className="p-4 bg-white rounded-lg border border-gray-200 hover:border-purple-300 hover:shadow transition-all text-center">
            <svg className="w-8 h-8 mx-auto text-yellow-600 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4" />
            </svg>
            <span className="text-sm font-medium">Cookie-Richtlinie</span>
          </button>
          <button className="p-4 bg-white rounded-lg border border-gray-200 hover:border-purple-300 hover:shadow transition-all text-center">
            <svg className="w-8 h-8 mx-auto text-purple-600 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
            </svg>
            <span className="text-sm font-medium">AVV-Vorlage</span>
          </button>
        </div>
      </div>

      {/* Filter */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-sm text-gray-500">Filter:</span>
        {['all', 'privacy-policy', 'terms', 'cookie-policy', 'dpa', 'active', 'draft'].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 === 'privacy-policy' ? 'Datenschutz' :
             f === 'terms' ? 'AGB' :
             f === 'cookie-policy' ? 'Cookie' :
             f === 'dpa' ? 'AVV' :
             f === 'active' ? 'Aktiv' : 'Entwuerfe'}
          </button>
        ))}
      </div>

      {/* Documents List */}
      <div className="space-y-4">
        {filteredDocuments.map(document => (
          <DocumentCard key={document.id} document={document} />
        ))}
      </div>

      {filteredDocuments.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 Dokumente gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie den Filter an oder erstellen Sie ein neues Dokument.</p>
        </div>
      )}
    </div>
  )
}
