'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'

interface ChecklistItem {
  requirement_id: string
  title: string
  article?: string
  status: string
  auditor_notes: string
  signed_off_by: string | null
  signed_off_at: string | null
}

interface SessionDetail {
  id: string
  name: string
  description?: string
  auditor_name: string
  auditor_email?: string
  auditor_organization?: string
  status: 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
}

export default function AuditReportDetailPage() {
  const params = useParams()
  const router = useRouter()
  const sessionId = params.sessionId as string

  const [session, setSession] = useState<SessionDetail | null>(null)
  const [items, setItems] = useState<ChecklistItem[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [pdfLanguage, setPdfLanguage] = useState<'de' | 'en'>('de')
  const [generatingPdf, setGeneratingPdf] = useState(false)

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)

        // Fetch session details
        const sessRes = await fetch(`/api/sdk/v1/compliance/audit/sessions`)
        if (sessRes.ok) {
          const data = await sessRes.json()
          const sessions = data.sessions || []
          const found = sessions.find((s: SessionDetail) => s.id === sessionId)
          if (found) setSession(found)
        }

        // Fetch checklist items
        const checkRes = await fetch(`/api/sdk/v1/compliance/audit/checklist/${sessionId}`)
        if (checkRes.ok) {
          const data = await checkRes.json()
          const checklistItems = data.items || data.checklist || data
          if (Array.isArray(checklistItems)) {
            setItems(checklistItems)
          }
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Laden fehlgeschlagen')
      } finally {
        setLoading(false)
      }
    }

    if (sessionId) fetchData()
  }, [sessionId])

  const handleSignOff = async (requirementId: string, status: string, notes: string) => {
    try {
      const res = await fetch(
        `/api/sdk/v1/compliance/audit/checklist/${sessionId}/items/${requirementId}/sign-off`,
        {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ status, auditor_notes: notes }),
        }
      )
      if (res.ok) {
        setItems(prev =>
          prev.map(item =>
            item.requirement_id === requirementId
              ? { ...item, status, auditor_notes: notes, signed_off_by: 'Aktueller Benutzer', signed_off_at: new Date().toISOString() }
              : item
          )
        )
      }
    } catch {
      // Silently fail
    }
  }

  const handlePdfDownload = async () => {
    setGeneratingPdf(true)
    setError(null)
    try {
      const res = await fetch(`/api/sdk/v1/compliance/audit/sessions/${sessionId}/report/pdf?language=${pdfLanguage}`)
      if (!res.ok) throw new Error('PDF-Generierung fehlgeschlagen')
      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 : 'PDF-Download fehlgeschlagen')
    } finally {
      setGeneratingPdf(false)
    }
  }

  const statusBadgeStyles: 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 statusLabels: Record<string, string> = {
    draft: 'Entwurf',
    in_progress: 'In Bearbeitung',
    completed: 'Abgeschlossen',
    archived: 'Archiviert',
  }

  const compliantCount = items.filter(i => i.status === 'compliant').length
  const nonCompliantCount = items.filter(i => i.status === 'non_compliant' || i.status === 'non-compliant').length
  const pendingCount = items.filter(i => !i.status || i.status === 'not_assessed' || i.status === 'pending').length

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="bg-white rounded-xl border border-slate-200 p-6 animate-pulse">
          <div className="h-8 w-64 bg-slate-200 rounded mb-4" />
          <div className="h-4 w-96 bg-slate-100 rounded mb-2" />
          <div className="h-4 w-48 bg-slate-100 rounded" />
        </div>
        <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="h-5 w-3/4 bg-slate-200 rounded mb-2" />
              <div className="h-4 w-1/2 bg-slate-100 rounded" />
            </div>
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Back Button + Title */}
      <div className="flex items-center gap-4">
        <button
          onClick={() => router.push('/sdk/audit-report')}
          className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
        >
          <svg className="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
          </svg>
        </button>
        <div className="flex-1">
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-bold text-gray-900">{session?.name || 'Audit Report'}</h1>
            {session && (
              <span className={`px-2 py-1 text-xs rounded-full ${statusBadgeStyles[session.status] || ''}`}>
                {statusLabels[session.status] || session.status}
              </span>
            )}
          </div>
          {session && (
            <div className="flex items-center gap-4 text-sm text-gray-500 mt-1">
              <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="flex items-center gap-2">
          <select
            value={pdfLanguage}
            onChange={(e) => setPdfLanguage(e.target.value as 'de' | 'en')}
            className="px-2 py-2 border border-gray-300 rounded-l-lg text-sm"
          >
            <option value="de">DE</option>
            <option value="en">EN</option>
          </select>
          <button
            onClick={handlePdfDownload}
            disabled={generatingPdf}
            className="px-4 py-2 bg-purple-600 text-white text-sm rounded-r-lg hover:bg-purple-700 disabled:opacity-50"
          >
            {generatingPdf ? 'Generiere...' : 'PDF herunterladen'}
          </button>
        </div>
      </div>

      {/* Error */}
      {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>
      )}

      {/* Progress */}
      {session && (
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-gray-900">Fortschritt</h2>
            <span className={`text-3xl font-bold ${
              session.completion_percentage >= 80 ? 'text-green-600' :
              session.completion_percentage >= 50 ? 'text-yellow-600' : 'text-red-600'
            }`}>
              {session.completion_percentage}%
            </span>
          </div>
          <div className="h-3 bg-gray-100 rounded-full overflow-hidden mb-4">
            <div
              className={`h-full rounded-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 text-sm">
            <div className="text-center p-3 bg-green-50 rounded-lg">
              <div className="font-semibold text-green-700">{compliantCount}</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">{nonCompliantCount}</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">{pendingCount}</div>
              <div className="text-xs text-slate-600">Ausstehend</div>
            </div>
          </div>
        </div>
      )}

      {/* Checklist Items */}
      <div className="space-y-3">
        <h2 className="text-lg font-semibold text-gray-900">Pruefpunkte ({items.length})</h2>
        {items.map((item) => (
          <ChecklistItemRow
            key={item.requirement_id}
            item={item}
            onSignOff={handleSignOff}
            readOnly={session?.status === 'completed' || session?.status === 'archived'}
          />
        ))}
      </div>

      {items.length === 0 && !loading && (
        <div className="bg-white rounded-xl border border-gray-200 p-8 text-center">
          <h3 className="text-lg font-medium text-gray-700 mb-2">Keine Pruefpunkte</h3>
          <p className="text-sm text-gray-500">Diese Session hat noch keine Checklist-Items.</p>
        </div>
      )}
    </div>
  )
}

function ChecklistItemRow({
  item,
  onSignOff,
  readOnly,
}: {
  item: ChecklistItem
  onSignOff: (requirementId: string, status: string, notes: string) => void
  readOnly: boolean
}) {
  const [editing, setEditing] = useState(false)
  const [notes, setNotes] = useState(item.auditor_notes || '')

  const statusColors: Record<string, string> = {
    compliant: 'border-green-200 bg-green-50',
    non_compliant: 'border-red-200 bg-red-50',
    'non-compliant': 'border-red-200 bg-red-50',
    partially_compliant: 'border-yellow-200 bg-yellow-50',
    not_assessed: 'border-gray-200 bg-gray-50',
    pending: 'border-gray-200 bg-gray-50',
  }

  const statusLabels: Record<string, string> = {
    compliant: 'Konform',
    non_compliant: 'Nicht konform',
    'non-compliant': 'Nicht konform',
    partially_compliant: 'Teilweise',
    not_assessed: 'Nicht geprueft',
    pending: 'Ausstehend',
  }

  return (
    <div className={`bg-white rounded-xl border-2 p-4 ${statusColors[item.status] || 'border-gray-200'}`}>
      <div className="flex items-start justify-between">
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-1">
            {item.article && (
              <span className="px-2 py-0.5 text-xs bg-blue-50 text-blue-600 rounded">{item.article}</span>
            )}
            <span className={`px-2 py-0.5 text-xs rounded-full ${
              item.status === 'compliant' ? 'bg-green-100 text-green-700' :
              item.status === 'non_compliant' || item.status === 'non-compliant' ? 'bg-red-100 text-red-700' :
              item.status === 'partially_compliant' ? 'bg-yellow-100 text-yellow-700' :
              'bg-gray-100 text-gray-500'
            }`}>
              {statusLabels[item.status] || item.status}
            </span>
          </div>
          <p className="text-sm font-medium text-gray-900">{item.title}</p>
          {item.auditor_notes && !editing && (
            <p className="text-xs text-gray-500 mt-1">{item.auditor_notes}</p>
          )}
          {item.signed_off_by && (
            <p className="text-xs text-gray-400 mt-1">
              Geprueft von {item.signed_off_by}
              {item.signed_off_at && ` am ${new Date(item.signed_off_at).toLocaleDateString('de-DE')}`}
            </p>
          )}
        </div>
        {!readOnly && (
          <div className="flex items-center gap-1">
            <select
              value={item.status || 'not_assessed'}
              onChange={(e) => onSignOff(item.requirement_id, e.target.value, item.auditor_notes || '')}
              className="px-2 py-1 text-xs border border-gray-300 rounded-lg"
            >
              <option value="not_assessed">Nicht geprueft</option>
              <option value="compliant">Konform</option>
              <option value="partially_compliant">Teilweise</option>
              <option value="non_compliant">Nicht konform</option>
            </select>
            <button
              onClick={() => setEditing(!editing)}
              className="p-1 text-gray-400 hover:text-gray-600 rounded"
              title="Notizen bearbeiten"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
              </svg>
            </button>
          </div>
        )}
      </div>
      {editing && (
        <div className="mt-3">
          <textarea
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            placeholder="Notizen hinzufuegen..."
            rows={2}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          />
          <div className="flex justify-end gap-2 mt-2">
            <button onClick={() => setEditing(false)} className="px-3 py-1 text-sm text-gray-500 hover:bg-gray-100 rounded-lg">
              Abbrechen
            </button>
            <button
              onClick={() => {
                onSignOff(item.requirement_id, item.status, notes)
                setEditing(false)
              }}
              className="px-3 py-1 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700"
            >
              Speichern
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
