import type { ChartDataItem } from '@interfaces/rescue/RescueInterface';
import { SEV_COLOR, gmColor, listColor, buoyColor, oilColor } from '../RescueScenarioView';

export function ScenarioComparison({ chartData }: { chartData: ChartDataItem[] }) {
  const W = 480,
    H = 180,
    PX = 50,
    PY = 20;
  const pw = W - PX * 2,
    ph = H - PY * 2;
  const xStep = chartData.length > 1 ? pw / (chartData.length - 1) : pw;

  if (chartData.length === 0) {
    return (
      <div className="p-10 text-center text-label-2 text-fg-disabled">
        비교할 시나리오 데이터가 없습니다.
      </div>
    );
  }

  return (
    <div className="p-5">
      {/* Chart 1: GM 추이 */}
      <div className="bg-bg-card border border-stroke rounded-[10px] p-4 mb-4">
        <div className="text-label-2 font-bold mb-2.5">📈 GM (복원심) 변화 추이 (m)</div>
        <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ maxHeight: 180 }}>
          {/* Grid */}
          {[0, 0.5, 1.0, 1.5, 2.0].map((v) => {
            const y = PY + ph - (v / 2.0) * ph;
            return (
              <g key={v}>
                <line x1={PX} x2={W - PX} y1={y} y2={y} stroke="var(--stroke-light)" />
                <text
                  x={PX - 6}
                  y={y + 3}
                  textAnchor="end"
                  fill="var(--fg-disabled)"
                  fontSize={8}
                  fontFamily="var(--font-mono)"
                >
                  {v}
                </text>
              </g>
            );
          })}
          {/* GM=1.0 threshold */}
          <line
            x1={PX}
            x2={W - PX}
            y1={PY + ph - (1.0 / 2.0) * ph}
            y2={PY + ph - (1.0 / 2.0) * ph}
            stroke="rgba(239,68,68,.4)"
            strokeDasharray="4"
          />
          <text
            x={W - PX + 4}
            y={PY + ph - (1.0 / 2.0) * ph + 3}
            fill="var(--color-danger)"
            fontSize={7}
          >
            GM=1.0 위험
          </text>
          {/* Area */}
          <polygon
            points={`${PX},${PY + ph} ${chartData.map((d, i) => `${PX + i * xStep},${PY + ph - (d.gm / 2.0) * ph}`).join(' ')} ${PX + (chartData.length - 1) * xStep},${PY + ph}`}
            fill="rgba(6,182,212,.08)"
          />
          {/* Line + dots */}
          <polyline
            points={chartData
              .map((d, i) => `${PX + i * xStep},${PY + ph - (d.gm / 2.0) * ph}`)
              .join(' ')}
            fill="none"
            stroke="var(--color-accent)"
            strokeWidth={2}
          />
          {chartData.map((d, i) => (
            <g key={d.id}>
              <circle
                cx={PX + i * xStep}
                cy={PY + ph - (d.gm / 2.0) * ph}
                r={4}
                fill={SEV_COLOR[d.severity]}
                stroke="#0d1117"
                strokeWidth={1.5}
              />
              <text
                x={PX + i * xStep}
                y={PY + ph + 14}
                textAnchor="middle"
                fill="var(--fg-disabled)"
                fontSize={8}
                fontFamily="var(--font-korean)"
              >
                {d.label}
              </text>
              <text
                x={PX + i * xStep}
                y={PY + ph - (d.gm / 2.0) * ph - 8}
                textAnchor="middle"
                fill="var(--fg-default)"
                fontSize={8}
                fontFamily="var(--font-mono)"
                fontWeight={700}
              >
                {d.gm}
              </text>
            </g>
          ))}
        </svg>
      </div>

      {/* Charts 2 & 3: 2-column */}
      <div className="grid grid-cols-2 gap-4 mb-4">
        {/* Chart 2: 횡경사 변화 */}
        <div className="bg-bg-card border border-stroke rounded-[10px] p-4">
          <div className="text-label-2 font-bold mb-2.5">📉 횡경사 (List) 변화 (°)</div>
          <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ maxHeight: 160 }}>
            {[0, 5, 10, 15, 20, 25].map((v) => {
              const y = PY + ph - (v / 25) * ph;
              return (
                <g key={v}>
                  <line x1={PX} x2={W - PX} y1={y} y2={y} stroke="var(--stroke-light)" />
                  <text
                    x={PX - 6}
                    y={y + 3}
                    textAnchor="end"
                    fill="var(--fg-disabled)"
                    fontSize={7}
                    fontFamily="var(--font-mono)"
                  >
                    {v}
                  </text>
                </g>
              );
            })}
            <line
              x1={PX}
              x2={W - PX}
              y1={PY + ph - (15 / 25) * ph}
              y2={PY + ph - (15 / 25) * ph}
              stroke="rgba(239,68,68,.3)"
              strokeDasharray="4"
            />
            <polyline
              points={chartData
                .map((d, i) => `${PX + i * xStep},${PY + ph - (d.list / 25) * ph}`)
                .join(' ')}
              fill="none"
              stroke="var(--color-warning)"
              strokeWidth={2}
            />
            {chartData.map((d, i) => (
              <g key={d.id}>
                <circle
                  cx={PX + i * xStep}
                  cy={PY + ph - (d.list / 25) * ph}
                  r={3.5}
                  fill={SEV_COLOR[d.severity]}
                  stroke="#0d1117"
                  strokeWidth={1.5}
                />
                <text
                  x={PX + i * xStep}
                  y={PY + ph + 14}
                  textAnchor="middle"
                  fill="var(--fg-disabled)"
                  fontSize={7}
                  fontFamily="var(--font-korean)"
                >
                  {d.label}
                </text>
              </g>
            ))}
          </svg>
        </div>

        {/* Chart 3: 유출률 변화 (bar) */}
        <div className="bg-bg-card border border-stroke rounded-[10px] p-4">
          <div className="text-label-2 font-bold mb-2.5">📊 유출률 변화 (L/min)</div>
          <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ maxHeight: 160 }}>
            {[0, 50, 100, 150, 200].map((v) => {
              const y = PY + ph - (v / 200) * ph;
              return (
                <g key={v}>
                  <line x1={PX} x2={W - PX} y1={y} y2={y} stroke="var(--stroke-light)" />
                  <text
                    x={PX - 6}
                    y={y + 3}
                    textAnchor="end"
                    fill="var(--fg-disabled)"
                    fontSize={7}
                    fontFamily="var(--font-mono)"
                  >
                    {v}
                  </text>
                </g>
              );
            })}
            {chartData.map((d, i) => {
              const barW = xStep * 0.5;
              const barH = (d.oil / 200) * ph;
              return (
                <g key={d.id}>
                  <rect
                    x={PX + i * xStep - barW / 2}
                    y={PY + ph - barH}
                    width={barW}
                    height={barH}
                    rx={3}
                    fill={SEV_COLOR[d.severity]}
                    opacity={0.7}
                  />
                  <text
                    x={PX + i * xStep}
                    y={PY + ph - barH - 4}
                    textAnchor="middle"
                    fill="var(--fg-default)"
                    fontSize={8}
                    fontFamily="var(--font-mono)"
                    fontWeight={700}
                  >
                    {d.oil}
                  </text>
                  <text
                    x={PX + i * xStep}
                    y={PY + ph + 14}
                    textAnchor="middle"
                    fill="var(--fg-disabled)"
                    fontSize={7}
                    fontFamily="var(--font-korean)"
                  >
                    {d.label}
                  </text>
                </g>
              );
            })}
          </svg>
        </div>
      </div>

      {/* Chart 4: 비교 테이블 */}
      <div className="bg-bg-card border border-stroke rounded-[10px] p-4">
        <div className="text-label-2 font-bold mb-2.5">📋 시나리오 종합 비교표</div>
        <table className="w-full border-collapse text-caption">
          <thead>
            <tr className="bg-bg-base">
              <th className="py-[7px] px-2 text-left border-b-2 border-[var(--stroke-light)] text-fg-sub">
                지표
              </th>
              {chartData.map((d) => (
                <th
                  key={d.id}
                  className="py-[7px] px-2 text-center border-b-2 border-[var(--stroke-light)]"
                  style={{ color: SEV_COLOR[d.severity] }}
                >
                  {d.id}
                  <br />
                  <span className="font-normal text-caption text-fg-disabled">{d.label}</span>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {[
              {
                label: 'GM (m)',
                key: 'gm',
                fmt: (d: ChartDataItem) => d.gm.toFixed(1),
                clr: (d: ChartDataItem) => gmColor(d.gm),
              },
              {
                label: '횡경사 (°)',
                key: 'list',
                fmt: (d: ChartDataItem) => `${d.list}°`,
                clr: (d: ChartDataItem) => listColor(d.list),
              },
              {
                label: '잔존부력 (%)',
                key: 'buoy',
                fmt: (d: ChartDataItem) => `${d.buoy}%`,
                clr: (d: ChartDataItem) => buoyColor(d.buoy),
              },
              {
                label: '유출률 (L/min)',
                key: 'oil',
                fmt: (d: ChartDataItem) => `${d.oil}`,
                clr: (d: ChartDataItem) => oilColor(d.oil),
              },
              {
                label: 'BM 비율 (%)',
                key: 'bm',
                fmt: (d: ChartDataItem) => `${d.bm}%`,
                clr: (d: ChartDataItem) =>
                  d.bm > 100
                    ? 'var(--color-danger)'
                    : d.bm > 85
                      ? 'var(--color-warning)'
                      : 'var(--color-success)',
              },
              {
                label: '위험 등급',
                key: 'sev',
                fmt: (d: ChartDataItem) => d.severity,
                clr: (d: ChartDataItem) => SEV_COLOR[d.severity],
              },
            ].map((row) => (
              <tr key={row.label} style={{ borderBottom: '1px solid rgba(255,255,255,.04)' }}>
                <td className="py-1.5 px-2 font-semibold text-fg-sub">{row.label}</td>
                {chartData.map((d) => (
                  <td
                    key={d.id}
                    className="py-1.5 px-2 text-center font-mono font-bold"
                    style={{ color: row.clr(d) }}
                  >
                    {row.fmt(d)}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
