'use client'

import React, { useState, useEffect, useCallback } from 'react'
import { useParams } from 'next/navigation'
import { QuestionnaireView } from '../_components/QuestionnaireView'
import { AuditResult } from '../_components/AuditResult'

interface Question {
  id: string
  mc_id: string
  mc_name: string
  question: string
  question_type: string
  evidence_required: boolean
  pass_criteria: string[]
  fail_criteria: string[]
  severity: string
  regulation: string
  depends_on?: string
}

interface Audit {
  id: string
  tenant_id: string
  template_id: string
  name: string
  target_name: string
  status: string
  total_questions: number
  answered_questions: number
  compliance_score: number
  questions: Question[]
  created_at: string
  completed_at: string | null
}

interface Answer {
  id: string
  question_id: string
  mc_id: string
  value: unknown
  comment: string
  evidence_ids: string[]
  status: string
  answered_at: string
}

interface ScoreResult {
  audit_id: string
  total_questions: number
  answered: number
  passed: number
  failed: number
  skipped: number
  compliance_score: number
  by_regulation: Record<string, { total: number; passed: number; score: number }>
  by_severity: Record<string, { total: number; passed: number; failed: number }>
}

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

export default function AuditDetailPage() {
  const params = useParams()
  const auditId = params.auditId as string

  const [audit, setAudit] = useState<Audit | null>(null)
  const [answers, setAnswers] = useState<Answer[]>([])
  const [score, setScore] = useState<ScoreResult | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  const loadAudit = useCallback(async () => {
    try {
      const res = await fetch(`/api/sdk/v1/use-case/audits/${auditId}`, {
        headers: { 'X-Tenant-ID': TENANT_ID },
      })
      if (!res.ok) throw new Error('Audit nicht gefunden')
      const data = await res.json()
      setAudit(data.audit)
      setAnswers(data.answers || [])
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler')
    } finally {
      setLoading(false)
    }
  }, [auditId])

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

  const handleAnswer = async (questionId: string, value: unknown, comment: string) => {
    if (!audit) return
    try {
      const res = await fetch(`/api/sdk/v1/use-case/audits/${auditId}/answer`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Tenant-ID': TENANT_ID,
        },
        body: JSON.stringify({
          question_id: questionId,
          value,
          comment,
          status: 'answered',
        }),
      })
      if (!res.ok) throw new Error('Antwort konnte nicht gespeichert werden')
      const data = await res.json()

      // Update local state
      setAnswers(prev => {
        const idx = prev.findIndex(a => a.question_id === questionId)
        const newAnswer = data.answer
        if (idx >= 0) {
          const copy = [...prev]
          copy[idx] = newAnswer
          return copy
        }
        return [...prev, newAnswer]
      })

      if (data.progress) {
        setAudit(prev => prev ? {
          ...prev,
          answered_questions: data.progress.answered,
          compliance_score: data.progress.compliance_score,
          status: data.progress.answered >= prev.total_questions ? 'completed' : 'in_progress',
        } : null)
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler')
    }
  }

  const handleSkip = async (questionId: string) => {
    if (!audit) return
    try {
      await fetch(`/api/sdk/v1/use-case/audits/${auditId}/answer`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Tenant-ID': TENANT_ID,
        },
        body: JSON.stringify({
          question_id: questionId,
          value: null,
          status: 'skipped',
        }),
      })
      await loadAudit()
    } catch { /* ignore */ }
  }

  const loadScore = async () => {
    try {
      const res = await fetch(`/api/sdk/v1/use-case/audits/${auditId}/score`, {
        headers: { 'X-Tenant-ID': TENANT_ID },
      })
      if (res.ok) {
        const data = await res.json()
        setScore(data)
      }
    } catch { /* ignore */ }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-gray-500">Lade Audit...</div>
      </div>
    )
  }

  if (error || !audit) {
    return (
      <div className="min-h-screen bg-gray-50 py-8">
        <div className="max-w-4xl mx-auto px-4">
          <div className="bg-red-50 border border-red-200 rounded-lg p-4">
            <p className="text-red-700">{error || 'Audit nicht gefunden'}</p>
            <a href="/sdk/use-case-audit" className="text-sm text-red-500 mt-2 underline">
              Zurueck zur Liste
            </a>
          </div>
        </div>
      </div>
    )
  }

  const showResult = audit.status === 'completed' || score !== null

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-4xl mx-auto px-4">
        {/* Header */}
        <div className="mb-6 flex items-center justify-between">
          <div>
            <a href="/sdk/use-case-audit" className="text-sm text-blue-600 hover:text-blue-800 mb-1 inline-block">
              &larr; Alle Audits
            </a>
            <h1 className="text-2xl font-bold text-gray-900">{audit.name}</h1>
            {audit.target_name && (
              <p className="text-gray-600">{audit.target_name}</p>
            )}
          </div>
          <div className="flex items-center gap-3">
            {/* Progress indicator */}
            <div className="text-right">
              <div className="text-sm text-gray-500">
                {audit.answered_questions} / {audit.total_questions} beantwortet
              </div>
              <div className="w-32 h-2 bg-gray-200 rounded-full mt-1">
                <div
                  className="h-full bg-blue-500 rounded-full transition-all"
                  style={{ width: `${audit.total_questions > 0 ? (audit.answered_questions / audit.total_questions) * 100 : 0}%` }}
                />
              </div>
            </div>
            {audit.answered_questions > 0 && (
              <button
                onClick={loadScore}
                className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm font-medium"
              >
                Ergebnis anzeigen
              </button>
            )}
          </div>
        </div>

        {error && (
          <div className="mb-4 bg-red-50 border border-red-200 rounded-lg p-3">
            <p className="text-red-700 text-sm">{error}</p>
          </div>
        )}

        {showResult && score ? (
          <AuditResult audit={audit} score={score} />
        ) : (
          <QuestionnaireView
            questions={audit.questions}
            answers={answers}
            onAnswer={handleAnswer}
            onSkip={handleSkip}
          />
        )}
      </div>
    </div>
  )
}
