'use client'

import React, { useState } from 'react'
import { IstAssessment } from './IstAssessment'

const PRODUCT_TYPES = [
  { value: 'iot', label: 'IoT / Connected Device' },
  { value: 'software', label: 'Software / Desktop App' },
  { value: 'saas', label: 'SaaS / Cloud-Plattform' },
  { value: 'hardware', label: 'Hardware / Elektronik' },
  { value: 'machinery', label: 'Maschine / Anlage' },
  { value: 'medical_device', label: 'Medizinprodukt' },
  { value: 'exchange', label: 'Krypto-Exchange / Fintech' },
  { value: 'other', label: 'Sonstiges' },
]

const TECHNOLOGIES = [
  { value: 'ai', label: 'Kuenstliche Intelligenz / ML' },
  { value: 'blockchain', label: 'Blockchain / Smart Contracts' },
  { value: 'cloud', label: 'Cloud-Infrastruktur' },
  { value: 'api', label: 'REST/GraphQL API' },
  { value: 'database', label: 'Datenbank' },
  { value: 'encryption', label: 'Verschluesselung' },
  { value: 'ota_updates', label: 'OTA Software-Updates' },
  { value: 'sensor', label: 'Sensoren' },
  { value: 'actuator', label: 'Aktoren / Motoren' },
  { value: 'network', label: 'Netzwerk-Anbindung' },
  { value: 'camera', label: 'Kamera / Bilderkennung' },
  { value: 'payment', label: 'Zahlungsabwicklung' },
  { value: 'fiat_gateway', label: 'Fiat On/Off-Ramp' },
]

const DATA_TYPES = [
  { value: 'personal_data', label: 'Personenbezogene Daten' },
  { value: 'health_data', label: 'Gesundheitsdaten' },
  { value: 'financial_data', label: 'Finanzdaten' },
  { value: 'telemetry', label: 'Telemetrie / Nutzungsdaten' },
]

const CERTIFICATIONS = [
  { value: 'ISO27001', label: 'ISO 27001' },
  { value: 'CE', label: 'CE-Kennzeichnung' },
  { value: 'SOC2', label: 'SOC 2' },
  { value: 'ISO13485', label: 'ISO 13485 (Medizin)' },
]

interface Props {
  onAnalyze: (profile: Record<string, unknown>) => void
  loading: boolean
}

export function ProductWizard({ onAnalyze, loading }: Props) {
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [productType, setProductType] = useState('')
  const [technologies, setTechnologies] = useState<string[]>([])
  const [dataProcessing, setDataProcessing] = useState<string[]>([])
  const [certifications, setCertifications] = useState<string[]>([])
  const [connectedToInternet, setConnectedToInternet] = useState(false)
  const [hasSoftwareUpdates, setHasSoftwareUpdates] = useState(false)
  const [usesAI, setUsesAI] = useState(false)
  const [processesPersonalData, setProcessesPersonalData] = useState(false)
  const [isCriticalInfra, setIsCriticalInfra] = useState(false)
  const [step, setStep] = useState(1)
  const [istData, setIstData] = useState({
    applied_norms: [] as string[],
    has_risk_assessment: false,
    has_technical_file: false,
    has_operating_manual: false,
    has_sbom: false,
    has_vuln_management: false,
    has_update_mechanism: false,
    has_incident_response: false,
    has_supply_chain_mgmt: false,
    ce_marking_since: '',
    product_age: '',
  })

  const toggleArrayValue = (
    arr: string[],
    setter: (v: string[]) => void,
    value: string
  ) => {
    setter(arr.includes(value) ? arr.filter(v => v !== value) : [...arr, value])
  }

  const handleSubmit = () => {
    onAnalyze({
      name: name || 'Unbenanntes Produkt',
      description,
      product_type: productType,
      technologies,
      data_processing: dataProcessing,
      markets: ['EU'],
      connected_to_internet: connectedToInternet,
      has_software_updates: hasSoftwareUpdates,
      uses_ai: usesAI,
      processes_personal_data: processesPersonalData,
      is_critical_infra_supplier: isCriticalInfra,
      existing_certifications: certifications,
      ...istData,
    })
  }

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-8">
      {/* Step Indicator */}
      <div className="flex items-center gap-4 mb-8">
        <button
          onClick={() => setStep(1)}
          className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium ${
            step === 1 ? 'bg-blue-100 text-blue-700' : 'text-gray-500 hover:bg-gray-50'
          }`}
        >
          <span className="w-6 h-6 rounded-full bg-blue-600 text-white text-xs flex items-center justify-center">1</span>
          Produkt beschreiben
        </button>
        <span className="text-gray-300">&rarr;</span>
        <button
          onClick={() => productType ? setStep(2) : null}
          className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium ${
            step === 2 ? 'bg-blue-100 text-blue-700' : 'text-gray-500 hover:bg-gray-50'
          } ${!productType ? 'opacity-50 cursor-not-allowed' : ''}`}
        >
          <span className={`w-6 h-6 rounded-full text-xs flex items-center justify-center ${
            step === 2 ? 'bg-blue-600 text-white' : 'bg-gray-300 text-white'
          }`}>2</span>
          IST-Zustand
        </button>
      </div>

      {step === 2 && (
        <>
          <IstAssessment data={istData} onChange={setIstData} />
          <div className="flex gap-4 mt-8">
            <button
              onClick={() => setStep(1)}
              className="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
            >
              Zurueck
            </button>
            <button
              onClick={handleSubmit}
              disabled={loading}
              className="flex-1 py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:bg-gray-300 transition-colors"
            >
              {loading ? 'Analyse laeuft...' : 'Gap-Analyse starten'}
            </button>
          </div>
        </>
      )}

      {step === 1 && (<>
      {/* Produktname */}
      <div className="mb-6">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Produktname
        </label>
        <input
          type="text"
          value={name}
          onChange={e => setName(e.target.value)}
          placeholder="z.B. SmartFactory Gateway Pro"
          className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
        />
      </div>

      {/* Beschreibung */}
      <div className="mb-6">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Produktbeschreibung
        </label>
        <textarea
          value={description}
          onChange={e => setDescription(e.target.value)}
          rows={3}
          placeholder="Beschreiben Sie Ihr Produkt in 2-3 Saetzen..."
          className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
        />
      </div>

      {/* Produkttyp */}
      <div className="mb-6">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Produkttyp
        </label>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {PRODUCT_TYPES.map(pt => (
            <button
              key={pt.value}
              onClick={() => setProductType(pt.value)}
              className={`px-4 py-3 rounded-lg border text-sm font-medium transition-colors ${
                productType === pt.value
                  ? 'bg-blue-50 border-blue-500 text-blue-700'
                  : 'border-gray-200 text-gray-700 hover:bg-gray-50'
              }`}
            >
              {pt.label}
            </button>
          ))}
        </div>
      </div>

      {/* Technologien */}
      <div className="mb-6">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Verwendete Technologien
        </label>
        <div className="flex flex-wrap gap-2">
          {TECHNOLOGIES.map(t => (
            <button
              key={t.value}
              onClick={() => toggleArrayValue(technologies, setTechnologies, t.value)}
              className={`px-3 py-1.5 rounded-full text-sm border transition-colors ${
                technologies.includes(t.value)
                  ? 'bg-blue-100 border-blue-400 text-blue-800'
                  : 'border-gray-200 text-gray-600 hover:bg-gray-50'
              }`}
            >
              {t.label}
            </button>
          ))}
        </div>
      </div>

      {/* Datenverarbeitung */}
      <div className="mb-6">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Verarbeitete Daten
        </label>
        <div className="flex flex-wrap gap-2">
          {DATA_TYPES.map(d => (
            <button
              key={d.value}
              onClick={() => toggleArrayValue(dataProcessing, setDataProcessing, d.value)}
              className={`px-3 py-1.5 rounded-full text-sm border transition-colors ${
                dataProcessing.includes(d.value)
                  ? 'bg-green-100 border-green-400 text-green-800'
                  : 'border-gray-200 text-gray-600 hover:bg-gray-50'
              }`}
            >
              {d.label}
            </button>
          ))}
        </div>
      </div>

      {/* Checkboxen */}
      <div className="mb-6 grid grid-cols-1 md:grid-cols-2 gap-4">
        {[
          { label: 'Mit dem Internet verbunden', value: connectedToInternet, setter: setConnectedToInternet },
          { label: 'Hat Software-Updates (OTA)', value: hasSoftwareUpdates, setter: setHasSoftwareUpdates },
          { label: 'Verwendet KI / Machine Learning', value: usesAI, setter: setUsesAI },
          { label: 'Verarbeitet personenbezogene Daten', value: processesPersonalData, setter: setProcessesPersonalData },
          { label: 'Zulieferer fuer kritische Infrastruktur', value: isCriticalInfra, setter: setIsCriticalInfra },
        ].map(cb => (
          <label key={cb.label} className="flex items-center gap-3 cursor-pointer">
            <input
              type="checkbox"
              checked={cb.value}
              onChange={e => cb.setter(e.target.checked)}
              className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
            <span className="text-sm text-gray-700">{cb.label}</span>
          </label>
        ))}
      </div>

      {/* Bestehende Zertifizierungen */}
      <div className="mb-8">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Bestehende Zertifizierungen (optional)
        </label>
        <div className="flex flex-wrap gap-2">
          {CERTIFICATIONS.map(cert => (
            <button
              key={cert.value}
              onClick={() => toggleArrayValue(certifications, setCertifications, cert.value)}
              className={`px-3 py-1.5 rounded-full text-sm border transition-colors ${
                certifications.includes(cert.value)
                  ? 'bg-purple-100 border-purple-400 text-purple-800'
                  : 'border-gray-200 text-gray-600 hover:bg-gray-50'
              }`}
            >
              {cert.label}
            </button>
          ))}
        </div>
      </div>

      {/* Next Step */}
      <button
        onClick={() => setStep(2)}
        disabled={!productType}
        className="w-full py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
      >
        Weiter: IST-Zustand erfassen &rarr;
      </button>
      </>)}
    </div>
  )
}
