import { useMemo, useCallback, useState } from 'react';
import { ScatterplotLayer } from '@deck.gl/layers';
import { BaseMap } from '@common/components/map/BaseMap';
import { DeckGLOverlay } from '@common/components/map/DeckGLOverlay';
import { FlyToController } from '@common/components/map/FlyToController';
import type { AssetOrgCompat } from '../services/assetsApi';
import { typeColor } from './assetTypes';
import { hexToRgba } from '@common/components/map/mapUtils';

interface AssetMapProps {
  organizations: AssetOrgCompat[];
  selectedOrg: AssetOrgCompat;
  onSelectOrg: (o: AssetOrgCompat) => void;
  regionFilter: string;
  onRegionFilterChange: (v: string) => void;
}

function AssetMap({
  organizations: orgs,
  selectedOrg,
  onSelectOrg,
  regionFilter,
  onRegionFilterChange,
}: AssetMapProps) {
  // 선택 항목이 실제로 바뀔 때만 flyTo (첫 렌더에서는 이동하지 않음)
  // 첫 렌더 ID를 useState lazy init으로 동결 → 그 외엔 useMemo로 target 파생
  const [initialId] = useState(selectedOrg.id);
  const flyTarget = useMemo(
    () =>
      selectedOrg.id === initialId
        ? null
        : { lng: selectedOrg.lng, lat: selectedOrg.lat, zoom: 10 },
    [selectedOrg, initialId],
  );

  const handleClick = useCallback(
    (org: AssetOrgCompat) => {
      onSelectOrg(org);
    },
    [onSelectOrg],
  );

  const markerLayer = useMemo(
    () =>
      new ScatterplotLayer({
        id: 'asset-orgs',
        data: orgs,
        getPosition: (d: AssetOrgCompat) => [d.lng, d.lat],
        getRadius: (d: AssetOrgCompat) => {
          const baseRadius = d.pinSize === 'hq' ? 14 : d.pinSize === 'lg' ? 10 : 7;
          const isSelected = selectedOrg.id === d.id;
          return isSelected ? baseRadius + 4 : baseRadius;
        },
        getFillColor: (d: AssetOrgCompat) => {
          const tc = typeColor(d.type);
          const isSelected = selectedOrg.id === d.id;
          return hexToRgba(isSelected ? tc.selected : tc.border, isSelected ? 229 : 178);
        },
        getLineColor: (d: AssetOrgCompat) => {
          const tc = typeColor(d.type);
          const isSelected = selectedOrg.id === d.id;
          return hexToRgba(isSelected ? tc.selected : tc.border, isSelected ? 255 : 200);
        },
        getLineWidth: (d: AssetOrgCompat) => (selectedOrg.id === d.id ? 3 : 2),
        stroked: true,
        radiusMinPixels: 4,
        radiusMaxPixels: 20,
        radiusUnits: 'pixels',
        pickable: true,
        onClick: (info: { object?: AssetOrgCompat }) => {
          if (info.object) handleClick(info.object);
        },
        updateTriggers: {
          getRadius: [selectedOrg.id],
          getFillColor: [selectedOrg.id],
          getLineColor: [selectedOrg.id],
          getLineWidth: [selectedOrg.id],
        },
      }),
    [orgs, selectedOrg, handleClick],
  );

  return (
    <div className="w-full h-full relative">
      <BaseMap center={[35.9, 127.8]} zoom={7}>
        <DeckGLOverlay layers={[markerLayer]} />
        <FlyToController target={flyTarget} duration={800} />
      </BaseMap>

      {/* 지역 필터 */}
      <div className="absolute top-3 left-3 z-[1000] flex gap-1">
        {[
          { value: 'all', label: '전체' },
          { value: '남해', label: '남해청' },
          { value: '서해', label: '서해청' },
          { value: '중부', label: '중부청' },
          { value: '동해', label: '동해청' },
          { value: '제주', label: '제주청' },
        ].map((r) => (
          <button
            key={r.value}
            onClick={() => onRegionFilterChange(r.value)}
            className={`px-2.5 py-1.5 text-caption font-bold rounded font-korean transition-colors ${
              regionFilter === r.value
                ? 'bg-[color-mix(in_srgb,var(--color-accent)_20%,transparent)] text-color-accent border border-[color-mix(in_srgb,var(--color-accent)_40%,transparent)]'
                : 'bg-bg-base/80 text-fg-sub border border-stroke hover:bg-bg-surface-hover/80'
            }`}
          >
            {r.label}
          </button>
        ))}
      </div>

      {/* 범례 */}
      <div className="absolute bottom-3 left-3 z-[1000] bg-bg-base/90 border border-stroke rounded-sm p-2.5 backdrop-blur-sm">
        <div className="text-caption text-fg-disabled font-bold mb-1.5 font-korean">범례</div>
        {[
          '해경관할',
          '해경경찰서',
          '파출소',
          '관련기관',
          '해양환경공단',
          '업체',
          '지자체',
          '기름저장시설',
          '정유사',
          '해군',
          '기타',
        ].map((label, i) => (
          <div key={i} className="flex items-center gap-1.5 mb-0.5 last:mb-0">
            <span
              className="w-2.5 h-2.5 rounded-full inline-block flex-shrink-0"
              style={{ background: typeColor(label).border }}
            />
            <span className="text-caption text-fg-sub font-korean">{label}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

export default AssetMap;
