'use client'

/**
 * Audit Report Management Page (SDK Version)
 *
 * Create and manage GDPR audit sessions with PDF report generation.
 */

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

interface AuditSession {
  id: string
  name: string
  description?: string
  auditor_name: string
  auditor_email?: string
  auditor_organization?: string
  status: 'draft' | 'in_progress' | 'completed' | 'archived'
  regulation_ids?: string[]
  total_items: number
  completed_items: number
  compliant_count: number
  non_compliant_count: number
  completion_percentage: number
  created_at: string
  started_at?: string
  completed_at?: string
}

const REGULATIONS = [
  { code: 'GDPR', name: 'DSGVO / GDPR', description: 'EU-Datenschutzgrundverordnung' },
  { code: 'BDSG', name: 'BDSG', description: 'Bundesdatenschutzgesetz' },
  { code: 'TTDSG', name: 'TTDSG', description: 'Telekommunikation-Telemedien-Datenschutz' },
]

export default function AuditReportPage() {
  const { state } = useSDK()
  const router = useRouter()
  const [sessions, setSessions] = useState<AuditSession[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState<'sessions' | 'new' | 'export'>('sessions')

  const [newSession, setNewSession] = useState({
    name: '',
    description: '',
    auditor_name: '',
    auditor_email: '',
    auditor_organization: '',
    regulation_codes: [] as string[],
  })
  const [creating, setCreating] = useState(false)
  const [generatingPdf, setGeneratingPdf] = useState<string | null>(null)
  const [pdfLanguage, setPdfLanguage] = useState<'de' | 'en'>('de')
  const [statusFilter, setStatusFilter] = useState<string>('all')

  useEffect(() => {
    fetchSessions()
  }, [statusFilter])

  const fetchSessions = async () => {
    try {
      setLoading(true)
      const params = statusFilter !== 'all' ? `?status=${statusFilter}` : ''
      const res = await fetch(`/api/sdk/v1/compliance/audit/sessions${params}`)
      if (!res.ok) throw new Error('Fehler beim Laden der Audit-Sessions')
      const data = await res.json()
      setSessions(data.sessions || [])
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unbekannter Fehler')
    } finally {
      setLoading(false)
    }
  }

  const createSession = async () => {
    if (!newSession.name || !newSession.auditor_name) {
      setError('Name und Auditor-Name sind Pflichtfelder')
      return
    }
    try {
      setCreating(true)
      const res = await fetch('/api/sdk/v1/compliance/audit/sessions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newSession),
      })
      if (!res.ok) throw new Error('Fehler beim Erstellen der Session')
      setNewSession({ name: '', description: '', auditor_name: '', auditor_email: '', auditor_organization: '', regulation_codes: [] })
      setActiveTab('sessions')
      fetchSessions()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unbekannter Fehler')
    } finally {
      setCreating(false)
    }
  }

  const startSession = async (sessionId: string) => {
    try {
      const res = await fetch(`/api/sdk/v1/compliance/audit/sessions/${sessionId}/start`, { method: 'PUT' })
      if (!res.ok) throw new Error('Fehler beim Starten der Session')
      fetchSessions()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unbekannter Fehler')
    }
  }

  const completeSession = async (sessionId: string) => {
    try {
      const res = await fetch(`/api/sdk/v1/compliance/audit/sessions/${sessionId}/complete`, { method: 'PUT' })
      if (!res.ok) throw new Error('Fehler beim Abschliessen der Session')
      fetchSessions()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unbekannter Fehler')
    }
  }

  const deleteSession = async (sessionId: string) => {
    if (!confirm('Session wirklich loeschen?')) return
    try {
      const res = await fetch(`/api/sdk/v1/compliance/audit/sessions/${sessionId}`, { method: 'DELETE' })
      if (!res.ok) throw new Error('Fehler beim Loeschen der Session')
      fetchSessions()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unbekannter Fehler')
    }
  }

  const downloadPdf = async (sessionId: string) => {
    try {
      setGeneratingPdf(sessionId)
      const res = await fetch(`/api/sdk/v1/compliance/audit/sessions/${sessionId}/report/pdf?language=${pdfLanguage}`)
      if (!res.ok) throw new Error('Fehler bei der PDF-Generierung')
      const blob = await res.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `audit-report-${sessionId}.pdf`
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unbekannter Fehler')
    } finally {
      setGeneratingPdf(null)
    }
  }

  const getStatusBadge = (status: string) => {
    const styles: Record<string, string> = {
      draft: 'bg-slate-100 text-slate-700',
      in_progress: 'bg-blue-100 text-blue-700',
      completed: 'bg-green-100 text-green-700',
      archived: 'bg-purple-100 text-purple-700',
    }
    const labels: Record<string, string> = {
      draft: 'Entwurf',
      in_progress: 'In Bearbeitung',
      completed: 'Abgeschlossen',
      archived: 'Archiviert',
    }
    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${styles[status] || ''}`}>
        {labels[status] || status}
      </span>
    )
  }

  const getComplianceColor = (percentage: number) => {
    if (percentage >= 80) return 'text-green-600'
    if (percentage >= 50) return 'text-yellow-600'
    return 'text-red-600'
  }

  return (
    <div className="space-y-6">
      <StepHeader
        stepId="audit-report"
        title={STEP_EXPLANATIONS['audit-report']?.title || 'Audit Report'}
        description={STEP_EXPLANATIONS['audit-report']?.description || 'Audit-Berichte erstellen und verwalten'}
        explanation={STEP_EXPLANATIONS['audit-report']?.explanation || 'Erstellen Sie Audit-Sessions und generieren Sie PDF-Reports.'}
        tips={STEP_EXPLANATIONS['audit-report']?.tips}
        showProgress={true}
      />

      {error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-lg text-red-700 flex items-center justify-between">
          <span>{error}</span>
          <button onClick={() => setError(null)} className="text-red-500 hover:text-red-700">&times;</button>
        </div>
      )}

      {/* Tabs */}
      <div className="flex gap-2">
        {(['sessions', 'new', 'export'] as const).map((tab) => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={`px-4 py-2 rounded-lg font-medium transition-colors ${
              activeTab === tab ? 'bg-purple-600 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
            }`}
          >
            {tab === 'sessions' ? 'Audit-Sessions' : tab === 'new' ? '+ Neues Audit' : 'Export-Optionen'}
          </button>
        ))}
      </div>

      {/* Sessions Tab */}
      {activeTab === 'sessions' && (
        <div>
          <div className="flex items-center gap-4 mb-4">
            <label className="text-sm text-slate-600">Status:</label>
            <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)} className="px-3 py-2 border border-slate-200 rounded-lg text-sm">
              <option value="all">Alle</option>
              <option value="draft">Entwurf</option>
              <option value="in_progress">In Bearbeitung</option>
              <option value="completed">Abgeschlossen</option>
              <option value="archived">Archiviert</option>
            </select>
          </div>

          {loading ? (
            <div className="space-y-4">
              {[1, 2, 3].map(i => (
                <div key={i} className="bg-white rounded-xl border border-slate-200 p-6 animate-pulse">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-2">
                        <div className="h-6 w-48 bg-slate-200 rounded" />
                        <div className="h-5 w-20 bg-slate-200 rounded-full" />
                      </div>
                      <div className="h-4 w-64 bg-slate-100 rounded mt-2" />
                    </div>
                    <div className="text-right">
                      <div className="h-8 w-16 bg-slate-200 rounded" />
                      <div className="h-3 w-24 bg-slate-100 rounded mt-1" />
                    </div>
                  </div>
                  <div className="h-2 bg-slate-100 rounded-full mb-4" />
                  <div className="grid grid-cols-3 gap-4">
                    <div className="h-16 bg-slate-100 rounded-lg" />
                    <div className="h-16 bg-slate-100 rounded-lg" />
                    <div className="h-16 bg-slate-100 rounded-lg" />
                  </div>
                </div>
              ))}
            </div>
          ) : sessions.length === 0 ? (
            <div className="bg-white rounded-xl border border-slate-200 p-8 text-center">
              <h3 className="text-lg font-medium text-slate-700 mb-2">Keine Audit-Sessions vorhanden</h3>
              <p className="text-sm text-slate-500 mb-4">Erstellen Sie ein neues Audit, um mit der DSGVO-Pruefung zu beginnen.</p>
              <button onClick={() => setActiveTab('new')} className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700">Neues Audit erstellen</button>
            </div>
          ) : (
            <div className="space-y-4">
              {sessions.map((session) => (
                <div key={session.id} className="bg-white rounded-xl border border-slate-200 p-6 cursor-pointer hover:border-purple-300 transition-colors" onClick={() => router.push(`/sdk/audit-report/${session.id}`)}>
                  <div className="flex items-start justify-between mb-4">
                    <div>
                      <div className="flex items-center gap-3">
                        <h3 className="font-semibold text-slate-900">{session.name}</h3>
                        {getStatusBadge(session.status)}
                      </div>
                      {session.description && <p className="text-sm text-slate-500 mt-1">{session.description}</p>}
                      <div className="flex items-center gap-4 mt-2 text-xs text-slate-500">
                        <span>Auditor: {session.auditor_name}</span>
                        {session.auditor_organization && <span>| {session.auditor_organization}</span>}
                        <span>| Erstellt: {new Date(session.created_at).toLocaleDateString('de-DE')}</span>
                      </div>
                    </div>
                    <div className="text-right">
                      <div className={`text-2xl font-bold ${getComplianceColor(session.completion_percentage)}`}>{session.completion_percentage}%</div>
                      <div className="text-xs text-slate-500">{session.completed_items} / {session.total_items} Punkte</div>
                    </div>
                  </div>
                  <div className="h-2 bg-slate-100 rounded-full overflow-hidden mb-4">
                    <div className={`h-full transition-all ${session.completion_percentage >= 80 ? 'bg-green-500' : session.completion_percentage >= 50 ? 'bg-yellow-500' : 'bg-red-500'}`} style={{ width: `${session.completion_percentage}%` }} />
                  </div>
                  <div className="grid grid-cols-3 gap-4 mb-4 text-sm">
                    <div className="text-center p-3 bg-green-50 rounded-lg"><div className="font-semibold text-green-700">{session.compliant_count}</div><div className="text-xs text-green-600">Konform</div></div>
                    <div className="text-center p-3 bg-red-50 rounded-lg"><div className="font-semibold text-red-700">{session.non_compliant_count}</div><div className="text-xs text-red-600">Nicht Konform</div></div>
                    <div className="text-center p-3 bg-slate-50 rounded-lg"><div className="font-semibold text-slate-700">{session.total_items - session.completed_items}</div><div className="text-xs text-slate-600">Ausstehend</div></div>
                  </div>
                  <div className="flex items-center gap-2 pt-4 border-t border-slate-100">
                    {session.status === 'draft' && <button onClick={() => startSession(session.id)} className="px-3 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700">Audit starten</button>}
                    {session.status === 'in_progress' && <button onClick={() => completeSession(session.id)} className="px-3 py-2 bg-green-600 text-white text-sm rounded-lg hover:bg-green-700">Abschliessen</button>}
                    {(session.status === 'completed' || session.status === 'in_progress') && (
                      <button onClick={() => downloadPdf(session.id)} disabled={generatingPdf === session.id} className="px-3 py-2 bg-purple-600 text-white text-sm rounded-lg hover:bg-purple-700 disabled:opacity-50">
                        {generatingPdf === session.id ? 'Generiere PDF...' : 'PDF-Report'}
                      </button>
                    )}
                    {(session.status === 'draft' || session.status === 'archived') && <button onClick={() => deleteSession(session.id)} className="px-3 py-2 text-red-600 text-sm hover:text-red-700">Loeschen</button>}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* New Session Tab */}
      {activeTab === 'new' && (
        <div className="bg-white rounded-xl border border-slate-200 p-6">
          <h2 className="text-lg font-semibold text-slate-900 mb-4">Neues Audit erstellen</h2>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Audit-Name *</label>
              <input type="text" value={newSession.name} onChange={(e) => setNewSession({ ...newSession, name: e.target.value })} placeholder="z.B. DSGVO Jahresaudit 2026" className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Beschreibung</label>
              <textarea value={newSession.description} onChange={(e) => setNewSession({ ...newSession, description: e.target.value })} rows={3} placeholder="Optionale Beschreibung" className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Auditor Name *</label>
                <input type="text" value={newSession.auditor_name} onChange={(e) => setNewSession({ ...newSession, auditor_name: e.target.value })} placeholder="Name des Auditors" className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">E-Mail</label>
                <input type="email" value={newSession.auditor_email} onChange={(e) => setNewSession({ ...newSession, auditor_email: e.target.value })} placeholder="auditor@example.com" className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Organisation</label>
                <input type="text" value={newSession.auditor_organization} onChange={(e) => setNewSession({ ...newSession, auditor_organization: e.target.value })} placeholder="z.B. TUeV" className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">Zu pruefende Regelwerke</label>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                {REGULATIONS.map((reg) => (
                  <label key={reg.code} className={`flex items-center gap-3 p-3 border rounded-lg cursor-pointer transition-colors ${newSession.regulation_codes.includes(reg.code) ? 'border-purple-500 bg-purple-50' : 'border-slate-200 hover:border-slate-300'}`}>
                    <input type="checkbox" checked={newSession.regulation_codes.includes(reg.code)} onChange={(e) => { if (e.target.checked) { setNewSession({ ...newSession, regulation_codes: [...newSession.regulation_codes, reg.code] }) } else { setNewSession({ ...newSession, regulation_codes: newSession.regulation_codes.filter((c) => c !== reg.code) }) } }} className="w-4 h-4 text-purple-600" />
                    <div><div className="font-medium text-slate-800">{reg.name}</div><div className="text-xs text-slate-500">{reg.description}</div></div>
                  </label>
                ))}
              </div>
            </div>
            <div className="pt-4 border-t border-slate-100">
              <button onClick={createSession} disabled={creating} className="px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
                {creating ? 'Erstelle...' : 'Audit-Session erstellen'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Export Tab */}
      {activeTab === 'export' && (
        <div className="space-y-6">
          <div className="bg-white rounded-xl border border-slate-200 p-6">
            <h3 className="font-semibold text-slate-900 mb-4">PDF-Export Einstellungen</h3>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">Sprache</label>
              <div className="flex gap-3">
                <label className={`flex items-center gap-2 px-4 py-2 border rounded-lg cursor-pointer ${pdfLanguage === 'de' ? 'border-purple-500 bg-purple-50' : 'border-slate-200'}`}>
                  <input type="radio" checked={pdfLanguage === 'de'} onChange={() => setPdfLanguage('de')} className="w-4 h-4 text-purple-600" />
                  <span>Deutsch</span>
                </label>
                <label className={`flex items-center gap-2 px-4 py-2 border rounded-lg cursor-pointer ${pdfLanguage === 'en' ? 'border-purple-500 bg-purple-50' : 'border-slate-200'}`}>
                  <input type="radio" checked={pdfLanguage === 'en'} onChange={() => setPdfLanguage('en')} className="w-4 h-4 text-purple-600" />
                  <span>English</span>
                </label>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
