import { useState, useEffect, useRef } from 'react';
import { MATERIALS } from '../HNSScenarioView';

export function NewScenarioModal({
  isOpen,
  onClose,
  onSubmit,
}: {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (name: string) => void;
}) {
  const backdropRef = useRef<HTMLDivElement>(null);
  const [name, setName] = useState('');
  const [material, setMaterial] = useState('toluene');
  const [releaseType, setReleaseType] = useState('instant');
  const [amount, setAmount] = useState('2.5');
  const [unit, setUnit] = useState('t');
  const [timeStep, setTimeStep] = useState('T+0h');
  const [windDir, setWindDir] = useState('SW');
  const [windSpeed, setWindSpeed] = useState('5.2');
  const [temp, setTemp] = useState('18.5');
  const [stability, setStability] = useState('D');
  const [model, setModel] = useState('ALOHA');
  const [predTime, setPredTime] = useState('6');

  const mat = MATERIALS.find((m) => m.key === material) || MATERIALS[0];

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (e.target === backdropRef.current) onClose();
    };
    if (isOpen) document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [isOpen, onClose]);

  useEffect(() => {
    if (isOpen) setName(''); // eslint-disable-line react-hooks/set-state-in-effect -- 모달 열릴 때 이름 초기화
  }, [isOpen]);

  if (!isOpen) return null;

  const handleSubmit = () => {
    if (!name.trim()) return;
    onSubmit(name.trim());
  };

  return (
    <div
      ref={backdropRef}
      className="fixed inset-0 z-[9999] flex items-center justify-center"
      style={{ background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(4px)' }}
    >
      <div
        className="flex flex-col overflow-hidden rounded-[14px] bg-bg-surface border border-stroke w-[520px] max-h-[calc(100vh-80px)]"
        style={{ boxShadow: '0 20px 60px rgba(0,0,0,0.5)' }}
      >
        {/* Header */}
        <div className="flex items-center gap-3 border-b border-stroke px-5 py-4">
          <div className="flex items-center justify-center text-base w-9 h-9 rounded-[10px] bg-bg-elevated border border-stroke">
            🧪
          </div>
          <div className="flex-1">
            <h2 className="text-title-2 font-bold m-0">신규 HNS 대기확산 시나리오</h2>
            <div className="text-label-2 text-fg-disabled mt-0.5">
              물질·기상·유출조건을 설정하여 새 시나리오를 생성합니다
            </div>
          </div>
          <button
            onClick={onClose}
            className="flex items-center justify-center w-7 h-7 cursor-pointer text-fg-disabled text-label-1 rounded-sm border border-stroke bg-bg-card"
          >
            ✕
          </button>
        </div>

        {/* Scrollable content */}
        <div className="flex-1 overflow-y-auto flex flex-col gap-3.5 px-5 py-4">
          {/* 기본 정보 */}
          <ModalSection title="기본 정보">
            <ModalField label="시나리오명">
              <input
                className="prd-i"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="예: 풍향 변화 시나리오"
              />
            </ModalField>
            <div className="grid grid-cols-2 gap-2">
              <ModalField label="시간 단계">
                <select
                  className="prd-i"
                  value={timeStep}
                  onChange={(e) => setTimeStep(e.target.value)}
                >
                  {['T+0h', 'T+1h', 'T+3h', 'T+6h', 'T+12h', 'T+24h'].map((t) => (
                    <option key={t} value={t}>
                      {t}
                    </option>
                  ))}
                </select>
              </ModalField>
              <ModalField label="기준 시각">
                <input className="prd-i" type="text" defaultValue="2024-11-03 08:00" />
              </ModalField>
            </div>
          </ModalSection>

          {/* 물질·유출 조건 */}
          <ModalSection title="물질 · 유출 조건">
            <ModalField label="HNS 물질">
              <select
                className="prd-i"
                value={material}
                onChange={(e) => setMaterial(e.target.value)}
              >
                {MATERIALS.map((m) => (
                  <option key={m.key} value={m.key}>
                    {m.name} ({m.key})
                  </option>
                ))}
              </select>
            </ModalField>
            {/* Material properties card */}
            <div
              className="grid p-2 rounded-sm bg-bg-elevated border border-stroke"
              style={{
                gridTemplateColumns: 'repeat(5, 1fr)',
                gap: '4px',
              }}
            >
              {[
                { label: 'MW', value: mat.mw },
                { label: 'BP', value: mat.bp },
                { label: 'FP', value: mat.fp },
                { label: 'IDLH', value: mat.idlh },
                { label: 'ERPG-2', value: mat.erpg2 },
              ].map((p, i) => (
                <div key={i} className="text-center">
                  <div className="text-fg-disabled text-caption">{p.label}</div>
                  <div className="text-label-2 font-bold text-color-accent font-mono">
                    {p.value}
                  </div>
                </div>
              ))}
            </div>
            <div className="grid grid-cols-2 gap-2">
              <ModalField label="유출 유형">
                <select
                  className="prd-i"
                  value={releaseType}
                  onChange={(e) => setReleaseType(e.target.value)}
                >
                  <option value="instant">순간 유출</option>
                  <option value="continuous">연속 유출</option>
                  <option value="semi">반연속</option>
                </select>
              </ModalField>
              <ModalField label="유출량">
                <div className="flex gap-1">
                  <input
                    className="prd-i flex-1"
                    type="number"
                    value={amount}
                    onChange={(e) => setAmount(e.target.value)}
                  />
                  <select
                    className="prd-i w-[60px]"
                    value={unit}
                    onChange={(e) => setUnit(e.target.value)}
                  >
                    {['t', 'kg', 'm³', 'L'].map((u) => (
                      <option key={u} value={u}>
                        {u}
                      </option>
                    ))}
                  </select>
                </div>
              </ModalField>
            </div>
          </ModalSection>

          {/* 기상 조건 */}
          <ModalSection title="기상 조건">
            <div className="grid grid-cols-3 gap-2">
              <ModalField label="풍향">
                <select
                  className="prd-i"
                  value={windDir}
                  onChange={(e) => setWindDir(e.target.value)}
                >
                  {[
                    'N',
                    'NNE',
                    'NE',
                    'ENE',
                    'E',
                    'ESE',
                    'SE',
                    'SSE',
                    'S',
                    'SSW',
                    'SW',
                    'WSW',
                    'W',
                    'WNW',
                    'NW',
                    'NNW',
                  ].map((d) => (
                    <option key={d} value={d}>
                      {d}
                    </option>
                  ))}
                </select>
              </ModalField>
              <ModalField label="풍속 (m/s)">
                <input
                  className="prd-i"
                  type="number"
                  value={windSpeed}
                  onChange={(e) => setWindSpeed(e.target.value)}
                  step={0.1}
                />
              </ModalField>
              <ModalField label="기온 (°C)">
                <input
                  className="prd-i"
                  type="number"
                  value={temp}
                  onChange={(e) => setTemp(e.target.value)}
                  step={0.1}
                />
              </ModalField>
            </div>
            <div className="grid grid-cols-2 gap-2">
              <ModalField label="대기안정도 (Pasquill)">
                <select
                  className="prd-i"
                  value={stability}
                  onChange={(e) => setStability(e.target.value)}
                >
                  {[
                    'A (매우 불안정)',
                    'B (불안정)',
                    'C (약간 불안정)',
                    'D (중립)',
                    'E (약간 안정)',
                    'F (안정)',
                  ].map((s) => (
                    <option key={s[0]} value={s[0]}>
                      {s}
                    </option>
                  ))}
                </select>
              </ModalField>
              <ModalField label="확산 모델">
                <select className="prd-i" value={model} onChange={(e) => setModel(e.target.value)}>
                  {['ALOHA', 'PHAST', 'CALPUFF', 'Lagrangian'].map((m) => (
                    <option key={m} value={m}>
                      {m}
                    </option>
                  ))}
                </select>
              </ModalField>
            </div>
            <ModalField label="예측 시간">
              <select
                className="prd-i"
                value={predTime}
                onChange={(e) => setPredTime(e.target.value)}
              >
                {['1', '3', '6', '12', '24', '48'].map((h) => (
                  <option key={h} value={h}>
                    {h}시간
                  </option>
                ))}
              </select>
            </ModalField>
          </ModalSection>
        </div>

        {/* Footer */}
        <div className="flex gap-2 border-t border-stroke px-5 py-[14px]">
          <button
            onClick={onClose}
            className="flex-1 text-label-1 font-semibold cursor-pointer rounded-md text-fg-sub p-[10px] bg-bg-card border border-stroke"
          >
            취소
          </button>
          <button
            onClick={handleSubmit}
            className="cursor-pointer rounded-md text-label-1 font-bold text-static-white p-[10px] bg-color-navy hover:bg-color-navy-hover"
            style={{
              flex: 2,
              opacity: name.trim() ? 1 : 0.5,
            }}
          >
            🧪 시나리오 생성 및 예측 실행
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Helpers ─────────────────────────────────────────────
function ModalSection({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div>
      <div className="text-label-2 font-bold text-color-accent mb-2 pb-1 border-b border-stroke">
        {title}
      </div>
      <div className="flex flex-col gap-2">{children}</div>
    </div>
  );
}

function ModalField({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div>
      <div className="text-caption font-semibold text-fg-disabled mb-1">{label}</div>
      {children}
    </div>
  );
}
