'use client'

import { useState } from 'react'
import {
  HazardFormData, LifecyclePhase, RoleInfo,
  HAZARD_CATEGORIES, CATEGORY_LABELS, getRiskColor, getRiskLevelISO, getRiskLevelLegacy,
} from './types'
import { RiskBadge } from './RiskBadge'

export function HazardForm({
  onSubmit,
  onCancel,
  lifecyclePhases,
  roles,
}: {
  onSubmit: (data: HazardFormData) => void
  onCancel: () => void
  lifecyclePhases: LifecyclePhase[]
  roles: RoleInfo[]
}) {
  const [formData, setFormData] = useState<HazardFormData>({
    name: '', description: '', category: 'mechanical_hazard', component_id: '',
    severity: 3, exposure: 3, probability: 3, avoidance: 3,
    lifecycle_phase: '', trigger_event: '', affected_person: '',
    possible_harm: '', hazardous_zone: '', machine_module: '',
  })
  const [showExtended, setShowExtended] = useState(false)

  const isISOMode = formData.avoidance > 0
  const rInherent = isISOMode
    ? formData.severity * formData.exposure * formData.probability * formData.avoidance
    : formData.severity * formData.exposure * formData.probability
  const riskLevel = isISOMode ? getRiskLevelISO(rInherent) : getRiskLevelLegacy(rInherent)
  const formulaLabel = isISOMode ? 'R = S × F × P × A' : 'R = S × E × P'

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
      <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">Neue Gefaehrdung</h3>
      <div className="space-y-4">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Bezeichnung *</label>
            <input type="text" value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              placeholder="z.B. Quetschung durch Roboterarm"
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Kategorie</label>
            <select value={formData.category} onChange={(e) => setFormData({ ...formData, category: e.target.value })}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              {HAZARD_CATEGORIES.map((cat) => <option key={cat} value={cat}>{CATEGORY_LABELS[cat] || cat}</option>)}
            </select>
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Beschreibung</label>
          <textarea value={formData.description} onChange={(e) => setFormData({ ...formData, description: e.target.value })}
            rows={2} placeholder="Detaillierte Beschreibung der Gefaehrdung..."
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white" />
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Lebensphase</label>
            <select value={formData.lifecycle_phase} onChange={(e) => setFormData({ ...formData, lifecycle_phase: e.target.value })}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">-- Keine Auswahl --</option>
              {lifecyclePhases.map((p) => <option key={p.id} value={p.id}>{p.label_de}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Betroffene Personen</label>
            <select value={formData.affected_person} onChange={(e) => setFormData({ ...formData, affected_person: e.target.value })}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">-- Bitte waehlen --</option>
              {roles.map((r) => <option key={r.id} value={r.id}>{r.label_de}</option>)}
            </select>
          </div>
        </div>

        <button type="button" onClick={() => setShowExtended(!showExtended)}
          className="text-sm text-purple-600 hover:text-purple-700 font-medium">
          {showExtended ? 'Weniger Felder anzeigen' : 'Weitere Felder anzeigen (Ausloeser, Gefahrenzone, Modul...)'}
        </button>

        {showExtended && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-gray-50 dark:bg-gray-750 rounded-lg">
            {[
              { label: 'Ausloeseereignis', field: 'trigger_event' as const, placeholder: 'z.B. Schutztuer offen bei Betrieb' },
              { label: 'Moeglicher Schaden', field: 'possible_harm' as const, placeholder: 'z.B. Schwere Quetschverletzung' },
              { label: 'Gefahrenzone', field: 'hazardous_zone' as const, placeholder: 'z.B. Roboter-Arbeitsbereich' },
              { label: 'Maschinenmodul', field: 'machine_module' as const, placeholder: 'z.B. Antriebseinheit' },
            ].map(({ label, field, placeholder }) => (
              <div key={field}>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{label}</label>
                <input type="text" value={formData[field] as string}
                  onChange={(e) => setFormData({ ...formData, [field]: e.target.value })}
                  placeholder={placeholder}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white" />
              </div>
            ))}
          </div>
        )}

        <div className="bg-gray-50 dark:bg-gray-750 rounded-lg p-4">
          <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Risikobewertung ({formulaLabel})</h4>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            {[
              { label: 'Schwere (S)', field: 'severity' as const, low: 'Gering', high: 'Toedlich' },
              { label: 'Haeufigkeit (F)', field: 'exposure' as const, low: 'Selten', high: 'Staendig' },
              { label: 'Wahrscheinlichkeit (P)', field: 'probability' as const, low: 'Unwahrscheinlich', high: 'Sehr wahrscheinlich' },
              { label: 'Vermeidbarkeit (A)', field: 'avoidance' as const, low: 'Leicht', high: 'Unmoeglich' },
            ].map(({ label, field, low, high }) => (
              <div key={field}>
                <label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">
                  {label}: <span className="font-bold">{formData[field]}</span>
                </label>
                <input type="range" min={1} max={5} value={formData[field]}
                  onChange={(e) => setFormData({ ...formData, [field]: Number(e.target.value) })}
                  className="w-full accent-purple-600" />
                <div className="flex justify-between text-xs text-gray-400"><span>{low}</span><span>{high}</span></div>
              </div>
            ))}
          </div>
          <div className={`mt-4 p-3 rounded-lg border ${getRiskColor(riskLevel)}`}>
            <div className="flex items-center justify-between">
              <span className="text-sm font-medium">{formulaLabel}</span>
              <div className="flex items-center gap-2">
                <span className="text-lg font-bold">{rInherent}</span>
                <RiskBadge level={riskLevel} />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="mt-4 flex items-center gap-3">
        <button onClick={() => onSubmit(formData)} disabled={!formData.name}
          className={`px-6 py-2 rounded-lg font-medium transition-colors ${formData.name ? 'bg-purple-600 text-white hover:bg-purple-700' : 'bg-gray-200 text-gray-400 cursor-not-allowed'}`}>
          Hinzufuegen
        </button>
        <button onClick={onCancel} className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
          Abbrechen
        </button>
      </div>
    </div>
  )
}
