'use client'

import { useState, useEffect } from 'react'

interface IABPurpose {
  id: number
  name: string
  name_de: string
}

const API = '/api/sdk/v1/compliance/tcf'

export function TCFSettings({ siteId, tcfEnabled, onToggle }: {
  siteId?: string
  tcfEnabled: boolean
  onToggle: (enabled: boolean) => void
}) {
  const [purposes, setPurposes] = useState<IABPurpose[]>([])
  const [categoryMap, setCategoryMap] = useState<Record<string, number[]>>({})
  const [testResult, setTestResult] = useState<string | null>(null)
  const [testing, setTesting] = useState(false)

  useEffect(() => {
    Promise.all([
      fetch(`${API}/purposes`).then(r => r.ok ? r.json() : []),
      fetch(`${API}/category-mapping`).then(r => r.ok ? r.json() : {}),
    ]).then(([p, m]) => {
      setPurposes(p)
      setCategoryMap(m)
    }).catch(() => {})
  }, [])

  const handleTestEncode = async () => {
    setTesting(true)
    setTestResult(null)
    try {
      const res = await fetch(`${API}/encode-categories`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ categories: ['necessary', 'statistics', 'marketing'] }),
      })
      if (res.ok) {
        const data = await res.json()
        setTestResult(`TC String: ${data.tc_string}\nPurposes: ${data.purposes_consented.join(', ')}`)
      }
    } catch { setTestResult('Fehler beim Generieren') }
    setTesting(false)
  }

  return (
    <div className="space-y-6">
      {/* Enable/Disable */}
      <div className="bg-white rounded-xl border border-gray-200 p-6">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="font-semibold text-gray-900">IAB TCF 2.2</h3>
            <p className="text-xs text-gray-500 mt-1">
              Transparency & Consent Framework — Standardisierte Einwilligungssignale fuer programmatische Werbung
            </p>
          </div>
          <label className="flex items-center gap-2">
            <input type="checkbox" checked={tcfEnabled} onChange={e => onToggle(e.target.checked)}
              className="w-5 h-5 text-purple-600 rounded" />
            <span className="text-sm font-medium">{tcfEnabled ? 'Aktiv' : 'Inaktiv'}</span>
          </label>
        </div>
        {!tcfEnabled && (
          <p className="mt-3 text-xs text-amber-600 bg-amber-50 p-3 rounded-lg">
            TCF ist nur erforderlich wenn Sie programmatische Werbung (AdTech) einsetzen.
            Fuer die meisten Websites reicht das Standard-Cookie-Banner.
          </p>
        )}
      </div>

      {tcfEnabled && (
        <>
          {/* IAB Purposes */}
          <div className="bg-white rounded-xl border border-gray-200 p-6">
            <h4 className="font-semibold text-gray-900 mb-3">12 IAB-Zwecke (Purposes)</h4>
            <p className="text-xs text-gray-500 mb-4">
              Diese Zwecke werden automatisch aus Ihren Cookie-Kategorien abgeleitet.
            </p>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
              {purposes.map(p => {
                const activeCats = Object.entries(categoryMap)
                  .filter(([, pids]) => pids.includes(p.id))
                  .map(([cat]) => cat)
                return (
                  <div key={p.id} className={`flex items-start gap-2 p-2 rounded-lg text-xs ${activeCats.length > 0 ? 'bg-green-50' : 'bg-gray-50'}`}>
                    <span className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold flex-shrink-0 ${activeCats.length > 0 ? 'bg-green-500 text-white' : 'bg-gray-300 text-white'}`}>
                      {p.id}
                    </span>
                    <div>
                      <div className="font-medium text-gray-700">{p.name_de}</div>
                      {activeCats.length > 0 && (
                        <div className="text-gray-400 mt-0.5">via: {activeCats.join(', ')}</div>
                      )}
                    </div>
                  </div>
                )
              })}
            </div>
          </div>

          {/* Category Mapping */}
          <div className="bg-white rounded-xl border border-gray-200 p-6">
            <h4 className="font-semibold text-gray-900 mb-3">Kategorie → Purpose Zuordnung</h4>
            <div className="space-y-2">
              {Object.entries(categoryMap).map(([cat, pids]) => (
                <div key={cat} className="flex items-center gap-3">
                  <span className="text-sm font-medium text-gray-700 w-24 capitalize">{cat}</span>
                  <div className="flex gap-1 flex-wrap">
                    {pids.length === 0 ? (
                      <span className="text-xs text-gray-400">Keine Einwilligung noetig</span>
                    ) : (
                      pids.map(pid => (
                        <span key={pid} className="px-2 py-0.5 text-[10px] bg-purple-100 text-purple-700 rounded-full">
                          Purpose {pid}
                        </span>
                      ))
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* TC String Test */}
          <div className="bg-white rounded-xl border border-gray-200 p-6">
            <h4 className="font-semibold text-gray-900 mb-3">TC String testen</h4>
            <button onClick={handleTestEncode} disabled={testing}
              className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
              {testing ? 'Generiere...' : 'Test TC String generieren'}
            </button>
            {testResult && (
              <pre className="mt-3 p-3 bg-gray-50 border border-gray-200 rounded-lg text-xs text-gray-700 overflow-x-auto whitespace-pre-wrap">
                {testResult}
              </pre>
            )}
            <p className="text-xs text-gray-400 mt-2">
              Simuliert: necessary + statistics + marketing → generiert base64url-codierten TC String
            </p>
          </div>

          {/* CMP Registration Info */}
          <div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
            <h4 className="font-semibold text-blue-800 text-sm">CMP-Registrierung</h4>
            <p className="text-xs text-blue-700 mt-1">
              Fuer den produktiven Einsatz muss Ihr CMP bei der IAB Europe registriert werden.
              Sie erhalten eine eindeutige CMP-ID die im TC String codiert wird.
            </p>
            <p className="text-xs text-blue-600 mt-2">
              Registrierung: <a href="https://iabeurope.eu/tcf-for-cmps/" target="_blank" rel="noopener"
                className="underline">iabeurope.eu/tcf-for-cmps</a>
            </p>
          </div>
        </>
      )}
    </div>
  )
}
