'use client'

import React, { useState, useEffect, useRef, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import { useSDK, ChecklistItem as SDKChecklistItem } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'

// =============================================================================
// TYPES
// =============================================================================

type DisplayStatus = 'compliant' | 'non-compliant' | 'partial' | 'not-reviewed'
type DisplayPriority = 'critical' | 'high' | 'medium' | 'low'

interface DisplayChecklistItem {
  id: string
  requirementId: string
  question: string
  category: string
  status: DisplayStatus
  notes: string
  evidence: string[]
  priority: DisplayPriority
  verifiedBy: string | null
  verifiedAt: Date | null
}

// =============================================================================
// HELPER FUNCTIONS
// =============================================================================

function mapSDKStatusToDisplay(status: SDKChecklistItem['status']): DisplayStatus {
  switch (status) {
    case 'PASSED': return 'compliant'
    case 'FAILED': return 'non-compliant'
    case 'NOT_APPLICABLE': return 'partial'
    case 'PENDING':
    default: return 'not-reviewed'
  }
}

function mapDisplayStatusToSDK(status: DisplayStatus): SDKChecklistItem['status'] {
  switch (status) {
    case 'compliant': return 'PASSED'
    case 'non-compliant': return 'FAILED'
    case 'partial': return 'NOT_APPLICABLE'
    case 'not-reviewed':
    default: return 'PENDING'
  }
}

// =============================================================================
// FALLBACK TEMPLATES
// =============================================================================

interface ChecklistTemplate {
  id: string
  requirementId: string
  question: string
  category: string
  priority: DisplayPriority
}

const checklistTemplates: ChecklistTemplate[] = [
  {
    id: 'chk-vvt-001',
    requirementId: 'req-gdpr-30',
    question: 'Ist ein Verzeichnis von Verarbeitungstaetigkeiten (VVT) vorhanden und aktuell?',
    category: 'Dokumentation',
    priority: 'critical',
  },
  {
    id: 'chk-dse-001',
    requirementId: 'req-gdpr-13',
    question: 'Sind Datenschutzhinweise fuer alle Verarbeitungen verfuegbar?',
    category: 'Transparenz',
    priority: 'high',
  },
  {
    id: 'chk-consent-001',
    requirementId: 'req-gdpr-6',
    question: 'Werden Einwilligungen ordnungsgemaess eingeholt und dokumentiert?',
    category: 'Einwilligung',
    priority: 'high',
  },
  {
    id: 'chk-dsr-001',
    requirementId: 'req-gdpr-15',
    question: 'Ist ein Prozess fuer Betroffenenrechte implementiert?',
    category: 'Betroffenenrechte',
    priority: 'critical',
  },
  {
    id: 'chk-avv-001',
    requirementId: 'req-gdpr-28',
    question: 'Sind Auftragsverarbeitungsvertraege (AVV) mit allen Dienstleistern abgeschlossen?',
    category: 'Auftragsverarbeitung',
    priority: 'critical',
  },
  {
    id: 'chk-dsfa-001',
    requirementId: 'req-gdpr-35',
    question: 'Wird eine DSFA fuer Hochrisiko-Verarbeitungen durchgefuehrt?',
    category: 'Risikobewertung',
    priority: 'high',
  },
  {
    id: 'chk-tom-001',
    requirementId: 'req-gdpr-32',
    question: 'Sind technische und organisatorische Massnahmen dokumentiert?',
    category: 'TOMs',
    priority: 'high',
  },
  {
    id: 'chk-incident-001',
    requirementId: 'req-gdpr-33',
    question: 'Gibt es einen Incident-Response-Prozess fuer Datenpannen?',
    category: 'Incident Response',
    priority: 'critical',
  },
  {
    id: 'chk-ai-001',
    requirementId: 'req-ai-act-9',
    question: 'Ist das KI-System nach EU AI Act klassifiziert?',
    category: 'AI Act',
    priority: 'high',
  },
  {
    id: 'chk-ai-002',
    requirementId: 'req-ai-act-13',
    question: 'Sind Transparenzanforderungen fuer KI-Systeme erfuellt?',
    category: 'AI Act',
    priority: 'high',
  },
]

// =============================================================================
// COMPONENTS
// =============================================================================

function ChecklistItemCard({
  item,
  onStatusChange,
  onNotesChange,
  onAddEvidence,
}: {
  item: DisplayChecklistItem
  onStatusChange: (status: DisplayStatus) => void
  onNotesChange: (notes: string) => void
  onAddEvidence: () => void
}) {
  const [showNotes, setShowNotes] = useState(false)

  const statusColors = {
    compliant: 'bg-green-100 text-green-700 border-green-300',
    'non-compliant': 'bg-red-100 text-red-700 border-red-300',
    partial: 'bg-yellow-100 text-yellow-700 border-yellow-300',
    'not-reviewed': 'bg-gray-100 text-gray-500 border-gray-300',
  }

  const priorityColors = {
    critical: 'bg-red-100 text-red-700',
    high: 'bg-orange-100 text-orange-700',
    medium: 'bg-yellow-100 text-yellow-700',
    low: 'bg-green-100 text-green-700',
  }

  return (
    <div className={`bg-white rounded-xl border-2 p-6 ${
      item.status === 'non-compliant' ? 'border-red-200' :
      item.status === 'partial' ? 'border-yellow-200' :
      item.status === 'compliant' ? 'border-green-200' : 'border-gray-200'
    }`}>
      <div className="flex items-start gap-4">
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-2">
            <span className="text-xs text-gray-500">{item.category}</span>
            <span className={`px-2 py-0.5 text-xs rounded-full ${priorityColors[item.priority]}`}>
              {item.priority === 'critical' ? 'Kritisch' :
               item.priority === 'high' ? 'Hoch' :
               item.priority === 'medium' ? 'Mittel' : 'Niedrig'}
            </span>
            <span className="px-2 py-0.5 text-xs bg-blue-50 text-blue-600 rounded">
              {item.requirementId}
            </span>
          </div>
          <p className="text-gray-900 font-medium">{item.question}</p>
        </div>
        <select
          value={item.status}
          onChange={(e) => onStatusChange(e.target.value as DisplayStatus)}
          className={`px-3 py-2 rounded-lg border text-sm font-medium ${statusColors[item.status]}`}
        >
          <option value="not-reviewed">Nicht geprueft</option>
          <option value="compliant">Konform</option>
          <option value="partial">Teilweise</option>
          <option value="non-compliant">Nicht konform</option>
        </select>
      </div>

      {item.notes && (
        <div className="mt-3 p-3 bg-gray-50 rounded-lg text-sm text-gray-600">
          {item.notes}
        </div>
      )}

      {item.evidence.length > 0 && (
        <div className="mt-3 flex items-center gap-2">
          <span className="text-sm text-gray-500">Nachweise:</span>
          {item.evidence.map(ev => (
            <span key={ev} className="px-2 py-1 text-xs bg-blue-50 text-blue-600 rounded">
              {ev}
            </span>
          ))}
        </div>
      )}

      {item.verifiedBy && item.verifiedAt && (
        <div className="mt-3 text-sm text-gray-500">
          Geprueft von {item.verifiedBy} am {item.verifiedAt.toLocaleDateString('de-DE')}
        </div>
      )}

      <div className="mt-3 flex items-center gap-2">
        <button
          onClick={() => setShowNotes(!showNotes)}
          className="text-sm text-purple-600 hover:text-purple-700"
        >
          {showNotes ? 'Notizen ausblenden' : 'Notizen bearbeiten'}
        </button>
        <button
          onClick={onAddEvidence}
          className="text-sm text-gray-500 hover:text-gray-700"
        >
          Nachweis hinzufuegen
        </button>
      </div>

      {showNotes && (
        <div className="mt-3">
          <textarea
            value={item.notes}
            onChange={(e) => onNotesChange(e.target.value)}
            placeholder="Notizen hinzufuegen..."
            rows={2}
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent text-sm"
          />
        </div>
      )}
    </div>
  )
}

function LoadingSkeleton() {
  return (
    <div className="space-y-4">
      {[1, 2, 3].map(i => (
        <div key={i} className="bg-white rounded-xl border border-gray-200 p-6 animate-pulse">
          <div className="flex items-center gap-2 mb-3">
            <div className="h-4 w-24 bg-gray-200 rounded" />
            <div className="h-4 w-16 bg-gray-200 rounded-full" />
          </div>
          <div className="h-5 w-full bg-gray-200 rounded" />
        </div>
      ))}
    </div>
  )
}

// =============================================================================
// MAIN PAGE
// =============================================================================

export default function AuditChecklistPage() {
  const { state, dispatch } = useSDK()
  const router = useRouter()
  const [filter, setFilter] = useState<string>('all')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [activeSessionId, setActiveSessionId] = useState<string | null>(null)
  const notesTimerRef = useRef<Record<string, ReturnType<typeof setTimeout>>>({})

  // Fetch checklist from backend on mount
  useEffect(() => {
    const fetchChecklist = async () => {
      try {
        setLoading(true)

        // First, try to find an active audit session
        const sessionsRes = await fetch('/api/sdk/v1/compliance/audit/sessions?status=in_progress')
        if (sessionsRes.ok) {
          const sessionsData = await sessionsRes.json()
          const sessions = sessionsData.sessions || sessionsData
          if (Array.isArray(sessions) && sessions.length > 0) {
            const session = sessions[0]
            setActiveSessionId(session.id)

            // Fetch checklist items for this session
            const checklistRes = await fetch(`/api/sdk/v1/compliance/audit/checklist/${session.id}`)
            if (checklistRes.ok) {
              const checklistData = await checklistRes.json()
              const items = checklistData.items || checklistData.checklist || checklistData
              if (Array.isArray(items) && items.length > 0) {
                const mapped: SDKChecklistItem[] = items.map((item: Record<string, unknown>) => ({
                  id: (item.id || item.requirement_id || '') as string,
                  requirementId: (item.requirement_id || '') as string,
                  title: (item.title || item.question || '') as string,
                  description: (item.category || item.description || '') as string,
                  status: ((item.status || 'PENDING') as string).toUpperCase() as SDKChecklistItem['status'],
                  notes: (item.notes || item.auditor_notes || '') as string,
                  verifiedBy: (item.verified_by || item.signed_off_by || null) as string | null,
                  verifiedAt: item.verified_at || item.signed_off_at ? new Date((item.verified_at || item.signed_off_at) as string) : null,
                }))
                dispatch({ type: 'SET_STATE', payload: { checklist: mapped } })
                setError(null)
                return
              }
            }
          }
        }

        // Fallback: load from templates
        loadFromTemplates()
      } catch {
        loadFromTemplates()
      } finally {
        setLoading(false)
      }
    }

    const loadFromTemplates = () => {
      if (state.checklist.length > 0) return

      const templatesToLoad = state.requirements.length > 0
        ? checklistTemplates.filter(t =>
            state.requirements.some(r => r.id === t.requirementId)
          )
        : checklistTemplates

      const items: SDKChecklistItem[] = templatesToLoad.map(template => ({
        id: template.id,
        requirementId: template.requirementId,
        title: template.question,
        description: template.category,
        status: 'PENDING',
        notes: '',
        verifiedBy: null,
        verifiedAt: null,
      }))

      if (items.length > 0) {
        dispatch({ type: 'SET_STATE', payload: { checklist: items } })
      }
    }

    fetchChecklist()
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  // Convert SDK checklist items to display items
  const displayItems: DisplayChecklistItem[] = state.checklist.map(item => {
    const template = checklistTemplates.find(t => t.id === item.id)

    return {
      id: item.id,
      requirementId: item.requirementId,
      question: item.title,
      category: item.description || template?.category || 'Allgemein',
      status: mapSDKStatusToDisplay(item.status),
      notes: item.notes,
      evidence: [],
      priority: template?.priority || 'medium',
      verifiedBy: item.verifiedBy,
      verifiedAt: item.verifiedAt,
    }
  })

  const filteredItems = filter === 'all'
    ? displayItems
    : displayItems.filter(item => item.status === filter || item.category === filter)

  const compliantCount = displayItems.filter(i => i.status === 'compliant').length
  const nonCompliantCount = displayItems.filter(i => i.status === 'non-compliant').length
  const partialCount = displayItems.filter(i => i.status === 'partial').length
  const notReviewedCount = displayItems.filter(i => i.status === 'not-reviewed').length

  const progress = displayItems.length > 0
    ? Math.round(((compliantCount + partialCount * 0.5) / displayItems.length) * 100)
    : 0

  const handleStatusChange = async (itemId: string, status: DisplayStatus) => {
    const sdkStatus = mapDisplayStatusToSDK(status)
    const updatedChecklist = state.checklist.map(item =>
      item.id === itemId
        ? {
            ...item,
            status: sdkStatus,
            verifiedBy: status !== 'not-reviewed' ? 'Aktueller Benutzer' : null,
            verifiedAt: status !== 'not-reviewed' ? new Date() : null,
          }
        : item
    )
    dispatch({ type: 'SET_STATE', payload: { checklist: updatedChecklist } })

    // Persist to backend if we have an active session
    if (activeSessionId) {
      try {
        const item = state.checklist.find(i => i.id === itemId)
        await fetch(`/api/sdk/v1/compliance/audit/checklist/${activeSessionId}/items/${item?.requirementId || itemId}/sign-off`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            status: sdkStatus === 'PASSED' ? 'compliant' : sdkStatus === 'FAILED' ? 'non_compliant' : sdkStatus === 'NOT_APPLICABLE' ? 'partially_compliant' : 'not_assessed',
            auditor_notes: item?.notes || '',
          }),
        })
      } catch {
        // Silently fail
      }
    }
  }

  const handleNotesChange = useCallback((itemId: string, notes: string) => {
    const updatedChecklist = state.checklist.map(item =>
      item.id === itemId ? { ...item, notes } : item
    )
    dispatch({ type: 'SET_STATE', payload: { checklist: updatedChecklist } })

    // Debounced persistence to backend
    if (notesTimerRef.current[itemId]) {
      clearTimeout(notesTimerRef.current[itemId])
    }
    notesTimerRef.current[itemId] = setTimeout(async () => {
      if (activeSessionId) {
        const item = state.checklist.find(i => i.id === itemId)
        try {
          await fetch(`/api/sdk/v1/compliance/audit/checklist/${activeSessionId}/items/${item?.requirementId || itemId}/sign-off`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ notes }),
          })
        } catch {
          // Silently fail
        }
      }
    }, 1000)
  }, [state.checklist, activeSessionId, dispatch])

  const handleExport = () => {
    const exportData = displayItems.map(item => ({
      id: item.id,
      requirementId: item.requirementId,
      question: item.question,
      category: item.category,
      status: item.status,
      notes: item.notes,
      priority: item.priority,
      verifiedBy: item.verifiedBy,
      verifiedAt: item.verifiedAt?.toISOString() || null,
    }))
    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `audit-checklist-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  const handleNewChecklist = async () => {
    try {
      setError(null)
      const res = await fetch('/api/sdk/v1/compliance/audit/sessions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: `Compliance Audit ${new Date().toLocaleDateString('de-DE')}`,
          auditor_name: 'Aktueller Benutzer',
          regulation_codes: ['GDPR'],
        }),
      })
      if (res.ok) {
        // Reload data
        window.location.reload()
      } else {
        setError('Fehler beim Erstellen der neuen Checkliste')
      }
    } catch {
      setError('Verbindung zum Backend fehlgeschlagen')
    }
  }

  const stepInfo = STEP_EXPLANATIONS['audit-checklist']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="audit-checklist"
        title={stepInfo.title}
        description={stepInfo.description}
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      >
        <div className="flex items-center gap-2">
          <button
            onClick={handleExport}
            className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
          >
            Exportieren
          </button>
          <button
            onClick={handleNewChecklist}
            className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            Neue Checkliste
          </button>
        </div>
      </StepHeader>

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

      {/* Requirements Alert */}
      {state.requirements.length === 0 && !loading && (
        <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
          <div className="flex items-start gap-3">
            <svg className="w-5 h-5 text-amber-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
            <div>
              <h4 className="font-medium text-amber-800">Keine Anforderungen definiert</h4>
              <p className="text-sm text-amber-700 mt-1">
                Bitte definieren Sie zuerst Anforderungen, um die zugehoerige Checkliste zu generieren.
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Checklist Info */}
      <div className="bg-white rounded-xl border border-gray-200 p-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-xl font-semibold text-gray-900">Compliance Audit {new Date().getFullYear()}</h2>
            <p className="text-sm text-gray-500 mt-1">Jaehrliche Ueberpruefung der Compliance-Konformitaet</p>
            <div className="flex items-center gap-4 mt-2 text-sm text-gray-500">
              <span>Frameworks: DSGVO, AI Act</span>
              <span>Letzte Aktualisierung: {new Date().toLocaleDateString('de-DE')}</span>
              {activeSessionId && (
                <span className="px-2 py-0.5 text-xs bg-blue-50 text-blue-600 rounded">
                  Session aktiv
                </span>
              )}
            </div>
          </div>
          <div className="text-center">
            <div className="text-4xl font-bold text-purple-600">{progress}%</div>
            <div className="text-sm text-gray-500">Fortschritt</div>
          </div>
        </div>
        <div className="mt-4 h-3 bg-gray-100 rounded-full overflow-hidden">
          <div
            className="h-full bg-purple-600 rounded-full transition-all"
            style={{ width: `${progress}%` }}
          />
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border border-green-200 p-4">
          <div className="text-sm text-green-600">Konform</div>
          <div className="text-2xl font-bold text-green-600">{compliantCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-yellow-200 p-4">
          <div className="text-sm text-yellow-600">Teilweise</div>
          <div className="text-2xl font-bold text-yellow-600">{partialCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-red-200 p-4">
          <div className="text-sm text-red-600">Nicht konform</div>
          <div className="text-2xl font-bold text-red-600">{nonCompliantCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 p-4">
          <div className="text-sm text-gray-500">Nicht geprueft</div>
          <div className="text-2xl font-bold text-gray-500">{notReviewedCount}</div>
        </div>
      </div>

      {/* Filter */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-sm text-gray-500">Filter:</span>
        {['all', 'not-reviewed', 'non-compliant', 'partial', 'compliant'].map(f => (
          <button
            key={f}
            onClick={() => setFilter(f)}
            className={`px-3 py-1 text-sm rounded-full transition-colors ${
              filter === f
                ? 'bg-purple-600 text-white'
                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
            }`}
          >
            {f === 'all' ? 'Alle' :
             f === 'not-reviewed' ? 'Offen' :
             f === 'non-compliant' ? 'Nicht konform' :
             f === 'partial' ? 'Teilweise' : 'Konform'}
          </button>
        ))}
      </div>

      {/* Loading State */}
      {loading && <LoadingSkeleton />}

      {/* Checklist Items */}
      {!loading && (
        <div className="space-y-4">
          {filteredItems.map(item => (
            <ChecklistItemCard
              key={item.id}
              item={item}
              onStatusChange={(status) => handleStatusChange(item.id, status)}
              onNotesChange={(notes) => handleNotesChange(item.id, notes)}
              onAddEvidence={() => router.push('/sdk/evidence')}
            />
          ))}
        </div>
      )}

      {!loading && filteredItems.length === 0 && state.requirements.length > 0 && (
        <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
          <div className="w-16 h-16 mx-auto bg-gray-100 rounded-full flex items-center justify-center mb-4">
            <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">Keine Eintraege gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie den Filter an.</p>
        </div>
      )}
    </div>
  )
}
