import { useRef, useState } from 'react';
import type { RescueOpsItem } from '@interfaces/rescue/RescueInterface';

export function NewScenarioModal({
  ops,
  onClose,
}: {
  ops: RescueOpsItem[];
  onClose: () => void;
}) {
  const overlayRef = useRef<HTMLDivElement>(null);
  const [submitting, setSubmitting] = useState(false);
  const [done, setDone] = useState(false);

  const handleSubmit = () => {
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      setDone(true);
    }, 2000);
  };

  /* ── shared className helpers ── */
  const labelCls = 'text-caption text-fg-disabled block mb-1';
  const inputCls =
    'w-full px-3 py-2 rounded-md border border-stroke bg-bg-base text-label-2 outline-none';
  const numCls = `${inputCls} font-mono`;
  const sectionIcon = (n: number) => (
    <div
      className="w-[18px] h-[18px] rounded-[5px] flex items-center justify-center text-caption font-bold text-color-accent"
      style={{ background: 'rgba(6,182,212,.12)' }}
    >
      {n}
    </div>
  );
  const sectionTitleCls = 'text-label-2 font-bold mb-2.5 flex items-center gap-1.5';

  return (
    <div
      ref={overlayRef}
      onClick={(e) => {
        if (e.target === overlayRef.current) onClose();
      }}
      className="fixed inset-0 z-[9999] flex items-center justify-center"
      style={{ background: 'rgba(0,0,0,.65)', backdropFilter: 'blur(6px)' }}
    >
      <div
        className="bg-bg-surface border border-stroke rounded-[14px] w-[700px] max-h-[88vh] flex flex-col overflow-hidden"
        style={{ boxShadow: '0 24px 80px rgba(0,0,0,.6)' }}
      >
        {/* ── 헤더 ── */}
        <div className="px-6 pt-5 pb-4 border-b border-stroke shrink-0">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2.5">
              <span className="text-lg">🚨</span>
              <div>
                <div className="text-title-4 font-bold">신규 긴급구난 시나리오 생성</div>
                <div className="text-label-2 text-fg-disabled mt-0.5">
                  선박 사고 조건 및 구난 분석 파라미터를 설정합니다 (SFR-009)
                </div>
              </div>
            </div>
            <span onClick={onClose} className="text-lg cursor-pointer text-fg-disabled p-1">
              ✕
            </span>
          </div>
        </div>

        {/* ── 본문 스크롤 ── */}
        <div className="flex-1 overflow-y-auto px-6 py-5 flex flex-col gap-[18px] scrollbar-thin">
          {/* ① 기본 정보 */}
          <div>
            <div className={sectionTitleCls}>{sectionIcon(1)} 기본 정보</div>
            <div className="grid grid-cols-2 gap-2.5">
              <div>
                <label className={labelCls}>
                  시나리오명 <span className="text-color-danger">*</span>
                </label>
                <input type="text" placeholder="예: T+3h 기관실 침수 확대" className={inputCls} />
              </div>
              <div>
                <label className={labelCls}>
                  연계 사고 <span className="text-color-danger">*</span>
                </label>
                <select defaultValue="0" className={inputCls}>
                  {ops.map((op, i) => (
                    <option key={op.rescueOpsSn} value={i}>
                      {op.opsCd} · {op.vesselNm}
                    </option>
                  ))}
                  <option value="new">+ 신규 사고 등록...</option>
                </select>
              </div>
              <div>
                <label className={labelCls}>
                  시간 단계 (Time Step) <span className="text-color-danger">*</span>
                </label>
                <select defaultValue="T+3h" className={inputCls}>
                  {[
                    'T+0h (사고 발생 직후)',
                    'T+1h',
                    'T+2h',
                    'T+3h',
                    'T+6h',
                    'T+12h',
                    'T+24h',
                    'T+48h',
                  ].map((t) => (
                    <option key={t} value={t}>
                      {t}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className={labelCls}>기준 시각</label>
                <input type="datetime-local" defaultValue="2024-10-27T13:30" className={inputCls} />
              </div>
            </div>
          </div>

          {/* ② 선박 정보 */}
          <div>
            <div className={sectionTitleCls}>{sectionIcon(2)} 선박 정보</div>
            <div className="grid grid-cols-3 gap-2.5">
              <div>
                <label className={labelCls}>
                  선박명 <span className="text-color-danger">*</span>
                </label>
                <input type="text" defaultValue="M/V SEA GUARDIAN" className={inputCls} />
              </div>
              <div>
                <label className={labelCls}>
                  선종 <span className="text-color-danger">*</span>
                </label>
                <select defaultValue="화물선 (Cargo)" className={inputCls}>
                  {[
                    '유조선 (Tanker)',
                    '화물선 (Cargo)',
                    '컨테이너선 (Container)',
                    '여객선 (Passenger)',
                    '어선 (Fishing)',
                    'LNG선',
                    '케미컬선 (Chemical)',
                    '기타',
                  ].map((v) => (
                    <option key={v}>{v}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className={labelCls}>총톤수 (GT)</label>
                <input type="number" defaultValue={45000} step={100} min={0} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>선체 길이 (m)</label>
                <input type="number" defaultValue={189} step={1} min={0} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>흘수 (m)</label>
                <input type="number" defaultValue={8.5} step={0.1} min={0} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>승선 인원</label>
                <input type="number" defaultValue={22} step={1} min={0} className={numCls} />
              </div>
            </div>
            <div className="mt-2 grid grid-cols-2 gap-2.5">
              <div>
                <label className={labelCls}>적재 화물</label>
                <input type="text" placeholder="예: 일반화물, 벙커C 450kL" className={inputCls} />
              </div>
              <div>
                <label className={labelCls}>연료유 종류 · 탑재량</label>
                <input type="text" defaultValue="벙커C 450kL / MGO 80kL" className={inputCls} />
              </div>
            </div>
          </div>

          {/* ③ 사고 조건 · 선체 상태 */}
          <div>
            <div className={sectionTitleCls}>{sectionIcon(3)} 사고 조건 · 선체 상태</div>
            <div className="grid grid-cols-3 gap-2.5">
              <div>
                <label className={labelCls}>
                  사고 유형 <span className="text-color-danger">*</span>
                </label>
                <select defaultValue="충돌 (Collision)" className={inputCls}>
                  {[
                    '충돌 (Collision)',
                    '좌초 (Grounding)',
                    '침수 (Flooding)',
                    '기관고장 (Engine Failure)',
                    '화재 (Fire)',
                    '전복 (Capsizing)',
                    '구조손상 (Structural)',
                  ].map((v) => (
                    <option key={v}>{v}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className={labelCls}>손상 구역</label>
                <select defaultValue="우현 중앙 (Starboard Mid)" className={inputCls}>
                  {[
                    '선수부 (Bow)',
                    '우현 중앙 (Starboard Mid)',
                    '좌현 중앙 (Port Mid)',
                    '선미부 (Stern)',
                    '기관실 (Engine Room)',
                    '선저 (Bottom)',
                    '복수 구역',
                  ].map((v) => (
                    <option key={v}>{v}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className={labelCls}>파공 크기 (㎡)</label>
                <input type="number" defaultValue={2.8} step={0.1} min={0} className={numCls} />
              </div>
            </div>
            <div className="mt-2 grid grid-cols-4 gap-2.5">
              <div>
                <label className={labelCls}>횡경사 (°)</label>
                <input type="number" defaultValue={8.5} step={0.5} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>종경사 (°)</label>
                <input type="number" defaultValue={2.1} step={0.1} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>건현 (m)</label>
                <input type="number" defaultValue={3.2} step={0.1} min={0} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>GM (m)</label>
                <input type="number" defaultValue={1.8} step={0.1} className={numCls} />
              </div>
            </div>
            {/* 침수 상태 */}
            <div className="mt-2.5 px-3.5 py-2.5 rounded-md border border-stroke bg-bg-card">
              <div className="text-caption font-bold mb-2">💧 침수 상태</div>
              <div className="grid grid-cols-4 gap-2">
                <div>
                  <label className="text-caption text-fg-disabled block mb-px">침수 구역 수</label>
                  <select
                    defaultValue="2개"
                    className="w-full px-2 py-1.5 rounded border border-stroke bg-bg-base text-label-2 outline-none"
                  >
                    {['1개', '2개', '3개', '4개 이상'].map((v) => (
                      <option key={v}>{v}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="text-caption text-fg-disabled block mb-px">침수량 (톤)</label>
                  <input
                    type="number"
                    defaultValue={850}
                    step={50}
                    min={0}
                    className="w-full px-2 py-1.5 rounded border border-stroke bg-bg-base text-label-2 font-mono outline-none"
                  />
                </div>
                <div>
                  <label className="text-caption text-fg-disabled block mb-px">
                    침수 진행률 (t/h)
                  </label>
                  <input
                    type="number"
                    defaultValue={120}
                    step={10}
                    min={0}
                    className="w-full px-2 py-1.5 rounded border border-stroke bg-bg-base text-label-2 font-mono outline-none"
                  />
                </div>
                <div>
                  <label className="text-caption text-fg-disabled block mb-px">
                    배수 능력 (t/h)
                  </label>
                  <input
                    type="number"
                    defaultValue={80}
                    step={10}
                    min={0}
                    className="w-full px-2 py-1.5 rounded border border-stroke bg-bg-base text-label-2 font-mono outline-none"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* ④ 사고 위치 · 해상 조건 */}
          <div>
            <div className={sectionTitleCls}>{sectionIcon(4)} 사고 위치 · 해상 조건</div>
            <div className="grid gap-2.5 items-end" style={{ gridTemplateColumns: '1fr 1fr auto' }}>
              <div>
                <label className={labelCls}>위도 (Lat)</label>
                <input type="text" defaultValue="34.5832" className={`${inputCls} font-mono`} />
              </div>
              <div>
                <label className={labelCls}>경도 (Lon)</label>
                <input type="text" defaultValue="128.4217" className={`${inputCls} font-mono`} />
              </div>
              <button
                className="px-3.5 py-2 rounded-md border border-[rgba(6,182,212,.3)] text-color-accent text-label-2 font-semibold cursor-pointer whitespace-nowrap"
                style={{ background: 'rgba(6,182,212,.08)' }}
              >
                📍 지도에서 선택
              </button>
            </div>
            <div className="mt-2 grid grid-cols-4 gap-2.5">
              <div>
                <label className={labelCls}>
                  풍향 / 풍속 <span className="text-color-danger">*</span>
                </label>
                <div className="flex gap-1">
                  <select
                    defaultValue="SW"
                    className="flex-1 p-2 rounded-md border border-stroke bg-bg-base text-label-2 outline-none"
                  >
                    {['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'].map((d) => (
                      <option key={d}>{d}</option>
                    ))}
                  </select>
                  <input
                    type="number"
                    defaultValue={12.5}
                    step={0.5}
                    min={0}
                    className="w-[60px] p-2 rounded-md border border-stroke bg-bg-base text-label-2 font-mono outline-none text-center"
                  />
                </div>
              </div>
              <div>
                <label className={labelCls}>
                  파고 (m) <span className="text-color-danger">*</span>
                </label>
                <input type="number" defaultValue={2.5} step={0.1} min={0} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>조류 방향 / 유속</label>
                <div className="flex gap-1">
                  <select
                    defaultValue="NE"
                    className="flex-1 p-2 rounded-md border border-stroke bg-bg-base text-label-2 outline-none"
                  >
                    {['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'].map((d) => (
                      <option key={d}>{d}</option>
                    ))}
                  </select>
                  <input
                    type="number"
                    defaultValue={1.2}
                    step={0.1}
                    min={0}
                    className="w-[60px] p-2 rounded-md border border-stroke bg-bg-base text-label-2 font-mono outline-none text-center"
                  />
                </div>
              </div>
              <div>
                <label className={labelCls}>수심 (m)</label>
                <input type="number" defaultValue={25} step={1} min={0} className={numCls} />
              </div>
            </div>
            <div className="mt-1.5 grid grid-cols-3 gap-2.5">
              <div>
                <label className={labelCls}>시정 (km)</label>
                <input type="number" defaultValue={8} step={1} min={0} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>해상 상태 (Douglas)</label>
                <select defaultValue="3 — 거침 (Moderate)" className={inputCls}>
                  {[
                    '0 — 평온 (Calm)',
                    '1 — 잔잔 (Smooth)',
                    '2 — 약간 거침 (Slight)',
                    '3 — 거침 (Moderate)',
                    '4 — 다소 높음 (Rough)',
                    '5 — 높음 (Very rough)',
                    '6 — 매우 높음 (High)',
                  ].map((v) => (
                    <option key={v}>{v}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className={labelCls}>수온 (°C)</label>
                <input type="number" defaultValue={17.2} step={0.5} className={numCls} />
              </div>
            </div>
          </div>

          {/* ⑤ 구난 분석 설정 */}
          <div>
            <div className={sectionTitleCls}>{sectionIcon(5)} 구난 분석 설정</div>
            <div className="grid grid-cols-3 gap-2.5">
              <div>
                <label className={labelCls}>
                  분석 모델 <span className="text-color-danger">*</span>
                </label>
                <select defaultValue="R&D 긴급구난 종합분석" className={inputCls}>
                  {[
                    'R&D 긴급구난 종합분석',
                    'HECSALV (Salvage)',
                    'NAPA Emergency',
                    '수동 입력 (직접 판단)',
                  ].map((v) => (
                    <option key={v}>{v}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className={labelCls}>예측 시간</label>
                <select defaultValue="12시간" className={inputCls}>
                  {['6시간', '12시간', '24시간', '48시간', '72시간'].map((v) => (
                    <option key={v}>{v}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className={labelCls}>분석 항목</label>
                <div className="flex flex-wrap gap-1 mt-0.5">
                  {['복원성', '예인력', '인양력', '유출 위험'].map((item) => (
                    <label
                      key={item}
                      className="flex items-center gap-px text-caption text-fg-sub cursor-pointer"
                    >
                      <input
                        type="checkbox"
                        defaultChecked
                        style={{ accentColor: 'var(--color-accent)', transform: 'scale(.85)' }}
                      />
                      {item}
                    </label>
                  ))}
                </div>
              </div>
            </div>
            {/* R&D 연계 분석 */}
            <div className="mt-2.5 px-3.5 py-2.5 flex flex-col gap-1.5 rounded-md border border-stroke bg-bg-card">
              <div className="text-caption font-bold">🔗 R&D 연계 분석</div>
              <div className="flex gap-3">
                <label className="flex items-center gap-1 text-caption text-fg-sub cursor-pointer">
                  <input type="checkbox" style={{ accentColor: 'var(--color-accent)' }} /> 유출유
                  확산예측 동시 실행
                </label>
                <label className="flex items-center gap-1 text-caption text-fg-sub cursor-pointer">
                  <input type="checkbox" style={{ accentColor: 'var(--color-accent)' }} /> HNS
                  대기확산 연계 분석
                </label>
              </div>
              <div className="text-caption text-fg-disabled leading-[1.5]">
                화물 유출 가능성이 있는 경우, 긴급구난 분석 결과와 확산예측을 동시에 수행하여 종합
                대응 판단을 지원합니다
              </div>
            </div>
          </div>

          {/* ⑥ 비고 */}
          <div>
            <div className={sectionTitleCls}>{sectionIcon(6)} 비고</div>
            <textarea
              placeholder="시나리오 설명, 가정 조건, 현장 상황 특이사항 등을 기록합니다..."
              className="w-full h-[60px] px-3 py-2.5 rounded-md border border-stroke bg-bg-base text-label-2 outline-none resize-y leading-relaxed scrollbar-thin"
            />
          </div>
        </div>

        {/* ── 하단 버튼 ── */}
        <div className="px-6 py-4 border-t border-stroke shrink-0 flex gap-2 items-center">
          <div className="flex-1 text-caption text-fg-disabled leading-[1.5]">
            <span className="text-color-danger">*</span> 필수 입력 항목 · 해상 조건은 기상청/조사원
            API 연계 시 자동 갱신
          </div>
          <button
            onClick={onClose}
            className="px-5 py-2.5 rounded-md border border-stroke bg-bg-card text-fg-sub text-caption font-semibold cursor-pointer"
          >
            취소
          </button>
          {done ? (
            <button
              onClick={onClose}
              className="px-7 py-2.5 rounded-md border-none text-static-white text-caption font-bold cursor-pointer bg-color-success"
            >
              ✅ 생성 완료 — 닫기
            </button>
          ) : (
            <button
              onClick={handleSubmit}
              disabled={submitting}
              className={`px-7 py-2.5 rounded-md border-none text-caption font-bold ${
                submitting
                  ? 'bg-bg-card text-fg-disabled cursor-wait'
                  : 'bg-color-navy text-static-white cursor-pointer hover:bg-color-navy-hover'
              }`}
            >
              {submitting ? '⏳ 분석 중...' : '🚨 시나리오 생성 · 분석 실행'}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
