import { useState } from 'react';
import { Map } from '@vis.gl/react-maplibre';
import { ScatterplotLayer } from '@deck.gl/layers';
import { useBaseMapStyle } from '@common/hooks/useBaseMapStyle';
import { useMapStore } from '@common/store/mapStore';
import { S57EncOverlay } from '@components/common/map/S57EncOverlay';
import { DeckGLOverlay } from '../WingAI';

type MismatchStatus = '불일치' | '의심' | '정상' | '확인중';

interface VesselDetection {
  id: string;
  mmsi: string;
  vesselName: string;
  /** AIS 등록 선종 */
  aisType: string;
  /** AI 영상 분석 선종 */
  detectedType: string;
  /** 불일치 여부 */
  mismatch: boolean;
  status: MismatchStatus;
  confidence: string;
  coord: string;
  lon: number;
  lat: number;
  time: string;
  detail: string;
}

export function DetectPanel() {
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [filterStatus, setFilterStatus] = useState<MismatchStatus | '전체'>('전체');
  const currentMapStyle = useBaseMapStyle();
  const mapToggles = useMapStore((s) => s.mapToggles);

  const detections: VesselDetection[] = [
    {
      id: 'VD-001',
      mmsi: '440123456',
      vesselName: 'OCEAN GLORY',
      aisType: '화물선',
      detectedType: '유조선',
      mismatch: true,
      status: '불일치',
      confidence: '94.2%',
      coord: '33.24°N 126.50°E',
      lon: 126.5,
      lat: 33.24,
      time: '14:23',
      detail: 'AIS 화물선 등록 → 영상 분석 결과 유조선 선형 + 탱크 구조 탐지',
    },
    {
      id: 'VD-002',
      mmsi: '441987654',
      vesselName: 'SEA PHOENIX',
      aisType: '유조선',
      detectedType: '화물선',
      mismatch: true,
      status: '불일치',
      confidence: '91.7%',
      coord: '34.73°N 127.68°E',
      lon: 127.68,
      lat: 34.73,
      time: '14:18',
      detail: 'AIS 유조선 등록 → 영상 분석 결과 컨테이너 적재 확인, 화물선 판정',
    },
    {
      id: 'VD-003',
      mmsi: '440555123',
      vesselName: 'DONGBANG 7',
      aisType: '어선',
      detectedType: '화물선',
      mismatch: true,
      status: '의심',
      confidence: '78.3%',
      coord: '35.15°N 129.13°E',
      lon: 129.13,
      lat: 35.15,
      time: '14:10',
      detail: 'AIS 어선 등록 → 선체 규모 및 구조가 어선 대비 과대, 화물선 의심',
    },
    {
      id: 'VD-004',
      mmsi: '440678901',
      vesselName: 'KOREA STAR',
      aisType: '화물선',
      detectedType: '화물선',
      mismatch: false,
      status: '정상',
      confidence: '97.8%',
      coord: '34.80°N 126.37°E',
      lon: 126.37,
      lat: 34.8,
      time: '14:05',
      detail: 'AIS 등록 선종과 영상 분석 결과 일치',
    },
    {
      id: 'VD-005',
      mmsi: 'N/A',
      vesselName: '미식별',
      aisType: 'AIS 미수신',
      detectedType: '유조선',
      mismatch: true,
      status: '확인중',
      confidence: '85.6%',
      coord: '33.11°N 126.27°E',
      lon: 126.27,
      lat: 33.11,
      time: '14:01',
      detail: 'AIS 신호 없음 → 위성 SAR로 유조선급 선형 탐지, 불법 운항 의심',
    },
    {
      id: 'VD-006',
      mmsi: '440234567',
      vesselName: 'BUSAN EXPRESS',
      aisType: '컨테이너선',
      detectedType: '유조선',
      mismatch: true,
      status: '불일치',
      confidence: '89.1%',
      coord: '35.05°N 129.10°E',
      lon: 129.1,
      lat: 35.05,
      time: '13:55',
      detail: 'AIS 컨테이너선 → 갑판 컨테이너 미확인, 탱크 구조 감지',
    },
    {
      id: 'VD-007',
      mmsi: '440345678',
      vesselName: 'JEJU BREEZE',
      aisType: '여객선',
      detectedType: '여객선',
      mismatch: false,
      status: '정상',
      confidence: '98.1%',
      coord: '33.49°N 126.52°E',
      lon: 126.52,
      lat: 33.49,
      time: '13:50',
      detail: 'AIS 등록 선종과 영상 분석 결과 일치',
    },
  ];

  const mismatchCount = detections.filter((d) => d.mismatch).length;
  const confirmingCount = detections.filter((d) => d.status === '확인중').length;

  const stats = [
    { value: String(detections.length), label: '분석 선박', color: 'var(--fg-default)' },
    { value: String(mismatchCount), label: '선종 불일치', color: 'var(--fg-default)' },
    { value: String(confirmingCount), label: '확인 중', color: 'var(--fg-default)' },
    {
      value: String(detections.filter((d) => !d.mismatch).length),
      label: '정상',
      color: 'var(--fg-default)',
    },
  ];

  const filtered =
    filterStatus === '전체' ? detections : detections.filter((d) => d.status === filterStatus);

  const statusStyle = (s: MismatchStatus) => {
    if (s === '불일치')
      return {
        background: 'color-mix(in srgb, var(--color-danger) 12%, transparent)',
        color: 'var(--color-danger)',
        border: '1px solid color-mix(in srgb, var(--color-danger) 25%, transparent)',
      };
    if (s === '의심')
      return {
        background: 'color-mix(in srgb, var(--color-caution) 12%, transparent)',
        color: 'var(--color-caution)',
        border: '1px solid color-mix(in srgb, var(--color-caution) 25%, transparent)',
      };
    if (s === '확인중')
      return {
        background: 'rgba(6,182,212,.08)',
        color: 'var(--color-accent)',
        border: '1px solid rgba(6,182,212,.25)',
      };
    return {
      background: 'color-mix(in srgb, var(--color-success) 12%, transparent)',
      color: 'var(--color-success)',
      border: '1px solid color-mix(in srgb, var(--color-success) 25%, transparent)',
    };
  };

  const filters: (MismatchStatus | '전체')[] = ['전체', '불일치', '의심', '확인중', '정상'];

  return (
    <div>
      {/* 통계 카드 */}
      <div className="grid grid-cols-4 gap-3 mb-5">
        {stats.map((s, i) => (
          <div key={i} className="bg-bg-elevated border border-stroke rounded-md p-3.5 text-center">
            <div className="text-[22px] font-bold font-mono" style={{ color: s.color }}>
              {s.value}
            </div>
            <div className="text-caption text-fg-disabled mt-1 font-korean">{s.label}</div>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-[1fr_380px] gap-4">
        {/* 탐지 결과 지도 */}
        <div
          className="bg-bg-elevated border border-stroke rounded-md overflow-hidden"
          style={{ minHeight: 480 }}
        >
          <div className="flex items-center justify-between px-4 py-3 border-b border-stroke">
            <div className="text-label-2 font-bold font-korean text-fg">
              🎯 선종 불일치 탐지 지도
            </div>
            <div className="text-caption text-fg-disabled font-mono">{filtered.length}척 표시</div>
          </div>
          <div className="relative" style={{ height: 440 }}>
            <Map
              initialViewState={{ longitude: 127.5, latitude: 34.0, zoom: 6.5 }}
              style={{ width: '100%', height: '100%' }}
              mapStyle={currentMapStyle}
              attributionControl={false}
            >
              <S57EncOverlay visible={mapToggles['s57'] ?? false} />
              <DeckGLOverlay
                layers={[
                  new ScatterplotLayer({
                    id: 'vessel-detect-markers',
                    data: filtered,
                    getPosition: (d: VesselDetection) => [d.lon, d.lat],
                    getRadius: (d: VesselDetection) => (selectedId === d.id ? 10 : 7),
                    radiusUnits: 'pixels' as const,
                    getFillColor: (d: VesselDetection) => {
                      if (d.status === '불일치') return [239, 68, 68, 200];
                      if (d.status === '의심') return [234, 179, 8, 200];
                      if (d.status === '확인중') return [6, 182, 212, 200];
                      return [34, 197, 94, 160];
                    },
                    getLineColor: [255, 255, 255, 255],
                    lineWidthMinPixels: 2,
                    stroked: true,
                    pickable: true,
                    onClick: ({ object }: { object?: VesselDetection }) => {
                      if (object) setSelectedId(object.id === selectedId ? null : object.id);
                    },
                    updateTriggers: { getRadius: [selectedId] },
                  }),
                ]}
              />
            </Map>
            {/* 범례 */}
            <div className="absolute bottom-3 left-3 bg-bg-elevated/90 border border-stroke rounded px-3 py-2 backdrop-blur-sm">
              <div className="flex items-center gap-3">
                {[
                  { color: 'var(--color-danger)', label: '불일치' },
                  { color: 'var(--color-caution)', label: '의심' },
                  { color: 'var(--color-accent)', label: '확인중' },
                  { color: 'var(--color-success)', label: '정상' },
                ].map((l) => (
                  <div key={l.label} className="flex items-center gap-1">
                    <div className="w-2.5 h-2.5 rounded-full" style={{ background: l.color }} />
                    <span className="text-caption font-korean text-fg-disabled">{l.label}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* 탐지 목록 */}
        <div
          className="bg-bg-elevated border border-stroke rounded-md overflow-hidden flex flex-col"
          style={{ maxHeight: 520 }}
        >
          <div className="px-4 py-3 border-b border-stroke shrink-0">
            <div className="flex items-center justify-between mb-2">
              <div className="text-label-2 font-bold font-korean text-fg">
                📋 MMSI 선종 검증 목록
              </div>
              <div className="text-caption text-fg-disabled font-mono">{filtered.length}건</div>
            </div>
            <div className="flex gap-1">
              {filters.map((f) => (
                <button
                  key={f}
                  onClick={() => setFilterStatus(f)}
                  className="px-2 py-0.5 rounded text-caption font-bold font-korean cursor-pointer border transition-colors"
                  style={
                    filterStatus === f
                      ? {
                          background: 'rgba(6,182,212,.08)',
                          borderColor: 'rgba(6,182,212,.3)',
                          color: 'var(--color-accent)',
                        }
                      : {
                          background: 'var(--bg-card)',
                          borderColor: 'var(--stroke-default)',
                          color: 'var(--fg-disabled)',
                        }
                  }
                >
                  {f}
                </button>
              ))}
            </div>
          </div>
          <div className="divide-y divide-stroke overflow-y-auto flex-1">
            {filtered.map((d) => (
              <div
                key={d.id}
                onClick={() => setSelectedId(selectedId === d.id ? null : d.id)}
                className="px-4 py-3 hover:bg-bg-surface-hover/30 transition-colors cursor-pointer"
                style={{ background: selectedId === d.id ? 'rgba(6,182,212,.04)' : undefined }}
              >
                <div className="flex items-center justify-between mb-1">
                  <div className="flex items-center gap-2">
                    <span className="text-caption font-mono text-fg-disabled">{d.id}</span>
                    <span className="text-caption font-bold font-korean text-fg">
                      {d.vesselName}
                    </span>
                  </div>
                  <span
                    className="px-1.5 py-0.5 rounded text-caption font-bold font-korean"
                    style={statusStyle(d.status)}
                  >
                    {d.status}
                  </span>
                </div>
                {/* 선종 비교 */}
                <div className="flex items-center gap-1.5 mt-1.5">
                  <span className="text-caption font-korean text-fg">AIS: {d.aisType}</span>
                  {d.mismatch && <span className="text-caption text-fg-disabled">≠</span>}
                  {!d.mismatch && <span className="text-caption text-fg-disabled">=</span>}
                  <span className="text-caption font-korean text-fg">AI: {d.detectedType}</span>
                </div>
                <div className="flex items-center gap-3 mt-1.5 text-caption text-fg-disabled font-mono">
                  <span>MMSI {d.mmsi}</span>
                  <span>{d.coord}</span>
                  <span>{d.time}</span>
                  <span>신뢰도 {d.confidence}</span>
                </div>
                {/* 펼침: 상세 */}
                {selectedId === d.id && (
                  <div
                    className="mt-2 px-3 py-2 rounded text-caption font-korean"
                    style={{
                      background: 'rgba(6,182,212,.04)',
                      border: '1px solid rgba(6,182,212,.12)',
                      color: 'var(--fg-sub)',
                    }}
                  >
                    {d.detail}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
