import { useState, useEffect } from 'react';
import { Map, useControl } from '@vis.gl/react-maplibre';
import { MapboxOverlay } from '@deck.gl/mapbox';
import { ScatterplotLayer } from '@deck.gl/layers';
import 'maplibre-gl/dist/maplibre-gl.css';
import type { ScatDetail } from './scatTypes';
import { hexToRgba } from '@common/components/map/mapUtils';
import { useBaseMapStyle } from '@common/hooks/useBaseMapStyle';

// ── DeckGLOverlay ──────────────────────────────────────
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function DeckGLOverlay({ layers }: { layers: any[] }) {
  const overlay = useControl<MapboxOverlay>(() => new MapboxOverlay({ interleaved: true }));
  overlay.setProps({ layers });
  return null;
}

// ── PopupMap (미니맵) ────────────────────────────────────
function PopupMap({
  lat,
  lng,
  esiCol,
  code,
  name,
  esi,
  onMapLoad,
}: {
  lat: number;
  lng: number;
  esiCol: string;
  code: string;
  name: string;
  esi: string;
  onMapLoad?: () => void;
}) {
  // 해안 구간 라인 / 조사 경로 — 하드코딩 방향이라 주석처리, 추후 실제 방향 데이터로 대체
  // const segLine: [number, number][] = [
  //   [lng - 0.004, lat - 0.002],
  //   [lng - 0.002, lat - 0.001],
  //   [lng, lat],
  //   [lng + 0.002, lat + 0.001],
  //   [lng + 0.004, lat + 0.002],
  // ]
  // const surveyRoute: [number, number][] = [
  //   [lng - 0.003, lat - 0.0015],
  //   [lng - 0.001, lat - 0.0005],
  //   [lng + 0.001, lat + 0.0005],
  //   [lng + 0.003, lat + 0.0015],
  // ]

  const deckLayers = [
    // 접근 포인트 (노란 점)
    new ScatterplotLayer({
      id: 'access-point',
      data: [{ position: [lng - 0.003, lat - 0.0015] as [number, number] }],
      getPosition: (d: { position: [number, number] }) => d.position,
      getRadius: 6,
      getFillColor: hexToRgba('#eab308', 178),
      getLineColor: hexToRgba('#eab308', 200),
      getLineWidth: 1,
      stroked: true,
      radiusMinPixels: 4,
      radiusMaxPixels: 8,
    }),
    // 메인 마커 (ESI 색상 원)
    new ScatterplotLayer({
      id: 'main-marker',
      data: [{ position: [lng, lat] as [number, number] }],
      getPosition: (d: { position: [number, number] }) => d.position,
      getRadius: 10,
      getFillColor: hexToRgba(esiCol, 229),
      getLineColor: [255, 255, 255, 255],
      getLineWidth: 2,
      stroked: true,
      radiusMinPixels: 8,
      radiusMaxPixels: 14,
    }),
  ];

  const currentMapStyle = useBaseMapStyle();

  return (
    <div className="relative w-full h-full">
      <Map
        key={`${lat}-${lng}`}
        initialViewState={{ longitude: lng, latitude: lat, zoom: 15 }}
        mapStyle={currentMapStyle}
        style={{ width: '100%', height: '100%' }}
        attributionControl={false}
        onLoad={onMapLoad}
      >
        <DeckGLOverlay layers={deckLayers} />
      </Map>
      {/* 마커 레이블 오버레이 */}
      <div
        className="pointer-events-none absolute text-fg font-korean text-[10px] rounded-[6px] text-center"
        style={{
          left: '50%',
          top: 'calc(50% - 44px)',
          transform: 'translateX(-50%)',
          background: 'color-mix(in srgb, var(--bg-base) 92%, transparent)',
          border: '1px solid var(--stroke-default)',
          padding: '3px 7px',
          whiteSpace: 'nowrap',
          zIndex: 10,
        }}
      >
        <div className="text-label-2 font-bold">
          {code} {name}
        </div>
        <div className="opacity-70">ESI {esi}</div>
      </div>
    </div>
  );
}

// ── ScatPopup Modal ──────────────────────────────────────
interface ScatPopupProps {
  data: ScatDetail | null;
  segCode: string;
  onClose: () => void;
}

function ScatPopup({ data, segCode, onClose }: ScatPopupProps) {
  const [popTab, setPopTab] = useState(0);
  const [imgLoaded, setImgLoaded] = useState(false);
  const [imgError, setImgError] = useState(false);
  const [mapLoaded, setMapLoaded] = useState(false);

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [onClose]);

  if (!data) return null;

  return (
    <div
      className="fixed inset-0 bg-[rgba(5,8,18,0.75)] backdrop-blur-md z-[9999] flex items-center justify-center"
      onClick={onClose}
    >
      <div
        className="w-[92%] max-w-[1200px] h-[90vh] bg-bg-surface border border-stroke rounded-xl shadow-[0_24px_64px_rgba(0,0,0,0.5)] flex flex-col overflow-hidden"
        style={{ animation: 'spIn 0.3s ease' }}
        onClick={(e) => e.stopPropagation()}
      >
        <style>{`
          @keyframes spIn {
            from { opacity: 0; transform: scale(0.95) translateY(10px); }
            to   { opacity: 1; transform: scale(1)    translateY(0); }
          }
        `}</style>

        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-stroke flex-shrink-0">
          <div className="flex items-center gap-2.5">
            <span className="text-title-4 font-bold text-color-success font-mono px-2.5 py-1 bg-[color-mix(in_srgb,var(--color-success)_10%,transparent)] border border-[color-mix(in_srgb,var(--color-success)_25%,transparent)] rounded-sm">
              {data.code}
            </span>
            <span className="text-title-3 font-bold font-korean">{data.name}</span>
            <span
              className="text-label-2 font-bold px-2.5 py-0.5 rounded-xl text-white"
              style={{ background: data.esiColor }}
            >
              ESI {data.esi}
            </span>
          </div>
          <button
            onClick={onClose}
            className="w-9 h-9 rounded-sm border border-stroke bg-bg-card text-fg-sub flex items-center justify-center cursor-pointer hover:bg-[color-mix(in_srgb,var(--color-danger)_15%,transparent)] hover:text-color-danger hover:border-[color-mix(in_srgb,var(--color-danger)_30%,transparent)] transition-colors text-lg"
          >
            ✕
          </button>
        </div>

        {/* Tabs */}
        <div className="flex border-b border-stroke px-6 flex-shrink-0">
          {['해안정보', '조사 이력'].map((label, i) => (
            <button
              key={i}
              onClick={() => setPopTab(i)}
              className={`px-5 py-3 text-caption font-semibold font-korean border-b-2 transition-colors cursor-pointer ${
                popTab === i
                  ? 'text-color-success border-status-green'
                  : 'text-fg-disabled border-transparent hover:text-fg-sub'
              }`}
            >
              {label}
            </button>
          ))}
        </div>

        {/* Body */}
        <div className="flex-1 min-h-0 overflow-hidden">
          {popTab === 0 && (
            <div className="flex h-full overflow-hidden">
              {/* Left column */}
              <div className="flex-1 overflow-y-auto border-r border-stroke p-5 px-6 scrollbar-thin">
                {/* 해안 조사 사진 */}
                <div className="w-full bg-bg-base border border-stroke rounded-md mb-4 relative overflow-hidden">
                  {/* Skeleton */}
                  {!imgLoaded && !imgError && (
                    <div className="w-full aspect-video bg-bg-card animate-pulse flex items-center justify-center">
                      <span className="text-fg-disabled text-caption font-korean">
                        사진 로딩 중...
                      </span>
                    </div>
                  )}
                  <img
                    src={`/scat/img/${segCode}-1.png`}
                    // src={`/scat/img/test.png`}
                    alt={`${segCode} 해안 조사 사진`}
                    className={`w-full h-auto object-contain ${imgLoaded ? '' : 'hidden'}`}
                    onLoad={() => setImgLoaded(true)}
                    onError={() => setImgError(true)}
                  />
                  {imgError && (
                    <div className="w-full aspect-video flex flex-col items-center justify-center text-fg-disabled text-caption font-korean">
                      {/* <span className="text-[40px]">📷</span> */}
                      <span>사진 없음</span>
                    </div>
                  )}
                  <div className="absolute top-2 left-2 px-2 py-0.5 bg-[color-mix(in_srgb,var(--bg-base)_80%,transparent)] border border-stroke rounded text-caption font-bold text-fg font-mono backdrop-blur-sm">
                    {segCode}
                  </div>
                </div>

                {/* Survey Info */}
                <div className="mb-4">
                  <div className="text-label-2 font-bold text-color-success uppercase tracking-wider mb-2.5 pb-1.5 border-b border-[color-mix(in_srgb,var(--color-success)_15%,transparent)] font-korean flex items-center gap-1.5">
                    🏖 해안 기본정보
                  </div>
                  {[
                    ['유형', data.type, ''],
                    [
                      '기질',
                      data.substrate,
                      data.esiColor === '#dc2626' || data.esiColor === '#991b1b'
                        ? 'text-color-danger'
                        : data.esiColor === '#f97316'
                          ? 'text-color-warning'
                          : '',
                    ],
                    ['구간 길이', data.length, ''],
                    [
                      '민감도',
                      data.sensitivity,
                      data.sensitivity === '상' || data.sensitivity === '최상'
                        ? 'text-color-danger'
                        : data.sensitivity === '중'
                          ? 'text-color-warning'
                          : 'text-color-success',
                    ],
                    [
                      '조사 상태',
                      data.status,
                      data.status === '완료'
                        ? 'text-color-success'
                        : data.status === '진행중'
                          ? 'text-color-warning'
                          : '',
                    ],
                    ['접근성', data.access, ''],
                    ['접근 포인트', data.accessPt, ''],
                  ].map(([k, v, cls], i) => (
                    <div
                      key={i}
                      className="flex justify-between py-1.5 text-caption border-b border-stroke last:border-b-0"
                    >
                      <span className="text-fg-sub font-korean">{k}</span>
                      <span className={`text-fg font-korean ${cls}`}>{v}</span>
                    </div>
                  ))}
                </div>

                {/* Sensitive Resources */}
                <div className="mb-4">
                  <div className="text-label-2 font-bold text-color-success uppercase tracking-wider mb-2.5 pb-1.5 border-b border-[color-mix(in_srgb,var(--color-success)_15%,transparent)] font-korean flex items-center gap-1.5">
                    🌿 민감 자원
                  </div>
                  {data.sensitive.map((s, i) => (
                    <div
                      key={i}
                      className="flex justify-between py-1.5 text-caption border-b border-stroke last:border-b-0"
                    >
                      <span className="text-fg-sub font-korean">{s.t}</span>
                      <span className="text-fg font-korean">{s.v}</span>
                    </div>
                  ))}
                </div>

                {/* Cleanup Methods */}
                <div className="mb-4">
                  <div className="text-label-2 font-bold text-color-success uppercase tracking-wider mb-2.5 pb-1.5 border-b border-[color-mix(in_srgb,var(--color-success)_15%,transparent)] font-korean flex items-center gap-1.5">
                    🧹 방제 방법
                  </div>
                  <div className="flex flex-wrap gap-1">
                    {data.cleanup.map((c, i) => (
                      <span
                        key={i}
                        className="inline-flex items-center gap-1 px-2 py-0.5 bg-bg-base border border-stroke rounded text-caption text-fg font-medium font-korean"
                      >
                        {c}
                      </span>
                    ))}
                  </div>
                </div>

                {/* End Criteria */}
                <div className="mb-4">
                  <div className="text-label-2 font-bold text-color-success uppercase tracking-wider mb-2.5 pb-1.5 border-b border-[color-mix(in_srgb,var(--color-success)_15%,transparent)] font-korean flex items-center gap-1.5">
                    ✅ 방제 종료 기준
                  </div>
                  <div className="px-3 py-2.5 bg-[color-mix(in_srgb,var(--color-caution)_6%,transparent)] border border-[color-mix(in_srgb,var(--color-caution)_15%,transparent)] rounded-sm text-label-2 text-fg-sub leading-[1.7] font-korean">
                    {data.endCriteria.map((e, i) => (
                      <div key={i} className="pl-3.5 relative mb-1">
                        <span className="absolute left-0 text-color-caution">•</span>
                        {e}
                      </div>
                    ))}
                  </div>
                </div>

                {/* Notes */}
                <div>
                  <div className="text-label-2 font-bold text-color-success uppercase tracking-wider mb-2.5 pb-1.5 border-b border-[color-mix(in_srgb,var(--color-success)_15%,transparent)] font-korean flex items-center gap-1.5">
                    📝 참고사항
                  </div>
                  <div className="px-3 py-2.5 bg-[color-mix(in_srgb,var(--color-caution)_6%,transparent)] border border-[color-mix(in_srgb,var(--color-caution)_15%,transparent)] rounded-sm text-label-2 text-fg-sub leading-[1.7] font-korean">
                    {data.notes.map((n, i) => (
                      <div key={i} className="pl-3.5 relative mb-1">
                        <span className="absolute left-0 text-color-caution">•</span>
                        {n}
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              {/* Right column - Mini map */}
              <div className="flex-1 overflow-y-auto p-5 px-6 scrollbar-thin">
                {/* MapLibre 미니맵 */}
                <div className="w-full aspect-[4/3] bg-bg-base border border-stroke rounded-md mb-4 overflow-hidden relative">
                  {!mapLoaded && (
                    <div className="absolute inset-0 bg-bg-card animate-pulse flex items-center justify-center z-10">
                      <span className="text-fg-disabled text-caption font-korean">
                        지도 로딩 중...
                      </span>
                    </div>
                  )}
                  <PopupMap
                    lat={data.lat}
                    lng={data.lng}
                    esi={data.esi}
                    esiCol={data.esiColor}
                    code={data.code}
                    name={data.name}
                    onMapLoad={() => setMapLoaded(true)}
                  />
                </div>

                {/* Legend */}
                <div className="flex flex-wrap gap-1.5 mb-4">
                  {[
                    { color: '#dc2626', label: 'ESI 고위험 구간' },
                    { color: '#f97316', label: 'ESI 중위험 구간' },
                    { color: '#22c55e', label: 'ESI 저위험 구간' },
                    { color: '#3b82f6', label: '조사 경로' },
                    { color: '#eab308', label: '접근 포인트' },
                  ].map((item, i) => (
                    <div
                      key={i}
                      className="flex items-center gap-1.5 text-caption text-fg-sub font-korean"
                    >
                      <span className="w-5 h-1 rounded-sm" style={{ background: item.color }} />
                      {item.label}
                    </div>
                  ))}
                </div>

                {/* Coordinates */}
                <div className="mb-4">
                  <div className="text-label-2 font-bold text-color-success uppercase tracking-wider mb-2.5 pb-1.5 border-b border-[color-mix(in_srgb,var(--color-success)_15%,transparent)] font-korean flex items-center gap-1.5">
                    📍 좌표 정보
                  </div>
                  {[
                    ['시작점 위도', `${data.lat.toFixed(4)}°N`],
                    ['시작점 경도', `${data.lng.toFixed(4)}°E`],
                    ['끝점 위도', `${(data.lat + 0.005).toFixed(4)}°N`],
                    ['끝점 경도', `${(data.lng + 0.008).toFixed(4)}°E`],
                  ].map(([k, v], i) => (
                    <div
                      key={i}
                      className="flex justify-between py-1.5 text-caption border-b border-stroke last:border-b-0"
                    >
                      <span className="text-fg-disabled font-korean">{k}</span>
                      <span className="text-color-success font-mono font-medium">{v}</span>
                    </div>
                  ))}
                </div>

                {/* Survey parameters */}
                <div>
                  <div className="text-label-2 font-bold text-color-success uppercase tracking-wider mb-2.5 pb-1.5 border-b border-[color-mix(in_srgb,var(--color-success)_15%,transparent)] font-korean flex items-center gap-1.5">
                    ⚙ 조사 파라미터
                  </div>
                  {[
                    ['조사 일시', '2026-01-15 10:30'],
                    ['조사팀', '제주해경 방제과'],
                    ['기상 상태', '맑음, 풍속 3.2m/s'],
                    ['조위', '중조 (TP +1.2m)'],
                    ['파고', '0.5-1.0m'],
                    ['수온', '14.2°C'],
                  ].map(([k, v], i) => (
                    <div
                      key={i}
                      className="flex justify-between py-1.5 text-caption border-b border-stroke last:border-b-0"
                    >
                      <span className="text-fg-disabled font-korean">{k}</span>
                      <span className="text-fg font-medium font-korean">{v}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {popTab === 1 && (
            <div className="p-6 overflow-y-auto h-full scrollbar-thin">
              <div className="text-caption font-bold font-korean mb-4">
                {data.code} {data.name} — 조사 이력
              </div>
              <div className="flex flex-col gap-3">
                {[
                  {
                    date: '2026-01-15',
                    team: '제주해경 방제과',
                    type: 'Pre-SCAT',
                    status: '완료',
                    note: '초기 사전조사 실시. ESI 확인.',
                  },
                ].map((h, i) => (
                  <div key={i} className="bg-bg-card border border-stroke rounded-md p-4">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-caption font-bold font-mono">{h.date}</span>
                      <span
                        className={`text-caption font-bold px-2 py-0.5 rounded-lg ${
                          h.type === 'Pre-SCAT'
                            ? 'bg-[color-mix(in_srgb,var(--color-success)_15%,transparent)] text-color-success'
                            : 'bg-[color-mix(in_srgb,var(--color-info)_15%,transparent)] text-color-info'
                        }`}
                      >
                        {h.type}
                      </span>
                    </div>
                    <div className="text-label-2 text-fg-sub font-korean mb-1">
                      조사팀: {h.team}
                    </div>
                    <div className="text-label-2 text-fg-disabled font-korean">{h.note}</div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default ScatPopup;
