'use client'

import { useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { useOperationalStates, type OperationalStateInfo } from './_hooks/useOperationalStates'

// ── State descriptions for ISO 12100 context ───────────────
const STATE_DESCRIPTIONS: Record<string, string> = {
  startup: 'Erstmaliges oder wiederholtes Einschalten der Maschine',
  homing: 'Referenzfahrt der Achsen nach dem Einschalten',
  automatic_operation: 'Vollautomatischer Produktionsbetrieb',
  manual_operation: 'Manuell gesteuerter Betrieb (Handrad, Tippbetrieb)',
  teach_mode: 'Programmierung und Einrichten bei reduzierter Geschwindigkeit',
  maintenance: 'Geplante Wartungs- und Instandhaltungsarbeiten',
  cleaning: 'Reinigung der Maschine und des Arbeitsbereichs',
  emergency_stop: 'Not-Halt ausgeloest — Maschine im sicheren Zustand',
  recovery_mode: 'Wiederanlauf nach Not-Halt oder Stoerung',
}

const STATE_ICONS: Record<string, string> = {
  startup: 'M13 10V3L4 14h7v7l9-11h-7z',
  homing: 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-4 0h4',
  automatic_operation: 'M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15',
  manual_operation: 'M7 11.5V14m0-2.5v-6a1.5 1.5 0 113 0m-3 6a1.5 1.5 0 00-3 0v2a7.5 7.5 0 0015 0v-5a1.5 1.5 0 00-3 0m-6-3V11m0-5.5v-1a1.5 1.5 0 013 0v1m0 0V11m0-5.5a1.5 1.5 0 013 0v3m0 0V11',
  teach_mode: 'M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z',
  maintenance: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z',
  cleaning: 'M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z',
  emergency_stop: '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',
  recovery_mode: 'M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15',
}

const STATE_COLORS: Record<string, { bg: string; border: string; text: string }> = {
  startup: { bg: 'bg-blue-50 dark:bg-blue-900/20', border: 'border-blue-200 dark:border-blue-800', text: 'text-blue-700 dark:text-blue-300' },
  homing: { bg: 'bg-indigo-50 dark:bg-indigo-900/20', border: 'border-indigo-200 dark:border-indigo-800', text: 'text-indigo-700 dark:text-indigo-300' },
  automatic_operation: { bg: 'bg-green-50 dark:bg-green-900/20', border: 'border-green-200 dark:border-green-800', text: 'text-green-700 dark:text-green-300' },
  manual_operation: { bg: 'bg-yellow-50 dark:bg-yellow-900/20', border: 'border-yellow-200 dark:border-yellow-800', text: 'text-yellow-700 dark:text-yellow-300' },
  teach_mode: { bg: 'bg-orange-50 dark:bg-orange-900/20', border: 'border-orange-200 dark:border-orange-800', text: 'text-orange-700 dark:text-orange-300' },
  maintenance: { bg: 'bg-purple-50 dark:bg-purple-900/20', border: 'border-purple-200 dark:border-purple-800', text: 'text-purple-700 dark:text-purple-300' },
  cleaning: { bg: 'bg-cyan-50 dark:bg-cyan-900/20', border: 'border-cyan-200 dark:border-cyan-800', text: 'text-cyan-700 dark:text-cyan-300' },
  emergency_stop: { bg: 'bg-red-50 dark:bg-red-900/20', border: 'border-red-200 dark:border-red-800', text: 'text-red-700 dark:text-red-300' },
  recovery_mode: { bg: 'bg-amber-50 dark:bg-amber-900/20', border: 'border-amber-200 dark:border-amber-800', text: 'text-amber-700 dark:text-amber-300' },
}

export default function OperationalStatesPage() {
  const { projectId } = useParams<{ projectId: string }>()
  const router = useRouter()
  const {
    allStates,
    activeTransitions,
    selectedStates,
    toggleState,
    saveSelection,
    runDeltaAnalysis,
    loading,
    saving,
    saved,
    deltaResult,
    deltaLoading,
  } = useOperationalStates(projectId)

  const [initStatus, setInitStatus] = useState<'idle' | 'running' | 'done' | 'error'>('idle')
  const [initResult, setInitResult] = useState<{ steps: { name: string; status: string; count: number; details?: string }[]; summary?: Record<string, number> } | null>(null)

  async function handleInitialize(force: boolean) {
    // Save current selection first
    await saveSelection(selectedStates)
    setInitStatus('running')
    setInitResult(null)
    try {
      const url = `/api/sdk/v1/iace/projects/${projectId}/initialize${force ? '?force=true' : ''}`
      const res = await fetch(url, { method: 'POST' })
      if (!res.ok) {
        const err = await res.json().catch(() => ({}))
        alert(err.error || 'Initialisierung fehlgeschlagen')
        setInitStatus('error')
        return
      }
      const data = await res.json()
      setInitResult(data)
      setInitStatus('done')
    } catch {
      setInitStatus('error')
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600" />
      </div>
    )
  }

  const hasChanges = true // always allow save (metadata merge is idempotent)

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold text-gray-900 dark:text-white">Betriebszustaende</h1>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
            Waehlen Sie die relevanten Betriebszustaende fuer diese Maschine (ISO 12100 Abschnitt 5)
          </p>
        </div>
        <div className="flex items-center gap-3">
          {saved && (
            <span className="flex items-center gap-1 text-xs text-green-600 dark:text-green-400">
              <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
              Gespeichert
            </span>
          )}
          <span className="px-2.5 py-1 rounded-full text-xs font-medium bg-purple-50 text-purple-700 border border-purple-200 dark:bg-purple-900/30 dark:text-purple-300 dark:border-purple-700">
            {selectedStates.length} / {allStates.length} aktiv
          </span>
        </div>
      </div>

      {/* State Selection Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
        {allStates.map((state) => (
          <StateCard
            key={state.id}
            state={state}
            selected={selectedStates.includes(state.id)}
            onToggle={() => toggleState(state.id)}
          />
        ))}
      </div>

      {/* Active Transitions */}
      {selectedStates.length >= 2 && (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5">
          <h2 className="text-sm font-semibold text-gray-900 dark:text-white mb-3">
            Zustandsuebergaenge ({activeTransitions.length})
          </h2>
          <p className="text-xs text-gray-500 dark:text-gray-400 mb-4">
            Gueltige Uebergaenge zwischen den ausgewaehlten Betriebszustaenden gemaess ISO 12100 State Graph
          </p>
          {activeTransitions.length === 0 ? (
            <p className="text-xs text-gray-400 italic">
              Keine direkten Uebergaenge zwischen den ausgewaehlten Zustaenden.
            </p>
          ) : (
            <div className="flex flex-wrap gap-2">
              {activeTransitions.map((t) => {
                const [from, to] = t.split('\u2192')
                const fromLabel = allStates.find((s) => s.id === from)?.label_de || from
                const toLabel = allStates.find((s) => s.id === to)?.label_de || to
                return (
                  <div
                    key={t}
                    className="flex items-center gap-1.5 px-3 py-1.5 bg-gray-50 dark:bg-gray-700 rounded-lg text-xs"
                  >
                    <span className="font-medium text-gray-700 dark:text-gray-300">{fromLabel}</span>
                    <svg className="w-3.5 h-3.5 text-purple-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
                    </svg>
                    <span className="font-medium text-gray-700 dark:text-gray-300">{toLabel}</span>
                  </div>
                )
              })}
            </div>
          )}
        </div>
      )}

      {/* Delta Analysis */}
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5">
        <div className="flex items-center justify-between mb-3">
          <div>
            <h2 className="text-sm font-semibold text-gray-900 dark:text-white">Delta-Vorschau</h2>
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
              Zeigt die Auswirkungen der Zustandsaenderung auf Gefaehrdungen und Massnahmen
            </p>
          </div>
          <button
            onClick={() => runDeltaAnalysis(selectedStates)}
            disabled={deltaLoading || selectedStates.length === 0}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {deltaLoading ? (
              <>
                <span className="animate-spin inline-block w-3.5 h-3.5 border-2 border-gray-400 border-t-transparent rounded-full" />
                Analyse...
              </>
            ) : (
              <>
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <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 2" />
                </svg>
                Delta berechnen
              </>
            )}
          </button>
        </div>

        {deltaResult && (
          <div className="space-y-3 mt-3 pt-3 border-t border-gray-200 dark:border-gray-700">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              <DeltaStat label="Neue Muster" value={deltaResult.added_patterns} positive />
              <DeltaStat label="Entfernte Muster" value={deltaResult.removed_patterns} positive={false} />
              <DeltaStat label="Neue Gefaehrdungen" value={deltaResult.added_hazards.length} positive />
              <DeltaStat label="Entfernte Gefaehrdungen" value={deltaResult.removed_hazards.length} positive={false} />
            </div>

            {deltaResult.added_hazards.length > 0 && (
              <div>
                <h3 className="text-xs font-medium text-green-700 dark:text-green-400 mb-1">
                  + Neue Gefaehrdungen
                </h3>
                <ul className="space-y-0.5">
                  {deltaResult.added_hazards.slice(0, 10).map((h, i) => (
                    <li key={i} className="text-xs text-gray-600 dark:text-gray-400 flex items-center gap-1">
                      <span className="text-green-500">+</span> {h}
                    </li>
                  ))}
                  {deltaResult.added_hazards.length > 10 && (
                    <li className="text-xs text-gray-400">... und {deltaResult.added_hazards.length - 10} weitere</li>
                  )}
                </ul>
              </div>
            )}

            {deltaResult.added_measures.length > 0 && (
              <div>
                <h3 className="text-xs font-medium text-blue-700 dark:text-blue-400 mb-1">
                  + Neue Massnahmen ({deltaResult.added_measures.length})
                </h3>
              </div>
            )}

            {deltaResult.added_patterns === 0 && deltaResult.removed_patterns === 0 && (
              <p className="text-xs text-gray-400 italic">Keine Aenderungen erkannt — die Zustandsauswahl hat keinen Einfluss auf die aktuellen Patterns.</p>
            )}
          </div>
        )}
      </div>

      {/* Initialize Section */}
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5">
        <h2 className="text-sm font-semibold text-gray-900 dark:text-white mb-1">Projekt initialisieren</h2>
        <p className="text-xs text-gray-500 dark:text-gray-400 mb-4">
          Erzeugt Gefaehrdungen und Massnahmen basierend auf Maschinenbeschreibung, Komponenten und den ausgewaehlten Betriebszustaenden.
        </p>
        <div className="flex items-center gap-3">
          <button
            disabled={initStatus === 'running' || selectedStates.length === 0}
            onClick={() => handleInitialize(false)}
            className="flex items-center gap-2 px-5 py-2.5 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {initStatus === 'running' ? (
              <>
                <span className="animate-spin inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full" />
                Analyse laeuft...
              </>
            ) : (
              <>
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
                Initialisieren
              </>
            )}
          </button>
          <button
            disabled={initStatus === 'running' || selectedStates.length === 0}
            onClick={() => {
              if (!confirm('Alle bestehenden Gefaehrdungen und Massnahmen loeschen und neu erstellen?')) return
              handleInitialize(true)
            }}
            className="flex items-center gap-2 px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 text-xs font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            Neu initialisieren
          </button>
        </div>

        {initResult && (
          <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 space-y-3">
            <h3 className="text-sm font-semibold text-green-800 dark:text-green-300">Initialisierung abgeschlossen</h3>
            <div className="space-y-1">
              {initResult.steps.map((s, i) => (
                <div key={i} className="flex items-center gap-2 text-xs">
                  <span className={s.status === 'done' ? 'text-green-600' : s.status === 'skipped' ? 'text-gray-400' : 'text-red-500'}>
                    {s.status === 'done' ? '\u2713' : s.status === 'skipped' ? '\u25CB' : '\u2717'}
                  </span>
                  <span className="text-gray-700 dark:text-gray-300">{s.name}</span>
                  {s.count > 0 && <span className="text-gray-400">({s.count})</span>}
                  {s.details && <span className="text-gray-400 text-[10px]">— {s.details}</span>}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Footer Actions */}
      <div className="flex items-center justify-between pt-4 border-t border-gray-200 dark:border-gray-700">
        <button
          onClick={() => router.push(`/sdk/iace/${projectId}/interview`)}
          className="px-4 py-2 text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
        >
          Zurueck zu Grenzen
        </button>
        <div className="flex items-center gap-3">
          <button
            onClick={() => saveSelection(selectedStates)}
            disabled={saving}
            className="flex items-center gap-2 px-5 py-2.5 bg-purple-600 text-white rounded-lg hover:bg-purple-700 text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {saving ? (
              <>
                <span className="animate-spin inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full" />
                Speichern...
              </>
            ) : (
              'Speichern'
            )}
          </button>
          <button
            onClick={() => {
              saveSelection(selectedStates)
              router.push(`/sdk/iace/${projectId}/components`)
            }}
            className="flex items-center gap-2 px-5 py-2.5 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm font-medium transition-colors"
          >
            Weiter zu Komponenten
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  )
}

// ── Sub-components ─────────────────────────────────────────

function StateCard({
  state,
  selected,
  onToggle,
}: {
  state: OperationalStateInfo
  selected: boolean
  onToggle: () => void
}) {
  const colors = STATE_COLORS[state.id] || STATE_COLORS.startup
  const description = STATE_DESCRIPTIONS[state.id] || ''
  const iconPath = STATE_ICONS[state.id] || STATE_ICONS.startup

  return (
    <button
      onClick={onToggle}
      className={`relative text-left p-4 rounded-xl border-2 transition-all ${
        selected
          ? `${colors.bg} ${colors.border} shadow-sm`
          : 'bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
      }`}
    >
      <div className="flex items-start gap-3">
        <div className={`w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0 ${
          selected ? colors.bg : 'bg-gray-100 dark:bg-gray-700'
        }`}>
          <svg
            className={`w-5 h-5 ${selected ? colors.text : 'text-gray-400'}`}
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d={iconPath} />
          </svg>
        </div>
        <div className="min-w-0 flex-1">
          <div className="flex items-center justify-between">
            <span className={`text-sm font-medium ${
              selected ? colors.text : 'text-gray-900 dark:text-white'
            }`}>
              {state.label_de}
            </span>
            <div className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${
              selected
                ? 'bg-purple-600 border-purple-600'
                : 'border-gray-300 dark:border-gray-600'
            }`}>
              {selected && (
                <svg className="w-3 h-3 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                </svg>
              )}
            </div>
          </div>
          <span className="text-[10px] text-gray-400 uppercase tracking-wider">{state.label_en}</span>
          {description && (
            <p className="mt-1 text-xs text-gray-500 dark:text-gray-400 leading-relaxed">{description}</p>
          )}
        </div>
      </div>
    </button>
  )
}

function DeltaStat({
  label,
  value,
  positive,
}: {
  label: string
  value: number
  positive: boolean
}) {
  const color = value === 0
    ? 'text-gray-400'
    : positive
      ? 'text-green-600 dark:text-green-400'
      : 'text-red-600 dark:text-red-400'
  return (
    <div className="text-center p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
      <div className={`text-xl font-bold ${color}`}>
        {value > 0 && positive ? '+' : ''}{value}
      </div>
      <div className="text-[10px] text-gray-500 mt-0.5">{label}</div>
    </div>
  )
}
