'use client'

import { useState } from 'react'

interface DeltaResult {
  added_patterns?: Array<{ pattern_name: string; hazard_cats: string[] }>
  removed_patterns?: Array<{ pattern_name: string; hazard_cats: string[] }>
  added_hazards?: Array<{ name: string; category: string }>
  removed_hazards?: Array<{ name: string; category: string }>
  added_measures?: Array<{ id: string; name: string }>
  removed_measures?: Array<{ id: string; name: string }>
}

interface DeltaPreviewModalProps {
  projectId: string
  currentInput: {
    component_library_ids: string[]
    energy_source_ids: string[]
    operational_states?: string[]
    human_roles?: string[]
  }
  proposedInput: {
    component_library_ids: string[]
    energy_source_ids: string[]
    operational_states?: string[]
    human_roles?: string[]
  }
  onClose: () => void
  onApply: () => void
  changeDescription: string
}

export function DeltaPreviewModal({
  projectId,
  currentInput,
  proposedInput,
  onClose,
  onApply,
  changeDescription,
}: DeltaPreviewModalProps) {
  const [result, setResult] = useState<DeltaResult | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  // Auto-run delta analysis on mount
  useState(() => {
    runDelta()
  })

  async function runDelta() {
    setLoading(true)
    setError('')
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/delta-analysis`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ current: currentInput, proposed: proposedInput }),
      })
      if (!res.ok) {
        setError('Delta-Analyse fehlgeschlagen')
        return
      }
      setResult(await res.json())
    } catch {
      setError('Verbindung fehlgeschlagen')
    } finally {
      setLoading(false)
    }
  }

  const addedP = result?.added_patterns?.length || 0
  const removedP = result?.removed_patterns?.length || 0
  const addedH = result?.added_hazards?.length || 0
  const removedH = result?.removed_hazards?.length || 0
  const addedM = result?.added_measures?.length || 0
  const removedM = result?.removed_measures?.length || 0
  const hasChanges = addedP + removedP + addedH + removedH + addedM + removedM > 0

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl w-full max-w-lg mx-4 max-h-[80vh] overflow-y-auto">
        {/* Header */}
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white">Delta-Vorschau</h2>
          <p className="text-xs text-gray-500 mt-0.5">{changeDescription}</p>
        </div>

        {/* Content */}
        <div className="px-6 py-4">
          {loading && (
            <div className="flex items-center justify-center py-8">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-purple-600" />
              <span className="ml-3 text-sm text-gray-500">Berechne Auswirkungen...</span>
            </div>
          )}

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

          {result && !loading && (
            <div className="space-y-4">
              {/* Summary Grid */}
              <div className="grid grid-cols-3 gap-3">
                <DeltaStat label="Patterns" added={addedP} removed={removedP} />
                <DeltaStat label="Gefaehrdungen" added={addedH} removed={removedH} />
                <DeltaStat label="Massnahmen" added={addedM} removed={removedM} />
              </div>

              {!hasChanges && (
                <p className="text-sm text-gray-400 italic text-center py-2">
                  Keine Auswirkungen erkannt — die Aenderung beeinflusst keine Patterns.
                </p>
              )}

              {/* Added Hazards */}
              {addedH > 0 && (
                <div>
                  <h3 className="text-xs font-semibold text-green-700 mb-1">+ Neue Gefaehrdungen</h3>
                  <ul className="space-y-0.5 max-h-32 overflow-y-auto">
                    {result!.added_hazards!.slice(0, 15).map((h, i) => (
                      <li key={i} className="text-xs text-gray-600 flex items-center gap-1">
                        <span className="text-green-500 flex-shrink-0">+</span>
                        <span className="truncate">{h.name || h.category}</span>
                      </li>
                    ))}
                    {addedH > 15 && <li className="text-xs text-gray-400">... und {addedH - 15} weitere</li>}
                  </ul>
                </div>
              )}

              {/* Removed Hazards */}
              {removedH > 0 && (
                <div>
                  <h3 className="text-xs font-semibold text-red-700 mb-1">- Entfallene Gefaehrdungen</h3>
                  <ul className="space-y-0.5 max-h-32 overflow-y-auto">
                    {result!.removed_hazards!.slice(0, 10).map((h, i) => (
                      <li key={i} className="text-xs text-gray-600 flex items-center gap-1">
                        <span className="text-red-500 flex-shrink-0">-</span>
                        <span className="truncate">{h.name || h.category}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex items-center justify-end gap-3">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm text-gray-600 hover:text-gray-800 transition-colors"
          >
            Abbrechen
          </button>
          <button
            onClick={onApply}
            disabled={loading}
            className="px-5 py-2 text-sm font-medium bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50"
          >
            Aenderung uebernehmen
          </button>
        </div>
      </div>
    </div>
  )
}

function DeltaStat({ label, added, removed }: { label: string; added: number; removed: number }) {
  return (
    <div className="text-center p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
      <div className="text-xs text-gray-500 mb-1">{label}</div>
      <div className="flex items-center justify-center gap-2">
        {added > 0 && <span className="text-sm font-bold text-green-600">+{added}</span>}
        {removed > 0 && <span className="text-sm font-bold text-red-600">-{removed}</span>}
        {added === 0 && removed === 0 && <span className="text-sm text-gray-400">0</span>}
      </div>
    </div>
  )
}
