'use client'

import React, { useState, useEffect } from 'react'
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'
  }
}

// =============================================================================
// CHECKLIST 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,
}: {
  item: DisplayChecklistItem
  onStatusChange: (status: DisplayStatus) => void
  onNotesChange: (notes: string) => 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 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>
  )
}

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

export default function AuditChecklistPage() {
  const { state, dispatch } = useSDK()
  const [filter, setFilter] = useState<string>('all')

  // Load checklist items based on requirements when requirements exist
  useEffect(() => {
    if (state.requirements.length > 0 && state.checklist.length === 0) {
      // Add relevant checklist items based on requirements
      const relevantItems = checklistTemplates.filter(t =>
        state.requirements.some(r => r.id === t.requirementId)
      )

      relevantItems.forEach(template => {
        const sdkItem: SDKChecklistItem = {
          id: template.id,
          requirementId: template.requirementId,
          title: template.question,
          description: template.category,
          status: 'PENDING',
          notes: '',
          verifiedBy: null,
          verifiedAt: null,
        }
        dispatch({ type: 'SET_STATE', payload: { checklist: [...state.checklist, sdkItem] } })
      })

      // If no requirements match, add all templates
      if (relevantItems.length === 0) {
        checklistTemplates.forEach(template => {
          const sdkItem: SDKChecklistItem = {
            id: template.id,
            requirementId: template.requirementId,
            title: template.question,
            description: template.category,
            status: 'PENDING',
            notes: '',
            verifiedBy: null,
            verifiedAt: null,
          }
          dispatch({ type: 'SET_STATE', payload: { checklist: [...state.checklist, sdkItem] } })
        })
      }
    }
  }, [state.requirements, state.checklist.length, dispatch])

  // 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: [], // Evidence is tracked separately in SDK
      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 = (itemId: string, status: DisplayStatus) => {
    const updatedChecklist = state.checklist.map(item =>
      item.id === itemId
        ? {
            ...item,
            status: mapDisplayStatusToSDK(status),
            verifiedBy: status !== 'not-reviewed' ? 'Aktueller Benutzer' : null,
            verifiedAt: status !== 'not-reviewed' ? new Date() : null,
          }
        : item
    )
    dispatch({ type: 'SET_STATE', payload: { checklist: updatedChecklist } })
  }

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

  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 className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
            Exportieren
          </button>
          <button 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>

      {/* Requirements Alert */}
      {state.requirements.length === 0 && (
        <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>
            </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>

      {/* Checklist Items */}
      <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)}
          />
        ))}
      </div>

      {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>
  )
}
