'use client'

import React, { useState, useEffect, useCallback } from 'react'
import { UseCaseSelector } from './_components/UseCaseSelector'

interface Template {
  id: string
  name: string
  description: string
  mc_filters: string[]
  regulations: string[]
}

interface AuditSummary {
  id: string
  template_id: string
  name: string
  target_name: string
  status: string
  total_questions: number
  answered_questions: number
  compliance_score: number
  created_at: string
  completed_at: string | null
}

const TENANT_ID = '00000000-0000-0000-0000-000000000001'

const STATUS_LABELS: Record<string, { label: string; color: string }> = {
  draft: { label: 'Entwurf', color: 'bg-gray-100 text-gray-700' },
  in_progress: { label: 'In Bearbeitung', color: 'bg-blue-100 text-blue-700' },
  completed: { label: 'Abgeschlossen', color: 'bg-green-100 text-green-700' },
}

export default function UseCaseAuditPage() {
  const [view, setView] = useState<'list' | 'new'>('list')
  const [templates, setTemplates] = useState<Template[]>([])
  const [audits, setAudits] = useState<AuditSummary[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const loadData = useCallback(async () => {
    try {
      const [tRes, aRes] = await Promise.all([
        fetch('/api/sdk/v1/use-case/templates'),
        fetch('/api/sdk/v1/use-case/audits', {
          headers: { 'X-Tenant-ID': TENANT_ID },
        }),
      ])
      if (tRes.ok) {
        const td = await tRes.json()
        setTemplates(td.templates || [])
      }
      if (aRes.ok) {
        const ad = await aRes.json()
        setAudits(ad.audits || [])
      }
    } catch { /* ignore */ }
  }, [])

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

  const handleCreateAudit = async (templateId: string, name: string, targetName: string) => {
    setLoading(true)
    setError('')
    try {
      const res = await fetch('/api/sdk/v1/use-case/audits', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Tenant-ID': TENANT_ID,
        },
        body: JSON.stringify({
          template_id: templateId,
          name,
          target_name: targetName,
        }),
      })
      if (!res.ok) {
        const err = await res.json()
        throw new Error(err.error || 'Audit konnte nicht erstellt werden')
      }
      const data = await res.json()
      window.location.href = `/sdk/use-case-audit/${data.audit.id}`
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-6xl mx-auto px-4">
        <div className="mb-8 flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Use-Case Audits</h1>
            <p className="text-gray-600 mt-2">
              Compliance-Pruefungen aus Master Controls — interaktive Frageboegen mit Scoring.
            </p>
          </div>
          {view === 'list' ? (
            <button
              onClick={() => setView('new')}
              className="px-5 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium text-sm"
            >
              + Neuen Audit starten
            </button>
          ) : (
            <button
              onClick={() => setView('list')}
              className="px-4 py-2 text-sm text-blue-600 hover:text-blue-800 border border-blue-200 rounded-lg hover:bg-blue-50"
            >
              Zurueck zur Liste
            </button>
          )}
        </div>

        {error && (
          <div className="mb-6 bg-red-50 border border-red-200 rounded-lg p-4">
            <p className="text-red-700">{error}</p>
            <button onClick={() => setError('')} className="text-sm text-red-500 mt-1 underline">
              Schliessen
            </button>
          </div>
        )}

        {view === 'new' && (
          <UseCaseSelector
            templates={templates}
            onCreateAudit={handleCreateAudit}
            loading={loading}
          />
        )}

        {view === 'list' && (
          <div>
            {audits.length > 0 ? (
              <div className="space-y-3">
                {audits.map(a => {
                  const st = STATUS_LABELS[a.status] || STATUS_LABELS.draft
                  const progress = a.total_questions > 0
                    ? Math.round((a.answered_questions / a.total_questions) * 100)
                    : 0
                  return (
                    <a
                      key={a.id}
                      href={`/sdk/use-case-audit/${a.id}`}
                      className="block bg-white rounded-xl shadow-sm border border-gray-200 p-5 hover:shadow-md hover:border-blue-300 transition-all"
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex-1 min-w-0">
                          <h3 className="font-semibold text-gray-900 truncate">{a.name}</h3>
                          {a.target_name && (
                            <p className="text-sm text-gray-500 mt-0.5">{a.target_name}</p>
                          )}
                        </div>
                        <div className="flex items-center gap-3 ml-4">
                          <span className={`px-3 py-1 rounded-full text-xs font-medium ${st.color}`}>
                            {st.label}
                          </span>
                          <div className="text-right">
                            <div className="text-sm font-medium text-gray-700">
                              {a.answered_questions}/{a.total_questions}
                            </div>
                            <div className="w-20 h-1.5 bg-gray-200 rounded-full mt-1">
                              <div
                                className="h-full bg-blue-500 rounded-full transition-all"
                                style={{ width: `${progress}%` }}
                              />
                            </div>
                          </div>
                          {a.status === 'completed' && (
                            <div className={`text-lg font-bold ${
                              a.compliance_score >= 80 ? 'text-green-600' :
                              a.compliance_score >= 50 ? 'text-yellow-600' : 'text-red-600'
                            }`}>
                              {Math.round(a.compliance_score)}%
                            </div>
                          )}
                          <span className="text-xs text-gray-400">
                            {new Date(a.created_at).toLocaleDateString('de-DE')}
                          </span>
                        </div>
                      </div>
                    </a>
                  )
                })}
              </div>
            ) : (
              <div className="text-center py-16 bg-white rounded-xl border border-gray-200">
                <div className="text-4xl mb-4">&#128203;</div>
                <h3 className="text-lg font-medium text-gray-700 mb-2">Noch keine Audits</h3>
                <p className="text-gray-500 mb-6">Starten Sie Ihren ersten Compliance-Audit.</p>
                <button
                  onClick={() => setView('new')}
                  className="px-5 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium text-sm"
                >
                  Jetzt starten
                </button>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
