'use client'

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

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

interface CookieCategory {
  id: string
  name: string
  description: string
  required: boolean
  enabled: boolean
  cookies: Cookie[]
}

interface Cookie {
  name: string
  provider: string
  purpose: string
  expiry: string
  type: 'first-party' | 'third-party'
}

interface BannerConfig {
  position: 'bottom' | 'top' | 'center'
  style: 'bar' | 'popup' | 'modal'
  primaryColor: string
  showDeclineAll: boolean
  showSettings: boolean
  blockScripts: boolean
}

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

const mockCategories: CookieCategory[] = [
  {
    id: 'necessary',
    name: 'Notwendig',
    description: 'Diese Cookies sind fuer die Grundfunktionen der Website erforderlich.',
    required: true,
    enabled: true,
    cookies: [
      { name: 'session_id', provider: 'Eigene', purpose: 'Session-Verwaltung', expiry: 'Session', type: 'first-party' },
      { name: 'csrf_token', provider: 'Eigene', purpose: 'Sicherheit', expiry: 'Session', type: 'first-party' },
    ],
  },
  {
    id: 'analytics',
    name: 'Analyse',
    description: 'Diese Cookies helfen uns, die Nutzung der Website zu verstehen.',
    required: false,
    enabled: true,
    cookies: [
      { name: '_ga', provider: 'Google Analytics', purpose: 'Nutzeranalyse', expiry: '2 Jahre', type: 'third-party' },
      { name: '_gid', provider: 'Google Analytics', purpose: 'Nutzeranalyse', expiry: '24 Stunden', type: 'third-party' },
    ],
  },
  {
    id: 'marketing',
    name: 'Marketing',
    description: 'Diese Cookies werden fuer personalisierte Werbung verwendet.',
    required: false,
    enabled: false,
    cookies: [
      { name: '_fbp', provider: 'Meta (Facebook)', purpose: 'Werbung', expiry: '3 Monate', type: 'third-party' },
      { name: 'IDE', provider: 'Google Ads', purpose: 'Werbung', expiry: '1 Jahr', type: 'third-party' },
    ],
  },
  {
    id: 'preferences',
    name: 'Praeferenzen',
    description: 'Diese Cookies speichern Ihre Einstellungen und Praeferenzen.',
    required: false,
    enabled: true,
    cookies: [
      { name: 'language', provider: 'Eigene', purpose: 'Spracheinstellung', expiry: '1 Jahr', type: 'first-party' },
      { name: 'theme', provider: 'Eigene', purpose: 'Design-Einstellung', expiry: '1 Jahr', type: 'first-party' },
    ],
  },
]

const defaultConfig: BannerConfig = {
  position: 'bottom',
  style: 'bar',
  primaryColor: '#6366f1',
  showDeclineAll: true,
  showSettings: true,
  blockScripts: true,
}

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

function BannerPreview({ config, categories }: { config: BannerConfig; categories: CookieCategory[] }) {
  return (
    <div className="relative bg-gray-100 rounded-xl p-8 min-h-64 flex items-end justify-center">
      <div className="absolute inset-0 flex items-center justify-center text-gray-400 text-sm">
        Website-Vorschau
      </div>
      <div
        className={`w-full max-w-2xl bg-white rounded-xl shadow-xl p-6 border-2 ${
          config.position === 'center' ? 'absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2' : ''
        }`}
        style={{ borderColor: config.primaryColor }}
      >
        <h4 className="font-semibold text-gray-900">Wir verwenden Cookies</h4>
        <p className="text-sm text-gray-600 mt-2">
          Wir nutzen Cookies, um Ihnen die bestmoegliche Nutzung unserer Website zu ermoeglichen.
        </p>
        <div className="mt-4 flex items-center gap-3">
          <button
            className="px-4 py-2 rounded-lg text-white text-sm font-medium"
            style={{ backgroundColor: config.primaryColor }}
          >
            Alle akzeptieren
          </button>
          {config.showDeclineAll && (
            <button className="px-4 py-2 rounded-lg border border-gray-300 text-gray-700 text-sm font-medium">
              Alle ablehnen
            </button>
          )}
          {config.showSettings && (
            <button className="px-4 py-2 text-sm text-gray-600 hover:underline">
              Einstellungen
            </button>
          )}
        </div>
      </div>
    </div>
  )
}

function CategoryCard({
  category,
  onToggle,
}: {
  category: CookieCategory
  onToggle: (enabled: boolean) => void
}) {
  const [expanded, setExpanded] = useState(false)

  return (
    <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
      <div className="p-4 flex items-center justify-between">
        <div className="flex-1">
          <div className="flex items-center gap-2">
            <h4 className="font-semibold text-gray-900">{category.name}</h4>
            {category.required && (
              <span className="px-2 py-0.5 text-xs bg-gray-100 text-gray-500 rounded">Erforderlich</span>
            )}
            <span className="px-2 py-0.5 text-xs bg-blue-50 text-blue-600 rounded">
              {category.cookies.length} Cookies
            </span>
          </div>
          <p className="text-sm text-gray-500 mt-1">{category.description}</p>
        </div>
        <div className="flex items-center gap-4">
          <button
            onClick={() => setExpanded(!expanded)}
            className="text-sm text-purple-600 hover:underline"
          >
            {expanded ? 'Ausblenden' : 'Details'}
          </button>
          <label className="relative inline-flex items-center cursor-pointer">
            <input
              type="checkbox"
              checked={category.enabled}
              onChange={(e) => onToggle(e.target.checked)}
              disabled={category.required}
              className="sr-only peer"
            />
            <div className={`w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-purple-100 rounded-full peer ${
              category.enabled ? 'peer-checked:bg-purple-600' : ''
            } peer-disabled:opacity-50 after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all ${
              category.enabled ? 'after:translate-x-full' : ''
            }`} />
          </label>
        </div>
      </div>

      {expanded && (
        <div className="border-t border-gray-100 p-4 bg-gray-50">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-gray-500">
                <th className="pb-2">Cookie</th>
                <th className="pb-2">Anbieter</th>
                <th className="pb-2">Zweck</th>
                <th className="pb-2">Ablauf</th>
              </tr>
            </thead>
            <tbody className="text-gray-700">
              {category.cookies.map(cookie => (
                <tr key={cookie.name}>
                  <td className="py-1 font-mono text-xs">{cookie.name}</td>
                  <td className="py-1">{cookie.provider}</td>
                  <td className="py-1">{cookie.purpose}</td>
                  <td className="py-1">{cookie.expiry}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}

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

export default function CookieBannerPage() {
  const { state } = useSDK()
  const [categories, setCategories] = useState<CookieCategory[]>(mockCategories)
  const [config, setConfig] = useState<BannerConfig>(defaultConfig)

  const handleCategoryToggle = (categoryId: string, enabled: boolean) => {
    setCategories(prev =>
      prev.map(cat => cat.id === categoryId ? { ...cat, enabled } : cat)
    )
  }

  const totalCookies = categories.reduce((sum, cat) => sum + cat.cookies.length, 0)
  const thirdPartyCookies = categories.reduce(
    (sum, cat) => sum + cat.cookies.filter(c => c.type === 'third-party').length,
    0
  )

  const stepInfo = STEP_EXPLANATIONS['cookie-banner']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="cookie-banner"
        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">
            Code 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">
            Veroeffentlichen
          </button>
        </div>
      </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">Kategorien</div>
          <div className="text-3xl font-bold text-gray-900">{categories.length}</div>
        </div>
        <div className="bg-white rounded-xl border border-blue-200 p-6">
          <div className="text-sm text-blue-600">Cookies gesamt</div>
          <div className="text-3xl font-bold text-blue-600">{totalCookies}</div>
        </div>
        <div className="bg-white rounded-xl border border-orange-200 p-6">
          <div className="text-sm text-orange-600">Third-Party</div>
          <div className="text-3xl font-bold text-orange-600">{thirdPartyCookies}</div>
        </div>
        <div className="bg-white rounded-xl border border-green-200 p-6">
          <div className="text-sm text-green-600">Aktive Kategorien</div>
          <div className="text-3xl font-bold text-green-600">
            {categories.filter(c => c.enabled).length}
          </div>
        </div>
      </div>

      {/* Preview */}
      <div className="bg-white rounded-xl border border-gray-200 p-6">
        <h3 className="font-semibold text-gray-900 mb-4">Banner-Vorschau</h3>
        <BannerPreview config={config} categories={categories} />
      </div>

      {/* Configuration */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <h3 className="font-semibold text-gray-900 mb-4">Banner-Einstellungen</h3>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Position</label>
              <select
                value={config.position}
                onChange={(e) => setConfig({ ...config, position: e.target.value as any })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
              >
                <option value="bottom">Unten</option>
                <option value="top">Oben</option>
                <option value="center">Zentriert</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Stil</label>
              <select
                value={config.style}
                onChange={(e) => setConfig({ ...config, style: e.target.value as any })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
              >
                <option value="bar">Balken</option>
                <option value="popup">Popup</option>
                <option value="modal">Modal</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Primaerfarbe</label>
              <input
                type="color"
                value={config.primaryColor}
                onChange={(e) => setConfig({ ...config, primaryColor: e.target.value })}
                className="w-full h-10 rounded-lg cursor-pointer"
              />
            </div>
            <div className="space-y-2">
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={config.showDeclineAll}
                  onChange={(e) => setConfig({ ...config, showDeclineAll: e.target.checked })}
                  className="w-4 h-4 text-purple-600"
                />
                <span className="text-sm">"Alle ablehnen" anzeigen</span>
              </label>
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={config.showSettings}
                  onChange={(e) => setConfig({ ...config, showSettings: e.target.checked })}
                  className="w-4 h-4 text-purple-600"
                />
                <span className="text-sm">Einstellungen-Link anzeigen</span>
              </label>
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={config.blockScripts}
                  onChange={(e) => setConfig({ ...config, blockScripts: e.target.checked })}
                  className="w-4 h-4 text-purple-600"
                />
                <span className="text-sm">Skripte vor Einwilligung blockieren</span>
              </label>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <h3 className="font-semibold text-gray-900 mb-4">Texte anpassen</h3>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Ueberschrift</label>
              <input
                type="text"
                defaultValue="Wir verwenden Cookies"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
              <textarea
                rows={3}
                defaultValue="Wir nutzen Cookies, um Ihnen die bestmoegliche Nutzung unserer Website zu ermoeglichen."
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Link zur Datenschutzerklaerung</label>
              <input
                type="text"
                defaultValue="/datenschutz"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
              />
            </div>
          </div>
        </div>
      </div>

      {/* Cookie Categories */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-semibold text-gray-900">Cookie-Kategorien</h3>
          <button className="text-sm text-purple-600 hover:text-purple-700">
            + Kategorie hinzufuegen
          </button>
        </div>
        <div className="space-y-4">
          {categories.map(category => (
            <CategoryCard
              key={category.id}
              category={category}
              onToggle={(enabled) => handleCategoryToggle(category.id, enabled)}
            />
          ))}
        </div>
      </div>
    </div>
  )
}
