import { useMemo, useState } from 'react';
import { Map, Marker, Popup } from '@vis.gl/react-maplibre';
import { useBaseMapStyle } from '@common/hooks/useBaseMapStyle';
import type { RescueOpsItem, RescueScenario } from '@interfaces/rescue/RescueInterface';
import type { Severity } from '@/types/rescue/RescueType';
import {
  SEV_STYLE,
  SEV_COLOR,
  gmColor,
  listColor,
  buoyColor,
  oilColor,
} from '../RescueScenarioView';

export interface ScenarioMapOverlayProps {
  ops: RescueOpsItem[];
  selectedIncident: number;
  scenarios: RescueScenario[];
  selectedId: string;
  checked: Set<string>;
  onSelectScenario: (id: string) => void;
}

export function ScenarioMapOverlay({
  ops,
  selectedIncident,
  scenarios,
  selectedId,
  checked,
  onSelectScenario,
}: ScenarioMapOverlayProps) {
  const [popupId, setPopupId] = useState<string | null>(null);
  const baseMapStyle = useBaseMapStyle();

  const currentOp = ops[selectedIncident] ?? null;
  const center = useMemo<[number, number]>(
    () =>
      currentOp?.lon != null && currentOp?.lat != null
        ? [currentOp.lon, currentOp.lat]
        : [126.25, 37.467],
    [currentOp],
  );

  const visibleScenarios = useMemo(
    () => scenarios.filter((s) => checked.has(s.id)),
    [scenarios, checked],
  );

  const selected = scenarios.find((s) => s.id === selectedId);

  return (
    <div className="flex flex-col flex-1 overflow-hidden">
      {/* 시나리오 선택 바 */}
      <div className="flex items-center gap-1.5 px-4 py-2 border-b border-stroke bg-bg-surface shrink-0 overflow-x-auto">
        <span className="text-caption text-fg-disabled shrink-0">시나리오:</span>
        {visibleScenarios.map((sc) => {
          const sev = SEV_STYLE[sc.severity];
          const isActive = selectedId === sc.id;
          return (
            <button
              key={sc.id}
              onClick={() => onSelectScenario(sc.id)}
              className="cursor-pointer shrink-0 px-2 py-1 rounded text-caption font-semibold transition-all"
              style={{
                border: `1.5px solid ${isActive ? sev.color : sev.color + '40'}`,
                background: isActive ? sev.bg : 'transparent',
                color: isActive ? sev.color : 'var(--fg-disabled)',
              }}
            >
              {sc.id} {sc.timeStep}
            </button>
          );
        })}
      </div>

      {/* 지도 영역 */}
      <div className="flex-1 relative">
        <Map
          initialViewState={{ longitude: center[0], latitude: center[1], zoom: 11 }}
          mapStyle={baseMapStyle}
          style={{ width: '100%', height: '100%' }}
          attributionControl={false}
        >
          {/* 사고 위치 마커 */}
          {currentOp && currentOp.lon != null && currentOp.lat != null && (
            <Marker longitude={currentOp.lon} latitude={currentOp.lat} anchor="center">
              <div
                className="flex items-center justify-center"
                style={{
                  width: 28,
                  height: 28,
                  borderRadius: '50%',
                  background: 'rgba(239,68,68,0.25)',
                  border: '2px solid var(--color-danger)',
                }}
              >
                <div
                  style={{
                    width: 10,
                    height: 10,
                    borderRadius: '50%',
                    background: 'var(--color-danger)',
                  }}
                />
              </div>
            </Marker>
          )}

          {/* 시나리오별 마커 — 사고 지점 주변에 시간 순서대로 배치 */}
          {visibleScenarios.map((sc, idx) => {
            const angle = (idx / visibleScenarios.length) * Math.PI * 2 - Math.PI / 2;
            const radius = 0.015 + idx * 0.003;
            const lng = center[0] + Math.cos(angle) * radius;
            const lat = center[1] + Math.sin(angle) * radius * 0.8;
            const sev = SEV_STYLE[sc.severity];
            const isActive = selectedId === sc.id;

            return (
              <Marker
                key={sc.id}
                longitude={lng}
                latitude={lat}
                anchor="center"
                onClick={(e) => {
                  e.originalEvent.stopPropagation();
                  onSelectScenario(sc.id);
                  setPopupId(popupId === sc.id ? null : sc.id);
                }}
              >
                <div
                  className="cursor-pointer flex items-center justify-center transition-transform"
                  style={{
                    width: isActive ? 36 : 28,
                    height: isActive ? 36 : 28,
                    borderRadius: '50%',
                    background: sev.bg,
                    border: `2px solid ${sev.color}`,
                    transform: isActive ? 'scale(1.15)' : 'scale(1)',
                    boxShadow: isActive ? `0 0 12px ${sev.color}60` : 'none',
                    zIndex: isActive ? 10 : 1,
                  }}
                >
                  <span
                    className="font-bold font-mono"
                    style={{ fontSize: isActive ? 11 : 9, color: sev.color }}
                  >
                    {sc.timeStep.replace('T+', '')}
                  </span>
                </div>
              </Marker>
            );
          })}

          {/* 팝업 — 클릭한 시나리오 정보 표출 */}
          {popupId &&
            (() => {
              const sc = visibleScenarios.find((s) => s.id === popupId);
              if (!sc) return null;
              const idx = visibleScenarios.indexOf(sc);
              const angle = (idx / visibleScenarios.length) * Math.PI * 2 - Math.PI / 2;
              const radius = 0.015 + idx * 0.003;
              const lng = center[0] + Math.cos(angle) * radius;
              const lat = center[1] + Math.sin(angle) * radius * 0.8;
              const sev = SEV_STYLE[sc.severity];

              return (
                <Popup
                  longitude={lng}
                  latitude={lat}
                  anchor="bottom"
                  closeOnClick={false}
                  onClose={() => setPopupId(null)}
                  maxWidth="320px"
                  className="rescue-map-popup"
                >
                  <div
                    style={{
                      padding: '8px 4px',
                      minWidth: 260,
                      background: 'var(--bg-card)',
                      color: 'var(--fg)',
                    }}
                  >
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
                      <span
                        style={{
                          fontWeight: 800,
                          fontFamily: 'monospace',
                          color: sev.color,
                          fontSize: 13,
                        }}
                      >
                        {sc.id}
                      </span>
                      <span style={{ fontWeight: 700, fontSize: 12 }}>{sc.timeStep}</span>
                      <span
                        style={{
                          marginLeft: 'auto',
                          padding: '1px 6px',
                          borderRadius: 8,
                          fontSize: 10,
                          fontWeight: 700,
                          background: sev.bg,
                          color: sev.color,
                        }}
                      >
                        {sev.label}
                      </span>
                    </div>
                    <div
                      style={{
                        fontSize: 11,
                        color: 'var(--fg-sub)',
                        lineHeight: 1.5,
                        marginBottom: 6,
                      }}
                    >
                      {sc.description}
                    </div>
                    {/* KPI */}
                    <div
                      style={{
                        display: 'grid',
                        gridTemplateColumns: '1fr 1fr 1fr 1fr',
                        gap: 4,
                        marginBottom: 6,
                      }}
                    >
                      {[
                        { label: 'GM', value: `${sc.gm}m`, color: gmColor(parseFloat(sc.gm)) },
                        {
                          label: '횡경사',
                          value: `${sc.list}°`,
                          color: listColor(parseFloat(sc.list)),
                        },
                        { label: '부력', value: `${sc.buoyancy}%`, color: buoyColor(sc.buoyancy) },
                        {
                          label: '유출',
                          value: sc.oilRate.split(' ')[0],
                          color: oilColor(parseFloat(sc.oilRate)),
                        },
                      ].map((m) => (
                        <div
                          key={m.label}
                          style={{
                            textAlign: 'center',
                            padding: '3px 2px',
                            borderRadius: 3,
                            background: 'var(--bg-base)',
                            fontSize: 10,
                          }}
                        >
                          <div style={{ color: 'var(--fg-disabled)' }}>{m.label}</div>
                          <div style={{ fontWeight: 700, fontFamily: 'monospace', color: m.color }}>
                            {m.value}
                          </div>
                        </div>
                      ))}
                    </div>
                    {/* 구획 상태 */}
                    {sc.compartments.length > 0 && (
                      <div style={{ marginBottom: 4 }}>
                        <div
                          style={{
                            fontSize: 10,
                            fontWeight: 600,
                            color: 'var(--fg-disabled)',
                            marginBottom: 3,
                          }}
                        >
                          구획 상태
                        </div>
                        <div style={{ display: 'flex', gap: 3, flexWrap: 'wrap' }}>
                          {sc.compartments.map((c) => (
                            <span
                              key={c.name}
                              style={{
                                fontSize: 9,
                                padding: '1px 5px',
                                borderRadius: 3,
                                border: `1px solid ${c.color}40`,
                                color: c.color,
                              }}
                            >
                              {c.name}: {c.status}
                            </span>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                </Popup>
              );
            })()}
        </Map>

        {/* 좌측 하단 — 선택된 시나리오 요약 오버레이 */}
        {selected && (
          <div
            className="absolute bottom-3 left-3 z-10 rounded-lg border border-stroke overflow-hidden"
            style={{ background: 'rgba(15,23,42,0.92)', width: 280, backdropFilter: 'blur(8px)' }}
          >
            <div className="px-3 py-2 border-b border-stroke flex items-center gap-2">
              <span className="font-bold font-mono text-color-accent text-label-2">
                {selected.id}
              </span>
              <span className="text-caption font-bold">{selected.timeStep}</span>
              <span
                className="ml-auto px-1.5 py-0.5 rounded-md text-caption font-bold"
                style={{
                  background: SEV_STYLE[selected.severity].bg,
                  color: SEV_STYLE[selected.severity].color,
                }}
              >
                {SEV_STYLE[selected.severity].label}
              </span>
            </div>
            <div className="px-3 py-2">
              <div className="grid grid-cols-4 gap-1 font-mono text-caption mb-2">
                {[
                  {
                    label: 'GM',
                    value: `${selected.gm}m`,
                    color: gmColor(parseFloat(selected.gm)),
                  },
                  {
                    label: '횡경사',
                    value: `${selected.list}°`,
                    color: listColor(parseFloat(selected.list)),
                  },
                  {
                    label: '부력',
                    value: `${selected.buoyancy}%`,
                    color: buoyColor(selected.buoyancy),
                  },
                  {
                    label: '유출',
                    value: selected.oilRate.split(' ')[0],
                    color: oilColor(parseFloat(selected.oilRate)),
                  },
                ].map((m) => (
                  <div key={m.label} className="text-center p-1 bg-bg-base rounded">
                    <div className="text-fg-disabled" style={{ fontSize: 9 }}>
                      {m.label}
                    </div>
                    <div className="font-bold" style={{ color: m.color, fontSize: 11 }}>
                      {m.value}
                    </div>
                  </div>
                ))}
              </div>
              <div className="text-caption text-fg-sub leading-relaxed" style={{ fontSize: 10 }}>
                {selected.description.slice(0, 120)}
                {selected.description.length > 120 ? '...' : ''}
              </div>
            </div>
          </div>
        )}

        {/* 우측 상단 — 범례 */}
        <div
          className="absolute top-3 right-3 z-10 rounded-lg border border-stroke px-3 py-2"
          style={{ background: 'rgba(15,23,42,0.88)', backdropFilter: 'blur(8px)' }}
        >
          <div className="text-caption font-bold text-fg-disabled mb-1.5">시나리오 범례</div>
          {(['CRITICAL', 'HIGH', 'MEDIUM', 'RESOLVED'] as Severity[]).map((sev) => (
            <div key={sev} className="flex items-center gap-1.5 mb-0.5">
              <span
                className="inline-block rounded-full"
                style={{ width: 8, height: 8, background: SEV_COLOR[sev] }}
              />
              <span className="text-caption text-fg-sub">{SEV_STYLE[sev].label}</span>
            </div>
          ))}
          <div className="flex items-center gap-1.5 mt-1 pt-1 border-t border-stroke">
            <span
              className="inline-block rounded-full"
              style={{
                width: 8,
                height: 8,
                background: 'var(--color-danger)',
                border: '1px solid var(--color-danger)',
              }}
            />
            <span className="text-caption text-fg-sub">사고 위치</span>
          </div>
        </div>
      </div>
    </div>
  );
}
