'use client'

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

interface CustomHazardModalProps {
  onSubmit: (data: HazardFormData) => void
  onClose: () => void
  roles: RoleInfo[]
}

const INITIAL_FORM: HazardFormData = {
  name: '', description: '', category: 'mechanical', component_id: '',
  severity: 3, exposure: 3, probability: 3, avoidance: 3,
  lifecycle_phase: '', trigger_event: '', affected_person: '',
  possible_harm: '', hazardous_zone: '', machine_module: '',
}

export function CustomHazardModal({ onSubmit, onClose, roles }: CustomHazardModalProps) {
  const [form, setForm] = useState<HazardFormData>(INITIAL_FORM)
  const [submitting, setSubmitting] = useState(false)

  const rInherent = form.severity * form.exposure * form.probability * form.avoidance
  const riskLevel = getRiskLevelISO(rInherent)

  function set<K extends keyof HazardFormData>(key: K, val: HazardFormData[K]) {
    setForm(prev => ({ ...prev, [key]: val }))
  }

  async function handleSave() {
    if (!form.name.trim()) return
    setSubmitting(true)
    try {
      await onSubmit(form)
    } finally {
      setSubmitting(false)
    }
  }

  const inputCls = 'w-full px-3 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 text-sm'
  const labelCls = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto mx-4">
        <div className="sticky top-0 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-6 py-4 flex items-center justify-between rounded-t-xl z-10">
          <div>
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white">Eigene Gefaehrdung erstellen</h2>
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
              Maschinenspezifische Gefaehrdung definieren, die nicht in der Bibliothek enthalten ist.
            </p>
          </div>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div className="px-6 py-5 space-y-5">
          {/* Name + Category */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className={labelCls}>Bezeichnung (DE) *</label>
              <input type="text" value={form.name} onChange={e => set('name', e.target.value)}
                placeholder="z.B. Quetschung durch Sondergreifer" className={inputCls} />
            </div>
            <div>
              <label className={labelCls}>Kategorie *</label>
              <select value={form.category} onChange={e => set('category', e.target.value)} className={inputCls}>
                {HAZARD_CATEGORIES.map(cat => (
                  <option key={cat} value={cat}>{CATEGORY_LABELS[cat] || cat}</option>
                ))}
              </select>
            </div>
          </div>

          {/* Scenario */}
          <div>
            <label className={labelCls}>Gefahrensituation / Beschreibung</label>
            <textarea value={form.description} onChange={e => set('description', e.target.value)}
              rows={2} placeholder="Beschreibung der Gefahrensituation..."
              className={inputCls} />
          </div>

          {/* Trigger + Harm */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className={labelCls}>Ausloeseereignis</label>
              <input type="text" value={form.trigger_event} onChange={e => set('trigger_event', e.target.value)}
                placeholder="z.B. Schutztuer offen bei Betrieb" className={inputCls} />
            </div>
            <div>
              <label className={labelCls}>Moeglicher Schaden</label>
              <input type="text" value={form.possible_harm} onChange={e => set('possible_harm', e.target.value)}
                placeholder="z.B. Schwere Quetschverletzung" className={inputCls} />
            </div>
          </div>

          {/* Affected + Zone */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className={labelCls}>Betroffene Personen</label>
              {roles.length > 0 ? (
                <select value={form.affected_person} onChange={e => set('affected_person', e.target.value)} className={inputCls}>
                  <option value="">-- Bitte waehlen --</option>
                  {roles.map(r => <option key={r.id} value={r.id}>{r.label_de}</option>)}
                </select>
              ) : (
                <input type="text" value={form.affected_person} onChange={e => set('affected_person', e.target.value)}
                  placeholder="z.B. Bediener, Wartungspersonal" className={inputCls} />
              )}
            </div>
            <div>
              <label className={labelCls}>Gefahrenzone</label>
              <input type="text" value={form.hazardous_zone} onChange={e => set('hazardous_zone', e.target.value)}
                placeholder="z.B. Greifer-Arbeitsbereich" className={inputCls} />
            </div>
          </div>

          {/* Machine module */}
          <div>
            <label className={labelCls}>Maschinenmodul</label>
            <input type="text" value={form.machine_module} onChange={e => set('machine_module', e.target.value)}
              placeholder="z.B. Sondergreifer Typ X" className={inputCls} />
          </div>

          {/* Risk sliders */}
          <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">
              Standard-Risikobewertung (R = S x F x P x A)
            </h4>
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
              {([
                { label: 'Schwere (S)', key: 'severity' as const, low: 'Gering', high: 'Toedlich' },
                { label: 'Haeufigkeit (F)', key: 'exposure' as const, low: 'Selten', high: 'Staendig' },
                { label: 'Wahrscheinl. (P)', key: 'probability' as const, low: 'Unwahrsch.', high: 'Sehr wahrsch.' },
                { label: 'Vermeidbarkeit (A)', key: 'avoidance' as const, low: 'Leicht', high: 'Unmoeglich' },
              ]).map(({ label, key, low, high }) => (
                <div key={key}>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">
                    {label}: <span className="font-bold">{form[key]}</span>
                  </label>
                  <input type="range" min={1} max={5} value={form[key]}
                    onChange={e => set(key, Number(e.target.value))}
                    className="w-full accent-purple-600" />
                  <div className="flex justify-between text-[10px] text-gray-400">
                    <span>{low}</span><span>{high}</span>
                  </div>
                </div>
              ))}
            </div>
            <div className={`mt-3 p-2 rounded-lg border ${getRiskColor(riskLevel)}`}>
              <div className="flex items-center justify-between">
                <span className="text-xs font-medium">R = {form.severity} x {form.exposure} x {form.probability} x {form.avoidance}</span>
                <div className="flex items-center gap-2">
                  <span className="text-sm font-bold">{rInherent}</span>
                  <RiskBadge level={riskLevel} />
                </div>
              </div>
            </div>
          </div>

          {/* Tags hint */}
          <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
            <p className="text-xs text-blue-700 dark:text-blue-300">
              Die Gefaehrdung wird direkt in das Projekt-Hazard-Log aufgenommen.
              Sie koennen die Risikobewertung anschliessend in der Risikomatrix anpassen.
            </p>
          </div>
        </div>

        {/* Footer */}
        <div className="sticky bottom-0 bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 px-6 py-4 flex items-center justify-end gap-3 rounded-b-xl">
          <button onClick={onClose}
            className="px-4 py-2 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors">
            Abbrechen
          </button>
          <button onClick={handleSave} disabled={!form.name.trim() || submitting}
            className={`px-5 py-2 text-sm font-medium rounded-lg transition-colors ${
              form.name.trim() && !submitting
                ? 'bg-purple-600 text-white hover:bg-purple-700'
                : 'bg-gray-200 text-gray-400 cursor-not-allowed dark:bg-gray-700 dark:text-gray-500'
            }`}>
            {submitting ? 'Wird erstellt...' : 'Gefaehrdung erstellen'}
          </button>
        </div>
      </div>
    </div>
  )
}
