'use client'

import React, { useState, useEffect } from 'react'
import Link from 'next/link'
import { ZoneBadge } from '@/components/sdk/compliance-optimizer/ZoneBadge'

interface OptimizationSummary {
  id: string
  title: string
  is_compliant: boolean
  constraint_version: string
  created_at: string
  zone_map: Record<string, { zone: 'FORBIDDEN' | 'RESTRICTED' | 'SAFE' }>
  max_safe_config?: { safety_score: number; utility_score: number }
}

function countZones(zoneMap: Record<string, { zone: string }>) {
  let forbidden = 0, restricted = 0, safe = 0
  for (const v of Object.values(zoneMap || {})) {
    if (v.zone === 'FORBIDDEN') forbidden++
    else if (v.zone === 'RESTRICTED') restricted++
    else safe++
  }
  return { forbidden, restricted, safe }
}

export default function ComplianceOptimizerPage() {
  const [optimizations, setOptimizations] = useState<OptimizationSummary[]>([])
  const [loading, setLoading] = useState(true)
  const [total, setTotal] = useState(0)

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

  async function fetchOptimizations() {
    try {
      setLoading(true)
      const res = await fetch('/api/sdk/v1/maximizer/optimizations?limit=20')
      if (res.ok) {
        const data = await res.json()
        setOptimizations(data.optimizations || [])
        setTotal(data.total || 0)
      }
    } catch {
      // silent
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="max-w-6xl mx-auto p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Compliance Optimizer</h1>
          <p className="text-sm text-gray-500 mt-1">
            Regulatorischen Spielraum maximieren — KI-Use-Cases optimal konfigurieren
          </p>
        </div>
        <Link
          href="/sdk/compliance-optimizer/new"
          className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 text-sm font-medium"
        >
          Neue Optimierung
        </Link>
      </div>

      {loading ? (
        <div className="text-center py-12 text-gray-500">Laden...</div>
      ) : optimizations.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 rounded-lg border border-gray-200">
          <p className="text-gray-600 mb-2">Noch keine Optimierungen durchgefuehrt.</p>
          <Link href="/sdk/compliance-optimizer/new" className="text-blue-600 hover:underline text-sm">
            Erste Optimierung starten
          </Link>
        </div>
      ) : (
        <div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Titel</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Zonen</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Datum</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {optimizations.map((o) => {
                const zones = countZones(o.zone_map)
                return (
                  <tr key={o.id} className="hover:bg-gray-50">
                    <td className="px-4 py-3">
                      <Link href={`/sdk/compliance-optimizer/${o.id}`} className="text-blue-600 hover:underline font-medium text-sm">
                        {o.title || 'Ohne Titel'}
                      </Link>
                    </td>
                    <td className="px-4 py-3">
                      <ZoneBadge zone={o.is_compliant ? 'SAFE' : 'FORBIDDEN'} />
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-600">
                      {zones.forbidden > 0 && <span className="text-red-600 mr-2">{zones.forbidden} verboten</span>}
                      {zones.restricted > 0 && <span className="text-yellow-600 mr-2">{zones.restricted} eingeschraenkt</span>}
                      <span className="text-green-600">{zones.safe} erlaubt</span>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-500">
                      {new Date(o.created_at).toLocaleDateString('de-DE')}
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
          {total > 20 && (
            <div className="px-4 py-3 bg-gray-50 text-sm text-gray-500">
              {total} Optimierungen insgesamt
            </div>
          )}
        </div>
      )}
    </div>
  )
}
