'use client'

import { useState } from 'react'
import { READINESS_PRESETS, ReadinessPreset } from './readiness-presets'
import { ReadinessResultView, ReadinessResult } from './ReadinessResult'

const PRODUCER_TYPES = [
  { v: 'component', label: 'Komponente / Zulieferteil', hint: 'z. B. Steuerung, Sensor (B2B)' },
  { v: 'end_device', label: 'Endgerät', hint: 'fertiges Produkt' },
  { v: 'machine_integrator', label: 'Anlage / Maschine', hint: 'Integrator — Vernetzung/OTA meist gegeben' },
  { v: 'software_app', label: 'Software / App / Cloud', hint: 'keine eigene Hardware' },
]
const QUESTIONS = [
  { k: 'is_machinery', label: 'Ist das Produkt eine Maschine oder Anlage?' },
  { k: 'connected_to_internet', label: 'Mit Netzwerk / Internet verbunden?' },
  { k: 'has_firmware', label: 'Enthält Software oder Firmware?' },
  { k: 'has_software_updates', label: 'Werden Updates bereitgestellt?' },
  { k: 'remote_maintenance', label: 'Gibt es Fernwartungszugänge?' },
  { k: 'user_parameter_app', label: 'App / Weboberfläche für Nutzer?' },
  { k: 'processes_personal_data', label: 'Werden personenbezogene Daten verarbeitet?' },
  { k: 'is_critical_infra_supplier', label: 'Einsatz in kritischen Umgebungen?' },
]
const EVIDENCE = [
  { k: 'sbom', label: 'SBOM' },
  { k: 'vdp', label: 'Vulnerability-Disclosure-Policy' },
  { k: 'patch_process', label: 'Patch-/Update-Prozess' },
  { k: 'support_lifecycle', label: 'Support-Lifecycle' },
  { k: 'threat_model', label: 'Threat Model' },
  { k: 'security_logging', label: 'Security-Logging' },
  { k: 'auth_concept', label: 'Auth-/Passwortkonzept' },
  { k: 'incident_process', label: 'Incident-/Meldeprozess' },
]
const HAZARDS = [
  { k: 'movement_crush', label: 'Bewegung / Quetschen' },
  { k: 'laser_radiation', label: 'Laser / Strahlung (Auge)' },
  { k: 'force_energy', label: 'Kraft / Energie' },
  { k: 'temperature', label: 'Temperatur / Hitze' },
  { k: 'electrical', label: 'Elektrisch' },
]

export function ReadinessCheck({ onCreateProject }: { onCreateProject?: () => void }) {
  const [intendedUse, setIntendedUse] = useState('')
  const [producerType, setProducerType] = useState('')
  const [flags, setFlags] = useState<Record<string, boolean>>({})
  const [after2027, setAfter2027] = useState(true)
  const [customersAsk, setCustomersAsk] = useState(false)
  const [safetyRelevant, setSafetyRelevant] = useState(false)
  const [hazards, setHazards] = useState<Record<string, boolean>>({})
  const [evidence, setEvidence] = useState<Record<string, boolean>>({})
  const [digitalElements, setDigitalElements] = useState<string[]>([])
  const [result, setResult] = useState<ReadinessResult | null>(null)
  const [loading, setLoading] = useState(false)

  const toggle = (k: string) => setFlags((f) => ({ ...f, [k]: !f[k] }))
  const toggleEv = (k: string) => setEvidence((e) => ({ ...e, [k]: !e[k] }))
  const toggleHz = (k: string) => setHazards((h) => ({ ...h, [k]: !h[k] }))

  const applyPreset = (p: ReadinessPreset) => {
    setIntendedUse(p.intended_use)
    setProducerType(p.producer_type)
    setFlags({ ...p.flags })
    setAfter2027(p.placed_on_market_after_2027)
    setCustomersAsk(p.customers_request_cra_evidence)
    setSafetyRelevant(p.safety_relevant)
    setHazards(Object.fromEntries(p.hazard_types.map((k) => [k, true])))
    setEvidence(Object.fromEntries(p.provided_evidence.map((k) => [k, true])))
    setDigitalElements(p.digital_elements)
    setResult(null)
  }

  const run = async () => {
    setLoading(true)
    try {
      const res = await fetch('/api/v1/cra/readiness', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          intended_use: intendedUse,
          producer_type: producerType,
          placed_on_market_after_2027: after2027,
          customers_request_cra_evidence: customersAsk,
          provided_evidence: Object.keys(evidence).filter((k) => evidence[k]),
          digital_elements: digitalElements,
          safety_relevant: safetyRelevant,
          hazard_types: Object.keys(hazards).filter((k) => hazards[k]),
          ...flags,
        }),
      })
      setResult(res.ok ? await res.json() : null)
    } finally { setLoading(false) }
  }

  return (
    <div className="rounded-xl border border-purple-200 dark:border-purple-800 bg-purple-50/50 dark:bg-purple-900/20 p-5 mb-6">
      <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">CRA-Readiness-Check</h2>
      <p className="text-sm text-gray-600 dark:text-gray-300 mt-1">
        Neutrale Erst-Einschätzung: Fällt Ihr Produkt unter den CRA (Pflicht ab 11.12.2027) oder die
        Maschinenverordnung — und welche Nachweise fehlen noch? Maßgeblich ist das <span className="font-medium">Inverkehrbringen</span>,
        nicht der Entwicklungszeitpunkt. Auch Bestandsprodukte, die nach 2027 noch verkauft werden, sind betroffen.
      </p>

      {/* Demo-Presets */}
      <div className="flex flex-wrap items-center gap-2 mt-3">
        <span className="text-xs text-gray-500">Beispiel laden:</span>
        {READINESS_PRESETS.map((p) => (
          <button key={p.id} onClick={() => applyPreset(p)} title={p.sublabel}
            className="rounded border border-purple-300 dark:border-purple-700 bg-white dark:bg-gray-800 text-purple-700 dark:text-purple-300 text-xs px-2 py-1 hover:bg-purple-100">
            {p.label}
          </button>
        ))}
      </div>

      {/* Hersteller-Typ */}
      <p className="text-xs font-medium text-gray-600 dark:text-gray-300 mt-4 mb-1">Was bringen Sie in Verkehr?</p>
      <div className="grid sm:grid-cols-4 gap-2">
        {PRODUCER_TYPES.map((t) => (
          <button key={t.v} onClick={() => setProducerType(t.v)}
            className={`rounded border p-2 text-left text-xs ${
              producerType === t.v
                ? 'border-purple-500 bg-purple-100 dark:bg-purple-900/40'
                : 'border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 hover:border-purple-300'}`}>
            <span className="font-medium text-gray-800 dark:text-gray-200">{t.label}</span>
            <span className="block text-[10px] text-gray-400">{t.hint}</span>
          </button>
        ))}
      </div>

      <textarea
        value={intendedUse} onChange={(e) => setIntendedUse(e.target.value)}
        placeholder="Was tut das Produkt? (Schnittstellen, Software, Vernetzung …)"
        className="w-full text-sm rounded border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700 p-2 mt-3 mb-3" rows={2}
      />

      <div className="grid sm:grid-cols-2 gap-2 mb-3">
        {QUESTIONS.map((q) => (
          <label key={q.k} className="flex items-center gap-2 text-xs text-gray-700 dark:text-gray-300">
            <input type="checkbox" checked={!!flags[q.k]} onChange={() => toggle(q.k)} className="rounded" />
            {q.label}
          </label>
        ))}
      </div>

      {/* Verdict-relevante Fragen */}
      <div className="grid sm:grid-cols-2 gap-2 mb-3">
        <label className="flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-300">
          <input type="checkbox" checked={after2027} onChange={() => setAfter2027((b) => !b)} className="rounded" />
          Wird ab dem 11.12.2027 (noch) verkauft / in Verkehr gebracht?
        </label>
        <label className="flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-300">
          <input type="checkbox" checked={customersAsk} onChange={() => setCustomersAsk((b) => !b)} className="rounded" />
          Fragen Kunden bereits CRA-Nachweise an?
        </label>
      </div>

      {/* Personengefährdung → MaschinenVO-Bezug + Cyber-Safety-Brücke */}
      <label className="flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
        <input type="checkbox" checked={safetyRelevant} onChange={() => setSafetyRelevant((b) => !b)} className="rounded" />
        Kann die Funktion bei Fehler oder Manipulation Personen gefährden?
      </label>
      {safetyRelevant && (
        <div className="flex flex-wrap gap-1.5 mb-3 ml-5">
          {HAZARDS.map((h) => (
            <button key={h.k} type="button" onClick={() => toggleHz(h.k)}
              className={`rounded px-2 py-0.5 text-[11px] border ${
                hazards[h.k]
                  ? 'border-amber-400 bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-200'
                  : 'border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:border-amber-300'}`}>
              {h.label}
            </button>
          ))}
        </div>
      )}

      {/* Vorhandene Nachweise → Reifegrad */}
      <p className="text-xs text-gray-500 mb-1">Welche Nachweise haben Sie bereits?</p>
      <div className="grid sm:grid-cols-4 gap-1.5 mb-4">
        {EVIDENCE.map((e) => (
          <label key={e.k} className="flex items-center gap-1.5 text-[11px] text-gray-700 dark:text-gray-300">
            <input type="checkbox" checked={!!evidence[e.k]} onChange={() => toggleEv(e.k)} className="rounded" />
            {e.label}
          </label>
        ))}
      </div>

      <button onClick={run} disabled={loading}
        className="rounded bg-purple-600 hover:bg-purple-700 disabled:opacity-50 text-white text-sm px-4 py-2">
        {loading ? 'Prüfe …' : 'CRA-Readiness prüfen'}
      </button>

      {result && <ReadinessResultView result={result} onCreateProject={onCreateProject} />}
    </div>
  )
}
