import { Source, Layer, Popup } from 'react-map-gl/maplibre';
import { FONT_MONO } from '../../styles/fonts';
import type { FleetCompany } from '../../services/vesselAnalysis';
import type { VesselAnalysisDto } from '../../types';
import type { UseGroupPolygonsResult } from '../../hooks/useGroupPolygons';
import type {
  HoverTooltipState,
  GearPickerPopupState,
  PickerCandidate,
} from './fleetClusterTypes';
import type { FleetClusterGeoJsonResult } from './useFleetClusterGeoJson';
import { MODEL_ORDER, MODEL_COLORS } from './fleetClusterConstants';

interface FleetClusterMapLayersProps {
  geo: FleetClusterGeoJsonResult;
  selectedGearGroup: string | null;
  hoveredMmsi: string | null;
  enabledModels: Set<string>;
  expandedFleet: number | null;
  historyActive: boolean;
  // Popup/tooltip state
  hoverTooltip: HoverTooltipState | null;
  gearPickerPopup: GearPickerPopupState | null;
  pickerHoveredGroup: string | null;
  // Data for tooltip rendering
  groupPolygons: UseGroupPolygonsResult | undefined;
  companies: Map<number, FleetCompany>;
  analysisMap: Map<string, VesselAnalysisDto>;
  // Whether any correlation trails exist (drives conditional render)
  hasCorrelationTracks: boolean;
  // Callbacks
  onPickerHover: (group: string | null) => void;
  onPickerSelect: (candidate: PickerCandidate) => void;
  onPickerClose: () => void;
}

const FleetClusterMapLayers = ({
  geo,
  selectedGearGroup,
  hoveredMmsi,
  enabledModels,
  expandedFleet,
  historyActive,
  hoverTooltip,
  gearPickerPopup,
  pickerHoveredGroup,
  groupPolygons,
  companies,
  analysisMap,
  hasCorrelationTracks,
  onPickerHover,
  onPickerSelect,
  onPickerClose,
}: FleetClusterMapLayersProps) => {
  const {
    fleetPolygonGeoJSON,
    lineGeoJSON,
    hoveredGeoJSON,
    gearClusterGeoJson,
    memberMarkersGeoJson,
    pickerHighlightGeoJson,
    operationalPolygons,
    correlationVesselGeoJson,
    correlationTrailGeoJson,
    modelBadgesGeoJson,
    hoverHighlightGeoJson,
    hoverHighlightTrailGeoJson,
  } = geo;

  return (
    <>
      {/* 선단 폴리곤 레이어 */}
      <Source id="fleet-cluster-fill" type="geojson" data={fleetPolygonGeoJSON}>
        <Layer
          id="fleet-cluster-fill-layer"
          type="fill"
          paint={{
            'fill-color': ['get', 'color'],
            'fill-opacity': 0.1,
          }}
        />
        <Layer
          id="fleet-cluster-line-layer"
          type="line"
          paint={{
            'line-color': ['get', 'color'],
            'line-opacity': 0.5,
            'line-width': 1.5,
          }}
        />
      </Source>

      {/* 2척 선단 라인 (서버측 Polygon 처리로 빈 컬렉션) */}
      <Source id="fleet-cluster-line" type="geojson" data={lineGeoJSON}>
        <Layer
          id="fleet-cluster-line-only"
          type="line"
          paint={{
            'line-color': ['get', 'color'],
            'line-opacity': 0.5,
            'line-width': 1.5,
            'line-dasharray': [4, 2],
          }}
        />
      </Source>

      {/* 호버 하이라이트 (별도 Source) */}
      <Source id="fleet-cluster-hovered" type="geojson" data={hoveredGeoJSON}>
        <Layer
          id="fleet-cluster-hovered-fill"
          type="fill"
          paint={{
            'fill-color': ['get', 'color'],
            'fill-opacity': 0.25,
          }}
        />
      </Source>

      {/* 선택된 어구 그룹 — 이름 기반 하이라이트 폴리곤 */}
      {selectedGearGroup && enabledModels.has('identity') && !historyActive && (() => {
        const allGroups = groupPolygons
          ? [...groupPolygons.gearInZoneGroups, ...groupPolygons.gearOutZoneGroups]
          : [];
        const group = allGroups.find(g => g.groupKey === selectedGearGroup);
        if (!group?.polygon) return null;
        const hlGeoJson: GeoJSON.FeatureCollection = {
          type: 'FeatureCollection',
          features: [{
            type: 'Feature',
            properties: {},
            geometry: group.polygon,
          }],
        };
        return (
          <Source id="gear-cluster-selected" type="geojson" data={hlGeoJson}>
            <Layer id="gear-selected-fill" type="fill" paint={{ 'fill-color': '#f97316', 'fill-opacity': 0.25 }} />
            <Layer id="gear-selected-line" type="line" paint={{ 'line-color': '#f97316', 'line-width': 3, 'line-opacity': 0.9 }} />
          </Source>
        );
      })()}

      {/* 선택된 어구 그룹 — 모델별 오퍼레이셔널 폴리곤 오버레이 */}
      {selectedGearGroup && !historyActive && operationalPolygons.map(op => (
        <Source key={`op-${op.modelName}`} id={`gear-op-${op.modelName}`} type="geojson" data={op.geojson}>
          <Layer id={`gear-op-fill-${op.modelName}`} type="fill" paint={{
            'fill-color': op.color, 'fill-opacity': 0.12,
          }} />
          <Layer id={`gear-op-line-${op.modelName}`} type="line" paint={{
            'line-color': op.color, 'line-width': 2.5, 'line-opacity': 0.8,
            'line-dasharray': [6, 3],
          }} />
        </Source>
      ))}

      {/* 비허가 어구 클러스터 폴리곤 */}
      <Source id="gear-clusters" type="geojson" data={gearClusterGeoJson}>
        <Layer
          id="gear-cluster-fill-layer"
          type="fill"
          paint={{
            'fill-color': ['case', ['==', ['get', 'inZone'], 1], 'rgba(220, 38, 38, 0.12)', 'rgba(249, 115, 22, 0.08)'],
          }}
        />
        <Layer
          id="gear-cluster-line-layer"
          type="line"
          paint={{
            'line-color': ['case', ['==', ['get', 'inZone'], 1], '#dc2626', '#f97316'],
            'line-opacity': 0.7,
            'line-width': ['case', ['==', ['get', 'inZone'], 1], 2, 1.5],
            'line-dasharray': [4, 2],
          }}
        />
      </Source>

      {/* 가상 선박 마커 — 히스토리 재생 모드에서는 숨김 (deck.gl 레이어로 대체) */}
      <Source id="group-member-markers" type="geojson" data={historyActive ? ({ type: 'FeatureCollection', features: [] } as GeoJSON.FeatureCollection) : memberMarkersGeoJson}>
        <Layer
          id="group-member-icon"
          type="symbol"
          layout={{
            'icon-image': ['case', ['==', ['get', 'isGear'], 1], 'gear-diamond', 'ship-triangle'],
            'icon-size': ['interpolate', ['linear'], ['zoom'],
              4, ['*', ['get', 'baseSize'], 0.9],
              6, ['*', ['get', 'baseSize'], 1.2],
              8, ['*', ['get', 'baseSize'], 1.8],
              10, ['*', ['get', 'baseSize'], 2.6],
              12, ['*', ['get', 'baseSize'], 3.2],
              13, ['*', ['get', 'baseSize'], 4.0],
              14, ['*', ['get', 'baseSize'], 4.8],
            ],
            'icon-rotate': ['case', ['==', ['get', 'isGear'], 1], 0, ['get', 'cog']],
            'icon-rotation-alignment': 'map',
            'icon-allow-overlap': true,
            'icon-ignore-placement': true,
            'text-field': ['get', 'name'],
            'text-size': ['interpolate', ['linear'], ['zoom'], 4, 6, 8, 8, 12, 10],
            'text-offset': [0, 1.4],
            'text-anchor': 'top',
            'text-allow-overlap': false,
            'text-font': ['Open Sans Regular', 'Arial Unicode MS Regular'],
          }}
          paint={{
            'icon-color': ['get', 'color'],
            'icon-halo-color': 'rgba(0,0,0,0.6)',
            'icon-halo-width': 0.5,
            'text-color': ['get', 'color'],
            'text-halo-color': '#000000',
            'text-halo-width': 1,
          }}
        />
      </Source>

      {/* 어구 picker 호버 하이라이트 */}
      <Source id="gear-picker-highlight" type="geojson" data={pickerHighlightGeoJson}>
        <Layer id="gear-picker-highlight-fill" type="fill"
          paint={{ 'fill-color': '#ffffff', 'fill-opacity': 0.25 }} />
        <Layer id="gear-picker-highlight-line" type="line"
          paint={{ 'line-color': '#ffffff', 'line-width': 2, 'line-dasharray': [3, 2] }} />
      </Source>

      {/* 어구 다중 선택 팝업 */}
      {gearPickerPopup && (
        <Popup longitude={gearPickerPopup.lng} latitude={gearPickerPopup.lat}
          onClose={() => { onPickerClose(); }}
          closeOnClick={false} className="gl-popup" maxWidth="220px">
          <div style={{ fontSize: 10, fontFamily: FONT_MONO, padding: '4px 0' }}>
            <div style={{ fontWeight: 700, marginBottom: 4, color: '#e2e8f0', padding: '0 6px' }}>
              겹친 그룹 ({gearPickerPopup.candidates.length})
            </div>
            {gearPickerPopup.candidates.map(c => (
              <div key={c.isFleet ? `fleet-${c.clusterId}` : c.name}
                onMouseEnter={() => onPickerHover(c.isFleet ? String(c.clusterId) : c.name)}
                onMouseLeave={() => onPickerHover(null)}
                onClick={() => {
                  onPickerSelect(c);
                  onPickerClose();
                }}
                style={{
                  cursor: 'pointer', padding: '3px 6px',
                  borderLeft: `3px solid ${c.isFleet ? '#63b3ed' : c.inZone ? '#dc2626' : '#f97316'}`,
                  marginBottom: 2, borderRadius: 2,
                  backgroundColor: pickerHoveredGroup === (c.isFleet ? String(c.clusterId) : c.name) ? 'rgba(255,255,255,0.1)' : 'transparent',
                }}>
                <span style={{ color: c.isFleet ? '#63b3ed' : '#e2e8f0', fontSize: 9 }}>{c.isFleet ? '⚓ ' : ''}{c.name}</span>
                <span style={{ color: '#64748b', marginLeft: 4 }}>({c.count}{c.isFleet ? '척' : '개'})</span>
              </div>
            ))}
          </div>
        </Popup>
      )}

      {/* 폴리곤 호버 툴팁 */}
      {hoverTooltip && (() => {
        if (hoverTooltip.type === 'fleet') {
          const cid = hoverTooltip.id as number;
          const group = groupPolygons?.fleetGroups.find(g => Number(g.groupKey) === cid);
          const company = companies.get(cid);
          const memberCount = group?.memberCount ?? 0;
          return (
            <Popup longitude={hoverTooltip.lng} latitude={hoverTooltip.lat}
              closeButton={false} closeOnClick={false} anchor="bottom"
              className="gl-popup" maxWidth="220px"
            >
              <div style={{ fontFamily: FONT_MONO, fontSize: 10, padding: 4, color: '#e2e8f0' }}>
                <div style={{ fontWeight: 700, color: group?.color ?? '#63b3ed', marginBottom: 3 }}>
                  {company?.nameCn || group?.groupLabel || `선단 #${cid}`}
                </div>
                <div style={{ color: '#94a3b8' }}>선박 {memberCount}척</div>
                {expandedFleet === cid && group?.members.slice(0, 5).map(m => {
                  const dto = analysisMap.get(m.mmsi);
                  const role = dto?.algorithms.fleetRole.role ?? m.role;
                  return (
                    <div key={m.mmsi} style={{ fontSize: 9, color: '#7ea8c4', marginTop: 2 }}>
                      {role === 'LEADER' ? '★' : '·'} {m.name || m.mmsi} <span style={{ color: '#4a6b82' }}>{m.sog.toFixed(1)}kt</span>
                    </div>
                  );
                })}
                <div style={{ fontSize: 8, color: '#4a6b82', marginTop: 3 }}>클릭하여 상세 보기</div>
              </div>
            </Popup>
          );
        }
        if (hoverTooltip.type === 'gear') {
          const name = hoverTooltip.id as string;
          const allGroups = groupPolygons
            ? [...groupPolygons.gearInZoneGroups, ...groupPolygons.gearOutZoneGroups]
            : [];
          const group = allGroups.find(g => g.groupKey === name);
          if (!group) return null;
          const parentMember = group.members.find(m => m.isParent);
          const gearMembers = group.members.filter(m => !m.isParent);
          return (
            <Popup longitude={hoverTooltip.lng} latitude={hoverTooltip.lat}
              closeButton={false} closeOnClick={false} anchor="bottom"
              className="gl-popup" maxWidth={selectedGearGroup === name ? '280px' : '220px'}
            >
              <div style={{ fontFamily: FONT_MONO, fontSize: 10, padding: 4, color: '#e2e8f0' }}>
                <div style={{ fontWeight: 700, color: '#f97316', marginBottom: 3 }}>
                  {name} <span style={{ fontWeight: 400, color: '#94a3b8' }}>어구 {gearMembers.length}개</span>
                </div>
                {parentMember && (
                  <div style={{ fontSize: 9, color: '#fbbf24' }}>모선: {parentMember.name || parentMember.mmsi}</div>
                )}
                {selectedGearGroup === name && gearMembers.slice(0, 5).map(m => (
                  <div key={m.mmsi} style={{ fontSize: 9, color: '#7ea8c4', marginTop: 1 }}>
                    · {m.name || m.mmsi}
                  </div>
                ))}
                <div style={{ fontSize: 8, color: '#4a6b82', marginTop: 3 }}>클릭하여 선택/해제</div>
              </div>
            </Popup>
          );
        }
        return null;
      })()}

      {/* ── 연관 대상 트레일 + 마커 (비재생 모드) ── */}
      {selectedGearGroup && !historyActive && hasCorrelationTracks && (
        <Source id="correlation-trails" type="geojson" data={correlationTrailGeoJson}>
          <Layer id="correlation-trails-line" type="line" paint={{
            'line-color': ['get', 'color'], 'line-width': 2, 'line-opacity': 0.6,
            'line-dasharray': [6, 3],
          }} />
        </Source>
      )}
      {selectedGearGroup && !historyActive && (
        <Source id="correlation-vessels" type="geojson" data={correlationVesselGeoJson}>
          <Layer id="correlation-vessels-icon" type="symbol" layout={{
            'icon-image': ['case', ['==', ['get', 'isVessel'], 1], 'ship-triangle', 'gear-diamond'],
            'icon-size': ['case', ['==', ['get', 'isVessel'], 1], 0.7, 0.5],
            'icon-rotate': ['case', ['==', ['get', 'isVessel'], 1], ['get', 'cog'], 0],
            'icon-rotation-alignment': 'map',
            'icon-allow-overlap': true,
          }} paint={{
            'icon-color': ['get', 'color'],
            'icon-halo-color': 'rgba(0,0,0,0.6)',
            'icon-halo-width': 1,
          }} />
          <Layer id="correlation-vessels-label" type="symbol" layout={{
            'text-field': ['get', 'name'],
            'text-size': 8,
            'text-offset': [0, 1.5],
            'text-allow-overlap': false,
          }} paint={{
            'text-color': ['get', 'color'],
            'text-halo-color': 'rgba(0,0,0,0.8)',
            'text-halo-width': 1,
          }} />
        </Source>
      )}

      {/* ── 모델 배지 (비재생 모드) ── */}
      {selectedGearGroup && !historyActive && (
        <Source id="model-badges" type="geojson" data={modelBadgesGeoJson}>
          {MODEL_ORDER.map((model, i) => (
            enabledModels.has(model) ? (
              <Layer key={`badge-${model}`} id={`model-badge-${model}`} type="circle"
                filter={['==', ['get', `m${i}`], 1]}
                paint={{
                  'circle-radius': 3,
                  'circle-color': MODEL_COLORS[model] ?? '#94a3b8',
                  'circle-stroke-width': 0.5,
                  'circle-stroke-color': 'rgba(0,0,0,0.6)',
                  'circle-translate': [10 + i * 7, -6],
                }}
              />
            ) : null
          ))}
        </Source>
      )}

      {/* ── 호버 하이라이트 (비재생 모드) ── */}
      {hoveredMmsi && !historyActive && (
        <Source id="hover-highlight-point" type="geojson" data={hoverHighlightGeoJson}>
          <Layer id="hover-highlight-glow" type="circle" paint={{
            'circle-radius': 14, 'circle-color': '#ffffff', 'circle-opacity': 0.25,
            'circle-blur': 0.8,
          }} />
          <Layer id="hover-highlight-ring" type="circle" paint={{
            'circle-radius': 8, 'circle-color': 'transparent',
            'circle-stroke-width': 2, 'circle-stroke-color': '#ffffff',
          }} />
        </Source>
      )}
      {hoveredMmsi && !historyActive && (
        <Source id="hover-highlight-trail" type="geojson" data={hoverHighlightTrailGeoJson}>
          <Layer id="hover-highlight-trail-line" type="line" paint={{
            'line-color': '#ffffff', 'line-width': 3, 'line-opacity': 0.7,
          }} />
        </Source>
      )}
    </>
  );
};

export default FleetClusterMapLayers;
