import { Fragment } from 'react';
import type { AccidentType } from '@/types/rescue/RescueType';
import { accidentTypes, rscTypeData, gmColor, listColor, trimColor, buoyColor } from '../RescueView';
import { MetricCard } from './MetricCard';

export function RescuePanel({ activeType }: { activeType: AccidentType }) {
  const d = rscTypeData[activeType];
  const at = accidentTypes.find((t) => t.id === activeType)!;

  return (
    <div className="flex flex-col p-2.5 gap-2">
      <div className="text-label-1 font-bold text-fg font-korean">구난 분석 (RESCUE ANALYSIS)</div>
      <div className="text-caption text-fg-sub font-korean px-2 py-1 rounded bg-bg-card border border-stroke">
        현재 사고유형: {at.label} ({at.eng})
      </div>

      {/* 선박 단면도 SVG */}
      <div className="bg-bg-card border border-stroke rounded-md p-2 relative">
        <div className="absolute top-1.5 right-2 text-caption text-fg-disabled font-mono">
          VESSEL STATUS
        </div>
        <svg viewBox="0 0 260 80" className="w-full" style={{ height: '65px' }}>
          <rect
            x="30"
            y="24"
            width="170"
            height="28"
            rx="4"
            fill="var(--bg-surface-hover)"
            stroke="var(--stroke-light)"
            strokeWidth=".8"
          />
          <rect
            x="85"
            y="15"
            width="55"
            height="10"
            rx="2"
            fill="var(--bg-surface-hover)"
            stroke="var(--stroke-light)"
            strokeWidth=".6"
          />
          <rect
            x="42"
            y="27"
            width="30"
            height="18"
            rx="1"
            fill="color-mix(in srgb, var(--color-danger) 12%, transparent)"
            stroke="color-mix(in srgb, var(--color-danger) 35%, transparent)"
            strokeWidth=".6"
          />
          <text
            x="57"
            y="39"
            fill="color-mix(in srgb, var(--color-danger) 50%, transparent)"
            fontSize="4.5"
            textAnchor="middle"
            fontFamily="var(--font-mono)"
          >
            FLOODED
          </text>
          <circle
            cx="42"
            cy="38"
            r="6"
            fill="none"
            stroke="var(--color-danger)"
            strokeWidth="1"
            strokeDasharray="2,1"
          />
          <text
            x="42"
            y="50"
            fill="var(--color-danger)"
            fontSize="4"
            textAnchor="middle"
            fontFamily="var(--font-mono)"
          >
            IMPACT
          </text>
          <line
            x1="30"
            y1="52"
            x2="200"
            y2="52"
            stroke="var(--stroke-default)"
            strokeWidth=".4"
            strokeDasharray="3,2"
          />
          <text
            x="205"
            y="55"
            fill="var(--fg-disabled)"
            fontSize="4.5"
            fontFamily="var(--font-mono)"
          >
            WL
          </text>
          <line
            x1="130"
            y1="8"
            x2="130"
            y2="60"
            stroke="color-mix(in srgb, var(--fg-disabled) 15%, transparent)"
            strokeWidth=".4"
            strokeDasharray="2,2"
          />
          <text x="230" y="20" fill="var(--fg-disabled)" fontSize="5">
            LIST: {d.list}°
          </text>
          <text x="230" y="28" fill="var(--fg-disabled)" fontSize="5">
            TRIM: {d.trim}m
          </text>
        </svg>
      </div>

      {/* 핵심 지표 2×2 */}
      <div className="grid grid-cols-2 gap-1.5">
        <MetricCard
          label="GM (메타센터 높이)"
          value={d.gm}
          unit="m"
          color={gmColor(d.gm)}
          sub={`${parseFloat(d.gm) < 1.0 ? '위험' : parseFloat(d.gm) < 1.5 ? '주의' : '정상'} (기준: 1.5m 이상)`}
        />
        <MetricCard
          label="LIST (횡경사)"
          value={d.list}
          unit="°"
          color={listColor(d.list)}
          sub={`${parseFloat(d.list) > 20 ? '위험' : parseFloat(d.list) > 10 ? '주의' : '정상'} (기준: 10° 이내)`}
        />
      </div>
      <div className="grid grid-cols-2 gap-1.5">
        <MetricCard
          label="TRIM (종경사)"
          value={d.trim}
          unit="m"
          color={trimColor(d.trim)}
          sub="선미 침하 (AFT SINKAGE)"
        />
        <div className="bg-bg-card border border-stroke rounded-md p-2">
          <div className="text-caption text-fg-disabled font-korean">
            잔존 부력 (Reserve Buoyancy)
          </div>
          <div className="text-title-2 font-bold font-mono" style={{ color: buoyColor(d.buoy) }}>
            {d.buoy}
            <span className="text-label-2">%</span>
          </div>
          <div className="h-[5px] bg-bg-surface-hover rounded-sm mt-0.5">
            <div
              className="h-full rounded-sm transition-all"
              style={{ width: `${d.buoy}%`, background: buoyColor(d.buoy) }}
            />
          </div>
        </div>
      </div>

      {/* 긴급 조치 버튼 */}
      <div className="text-label-2 font-bold text-fg-disabled font-korean">
        긴급 조치 (EMERGENCY ACTIONS)
      </div>
      <div className="grid grid-cols-2 gap-1.5">
        {[
          { en: 'BALLAST INJECT', ko: '밸러스트 주입' },
          { en: 'BALLAST DISCHARGE', ko: '밸러스트 배출' },
          { en: 'ENGINE STOP', ko: '기관 정지' },
          { en: 'ANCHOR DROP', ko: '묘 투하' },
        ].map((btn, i) => (
          <button
            key={i}
            className="py-[7px] rounded-[5px] text-center cursor-pointer transition-all hover:brightness-125 bg-bg-card border border-stroke"
          >
            <div className="text-label-2 font-bold text-fg-sub font-mono">{btn.en}</div>
            <div className="text-caption font-korean text-color-danger">{btn.ko}</div>
          </button>
        ))}
      </div>

      {/* 구난 의사결정 프로세스 */}
      <div className="bg-bg-card border border-stroke rounded-md p-2">
        <div className="text-caption font-bold text-fg-sub font-korean mb-1.5">
          구난 의사결정 프로세스 (KRISO Decision Support)
        </div>
        <div className="flex flex-col gap-0.5 text-caption font-korean">
          <div className="flex items-center gap-1">
            {['① 상태평가', '② 사례분석', '③ 장비선정'].map((label, i) => (
              <Fragment key={i}>
                {i > 0 && <span className="text-fg-disabled">→</span>}
                <div className="px-1.5 py-0.5 rounded-sm text-center flex-shrink-0 min-w-[68px] bg-bg-card border border-stroke text-fg-sub">
                  {label}
                </div>
              </Fragment>
            ))}
          </div>
          <div className="flex items-center gap-1">
            {['④ 예인력', '⑤ 이초/인양', '⑥ 유출량'].map((label, i) => (
              <Fragment key={i}>
                {i > 0 && <span className="text-fg-disabled">→</span>}
                <div className="px-1.5 py-0.5 rounded-sm text-center flex-shrink-0 min-w-[68px] bg-bg-card border border-stroke text-fg-sub">
                  {label}
                </div>
              </Fragment>
            ))}
          </div>
        </div>
      </div>

      {/* 유체 정역학 */}
      <div className="bg-bg-card border border-stroke rounded-md p-2">
        <div className="text-caption font-bold text-fg-sub font-korean mb-1.5">
          유체 정역학 (Hydrostatics)
        </div>
        <div className="grid grid-cols-2 gap-1 text-caption font-mono">
          {[
            { label: '배수량(Δ)', value: '12,450 ton' },
            { label: '흘수(Draft)', value: '7.2 m' },
            { label: 'KG', value: '8.5 m' },
            { label: 'KM (횡)', value: '9.3 m' },
            { label: 'TPC', value: '22.8 t/cm' },
            { label: 'MTC', value: '185 t·m' },
          ].map((r, i) => (
            <div key={i} className="px-1.5 py-1 bg-bg-card rounded-sm">
              <span className="text-fg-disabled font-korean text-caption">{r.label}</span>
              <br />
              <b className="text-fg-sub">{r.value}</b>
            </div>
          ))}
        </div>
      </div>

      {/* 예인력/이초력 */}
      <div className="bg-bg-card border border-stroke rounded-md p-2">
        <div className="text-caption font-bold text-fg-sub font-korean mb-1.5">
          예인력 / 이초력 (Towing & Refloating)
        </div>
        <div className="grid grid-cols-2 gap-1 text-caption font-mono">
          {[
            { label: '필요 예인력', value: '285 kN' },
            { label: '비상 예인력', value: '420 kN' },
            { label: '이초 반력', value: '1,850 kN' },
            { label: '인양 안전성', value: 'FAIL' },
          ].map((r, i) => (
            <div key={i} className="px-1.5 py-1 bg-bg-card rounded-sm">
              <span className="text-fg-disabled font-korean text-caption">{r.label}</span>
              <br />
              <b className="text-fg-sub">{r.value}</b>
            </div>
          ))}
        </div>
        <div className="text-caption text-fg-disabled font-korean mt-1">
          ※ IMO Salvage Manual / Resistance Increase Ratio 기반 산출
        </div>
      </div>

      {/* 유출량 추정 */}
      <div className="bg-bg-card border border-stroke rounded-md p-2">
        <div className="text-caption font-bold text-fg-sub font-korean mb-1.5">
          유출량 추정 (Oil Outflow Estimation)
        </div>
        <div className="grid grid-cols-3 gap-1 text-caption font-mono">
          {[
            { label: '현재 유출률', value: d.oilRate },
            { label: '누적 유출량', value: '6.8 kL' },
            { label: '24h 예측', value: '145 kL' },
          ].map((r, i) => (
            <div key={i} className="px-1.5 py-1 bg-bg-card rounded-sm text-center">
              <span className="text-fg-disabled font-korean text-caption">{r.label}</span>
              <br />
              <b className="text-fg-sub">{r.value}</b>
            </div>
          ))}
        </div>
        <div className="mt-1 h-1 bg-bg-surface-hover rounded-sm">
          <div
            className="h-full rounded-sm"
            style={{
              width: '68%',
              background: 'var(--color-danger)',
            }}
          />
        </div>
        <div className="text-caption text-fg-disabled font-korean mt-0.5">
          잔여 연료유: 210 kL | 탱크 잔량: 68% 유출
        </div>
      </div>

      {/* CBR 사례기반 추론 */}
      <div className="bg-bg-card border border-stroke rounded-md p-2">
        <div className="text-caption font-bold text-fg-sub font-korean mb-1.5">
          CBR 유사 사고 사례 (Case-Based Reasoning)
        </div>
        <div className="flex flex-col gap-0.5">
          {[
            { pct: '94%', name: 'Hebei Spirit (2007)', desc: '태안 · 충돌 · 원유 12,547kL 유출' },
            { pct: '87%', name: 'Sea Empress (1996)', desc: '밀포드 · 좌초 · 72,000t 유출' },
            { pct: '82%', name: 'Rena (2011)', desc: '타우랑가 · 좌초 · 350t HFO 유출' },
          ].map((c, i) => (
            <div
              key={i}
              className="flex items-center gap-1.5 px-1.5 py-1 rounded-sm cursor-pointer hover:brightness-125 bg-bg-card border border-stroke"
            >
              <div className="w-7 h-4 rounded-sm flex items-center justify-center text-caption font-bold font-mono text-fg-sub bg-bg-surface-hover">
                {c.pct}
              </div>
              <div className="flex-1 text-caption font-korean">
                <b className="text-fg-sub">{c.name}</b>
                <br />
                <span className="text-fg-disabled">{c.desc}</span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 위험도 평가 */}
      <div className="bg-bg-card border border-stroke rounded-md p-2">
        <div className="text-caption font-bold text-fg-sub font-korean mb-1.5">
          위험도 평가 — 2차사고 시나리오
        </div>
        <div className="flex flex-col gap-0.5 text-caption font-korean">
          {[
            { label: '침수 확대 → 전복', level: 'HIGH', danger: true },
            { label: '유류 대량 유출 → 해양오염', level: 'HIGH', danger: true },
            { label: '선체 절단 (BM 초과)', level: 'MED', danger: true },
            { label: '화재/폭발', level: 'LOW', danger: false },
          ].map((r, i) => (
            <div key={i} className="flex items-center justify-between px-1.5 py-0.5 rounded-sm">
              <span className="text-fg-sub">{r.label}</span>
              <span
                className={`px-1.5 py-px rounded-lg text-caption font-bold ${r.danger ? 'text-color-danger' : 'text-fg-disabled'}`}
              >
                {r.level}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* 해상 e-Call */}
      <div className="bg-bg-card border border-stroke rounded-md p-2">
        <div className="text-caption font-bold text-fg-sub font-korean mb-1.5">
          해상 e-Call (GMDSS / VHF-DSC)
        </div>
        <div className="flex flex-col gap-0.5 text-caption font-mono text-fg-disabled">
          {[
            { label: 'MMSI', value: '440123456', danger: false },
            { label: 'Nature of Distress', value: 'COLLISION', danger: true },
            { label: 'DSC Alert', value: 'SENT ✓', danger: false },
            { label: 'EPIRB', value: 'ACTIVATED ✓', danger: false },
            { label: 'VTS 인천', value: 'ACK 10:36', danger: false },
          ].map((r, i) => (
            <div key={i} className="flex justify-between">
              <span className="font-korean">{r.label}</span>
              <b className={r.danger ? 'text-color-danger' : 'text-fg-sub'}>{r.value}</b>
            </div>
          ))}
        </div>
        <button className="w-full mt-1 py-1 rounded text-caption font-bold cursor-pointer font-korean bg-bg-card border border-stroke text-fg-sub">
          📡 DISTRESS RELAY 전송
        </button>
      </div>
    </div>
  );
}
