import { useState, useEffect } from 'react';
import type { Incident } from './IncidentsLeftPanel';
import {
  fetchPredictionAnalyses,
  fetchSensitiveResources,
  fetchSensitiveResourcesGeojson,
} from '@tabs/prediction/services/predictionApi';
import type {
  PredictionAnalysis,
  SensitiveResourceCategory,
  SensitiveResourceFeatureCollection,
} from '@tabs/prediction/services/predictionApi';
import { fetchNearbyOrgs } from '../services/incidentsApi';
import type { NearbyOrgItem } from '../services/incidentsApi';

export type ViewMode = 'overlay' | 'split2' | 'split3';

export interface AnalysisSection {
  key: string;
  icon: string;
  title: string;
  color: string;
  colorRgb: string;
  totalLabel: string;
  items: AnalysisItem[];
}

interface IncidentsRightPanelProps {
  incident: Incident | null;
  viewMode: ViewMode;
  onViewModeChange: (mode: ViewMode) => void;
  onRunAnalysis: (sections: AnalysisSection[], sensitiveCount: number) => void;
  analysisActive: boolean;
  onCloseAnalysis: () => void;
  onCheckedPredsChange?: (
    checked: Array<{ id: string; acdntSn: number; predRunSn: number | null; occurredAt: string }>,
  ) => void;
  onSensitiveDataChange?: (
    geojson: SensitiveResourceFeatureCollection | null,
    checkedCategories: Set<string>,
    categoryOrder: string[],
  ) => void;
  selectedVessel: { lat: number; lng: number; name?: string } | null;
}

interface AnalysisItem {
  id: string;
  name: string;
  sub: string;
  checked: boolean;
}

/* ── 카테고리 → 이모지 매핑 (prediction LeftPanel의 CATEGORY_ICON_MAP 기반, 미사용 보존) ── */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const CATEGORY_ICON: Record<string, string> = {
  어장정보: '🐟',
  양식장: '🦪',
  양식어업: '🦪',
  어류양식장: '🐟',
  패류양식장: '🦪',
  해조류양식장: '🌿',
  가두리양식장: '🔲',
  갑각류양식장: '🦐',
  기타양식장: '📦',
  영세어업: '🎣',
  유어장: '🎣',
  수산시장: '🐟',
  인공어초: '🪸',
  암초: '🪨',
  침선: '🚢',
  해수욕장: '🏖',
  갯바위낚시: '🪨',
  선상낚시: '🚤',
  마리나항: '⛵',
  무역항: '🚢',
  연안항: '⛵',
  국가어항: '⚓',
  지방어항: '⚓',
  어항: '⚓',
  항만구역: '⚓',
  항로: '🚢',
  정박지: '⛵',
  항로표지: '🔴',
  해수취수시설: '💧',
  '취수구·배수구': '🚰',
  LNG: '⚡',
  발전소: '🔌',
  '발전소·산단': '🏭',
  임해공단: '🏭',
  저유시설: '🛢',
  '해저케이블·배관': '🔌',
  갯벌: '🪨',
  해안선_ESI: '🏖',
  보호지역: '🛡',
  해양보호구역: '🌿',
  철새도래지: '🐦',
  습지보호구역: '🏖',
  보호종서식지: '🐢',
  '보호종 서식지': '🐢',
};

/* ── 헬퍼: 활성 모델 문자열 ─────────────────────── */
function getActiveModels(p: PredictionAnalysis): string {
  const models = [
    p.kospsStatus && p.kospsStatus !== 'pending' && p.kospsStatus !== 'none' ? 'KOSPS' : null,
    p.poseidonStatus && p.poseidonStatus !== 'pending' && p.poseidonStatus !== 'none'
      ? 'POSEIDON'
      : null,
    p.opendriftStatus && p.opendriftStatus !== 'pending' && p.opendriftStatus !== 'none'
      ? 'OpenDrift'
      : null,
  ]
    .filter(Boolean)
    .join('+');
  return models || '분석중';
}

/* ── HNS/구난 섹션 (미개발, 고정 구조만 유지) ────── */
const STATIC_SECTIONS = [
  {
    key: 'hns',
    icon: '🧪',
    title: 'HNS 대기확산',
    color: 'var(--color-accent)',
    colorRgb: '6,182,212',
  },
  {
    key: 'rsc',
    icon: '🚨',
    title: '긴급구난',
    color: 'var(--color-accent)',
    colorRgb: '6,182,212',
  },
];

/* ── Component ───────────────────────────────────── */

export function IncidentsRightPanel({
  incident,
  viewMode,
  onViewModeChange,
  onRunAnalysis,
  analysisActive,
  onCloseAnalysis,
  onCheckedPredsChange,
  onSensitiveDataChange,
  selectedVessel,
}: IncidentsRightPanelProps) {
  const [predItems, setPredItems] = useState<PredictionAnalysis[]>([]);
  const [checkedPredIds, setCheckedPredIds] = useState<Set<string>>(new Set());
  const [sensCategories, setSensCategories] = useState<SensitiveResourceCategory[]>([]);
  const [checkedSensCategories, setCheckedSensCategories] = useState<Set<string>>(new Set());
  const [sensitiveGeojson, setSensitiveGeojson] =
    useState<SensitiveResourceFeatureCollection | null>(null);
  const [nearbyRadius, setNearbyRadius] = useState(50);
  const [nearbyOrgs, setNearbyOrgs] = useState<NearbyOrgItem[]>([]);
  const [nearbyLoading, setNearbyLoading] = useState(false);

  useEffect(() => {
    if (!incident) {
      void Promise.resolve().then(() => {
        setPredItems([]);
        setSensCategories([]);
        setSensitiveGeojson(null);
        onCheckedPredsChange?.([]);
        onSensitiveDataChange?.(null, new Set(), []);
      });
      return;
    }
    const acdntSn = parseInt(incident.id, 10);
    fetchPredictionAnalyses({ acdntSn })
      .then((items) => {
        setPredItems(items);
        const allIds = new Set(items.map((i) => String(i.predRunSn ?? i.acdntSn)));
        setCheckedPredIds(allIds);
        onCheckedPredsChange?.(
          items.map((p) => ({
            id: String(p.predRunSn ?? p.acdntSn),
            acdntSn: p.acdntSn,
            predRunSn: p.predRunSn,
            occurredAt: p.occurredAt,
          })),
        );
      })
      .catch(() => setPredItems([]));
    Promise.all([fetchSensitiveResources(acdntSn), fetchSensitiveResourcesGeojson(acdntSn)])
      .then(([cats, geojson]) => {
        const allCategories = new Set(cats.map((c) => c.category));
        setSensCategories(cats);
        setCheckedSensCategories(allCategories);
        setSensitiveGeojson(geojson);
        onSensitiveDataChange?.(
          geojson,
          allCategories,
          cats.map((c) => c.category),
        );
      })
      .catch(() => {
        setSensCategories([]);
        setSensitiveGeojson(null);
      });
  }, [incident?.id]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (!selectedVessel) {
      void Promise.resolve().then(() => {
        setNearbyOrgs([]);
        setNearbyLoading(false);
      });
      return;
    }
    void Promise.resolve().then(() => setNearbyLoading(true));
    fetchNearbyOrgs(selectedVessel.lat, selectedVessel.lng, nearbyRadius)
      .then(setNearbyOrgs)
      .catch(() => setNearbyOrgs([]))
      .finally(() => setNearbyLoading(false));
  }, [selectedVessel, nearbyRadius]);

  const togglePredItem = (id: string) => {
    setCheckedPredIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      const newChecked = predItems
        .filter((p) => next.has(String(p.predRunSn ?? p.acdntSn)))
        .map((p) => ({
          id: String(p.predRunSn ?? p.acdntSn),
          acdntSn: p.acdntSn,
          predRunSn: p.predRunSn,
          occurredAt: p.occurredAt,
        }));
      onCheckedPredsChange?.(newChecked);
      return next;
    });
  };

  const removePredItem = (id: string) => {
    setPredItems((prev) => {
      const next = prev.filter((p) => String(p.predRunSn ?? p.acdntSn) !== id);
      onCheckedPredsChange?.(
        next
          .filter((p) => checkedPredIds.has(String(p.predRunSn ?? p.acdntSn)))
          .map((p) => ({
            id: String(p.predRunSn ?? p.acdntSn),
            acdntSn: p.acdntSn,
            predRunSn: p.predRunSn,
            occurredAt: p.occurredAt,
          })),
      );
      return next;
    });
    setCheckedPredIds((prev) => {
      const next = new Set(prev);
      next.delete(id);
      return next;
    });
  };

  const toggleSensCategory = (category: string) => {
    setCheckedSensCategories((prev) => {
      const next = new Set(prev);
      if (next.has(category)) {
        next.delete(category);
      } else {
        next.add(category);
      }
      onSensitiveDataChange?.(
        sensitiveGeojson,
        next,
        sensCategories.map((c) => c.category),
      );
      return next;
    });
  };

  /* 유출유 섹션을 AnalysisSection 형태로 변환 (통합 분석 실행 콜백용) */
  const oilSection: AnalysisSection = {
    key: 'oil',
    icon: '🛢',
    title: '유출유 확산예측',
    color: 'var(--color-accent)',
    colorRgb: '249,115,22',
    totalLabel: `전체 ${predItems.length}건`,
    items: predItems.map((p) => {
      const id = String(p.predRunSn ?? p.acdntSn);
      const dateStr = p.runDtm ? p.runDtm.slice(0, 10) : '';
      const oilLabel = p.oilType || '유출유';
      return {
        id,
        name: `${dateStr} ${oilLabel} 확산예측`.trim(),
        sub: `${getActiveModels(p)}${p.volume != null ? ` · ${p.volume}kL` : ''}`,
        checked: checkedPredIds.has(id),
      };
    }),
  };

  if (!incident) {
    return (
      <div className="flex flex-col items-center justify-center bg-bg-surface border-l border-stroke w-full h-full">
        <div className="text-center text-fg-disabled text-label-2">
          <div className="text-[32px] mb-2 opacity-30">📊</div>
          좌측에서 사고를 선택하면
          <br />
          통합분석 조회가 표시됩니다
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col bg-bg-surface border-l border-stroke overflow-hidden h-full w-[280px] min-w-[280px]">
      {/* Header */}
      <div className="px-[14px] py-2.5 border-b border-stroke shrink-0">
        <div className="text-caption font-bold mb-0.5">🔬 통합분석 조회</div>
        <div className="text-caption text-fg-disabled">
          선택: <span className="text-fg-disabled">{incident.name}</span>
        </div>
      </div>

      {/* Scrollable Content */}
      <div
        className="flex-1 h-0 overflow-y-auto flex flex-col gap-2 p-2"
        style={{ scrollbarWidth: 'thin', scrollbarColor: 'var(--stroke-light) transparent' }}
      >
        {/* 유출유 확산예측 섹션 */}
        {(() => {
          const sec = oilSection;
          const checkedCount = sec.items.filter((it) => it.checked).length;
          return (
            <div className="bg-bg-elevated border border-stroke rounded-md p-2.5">
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center gap-1.5">
                  {/* <span className="text-body-2">{sec.icon}</span> */}
                  <span className="text-caption">{sec.title}</span>
                </div>
                <button
                  className="text-caption font-semibold cursor-pointer"
                  style={{
                    padding: '3px 10px',
                    borderRadius: '4px',
                    border: '1px solid var(--stroke-default)',
                    color: sec.color,
                  }}
                >
                  조회
                </button>
              </div>
              <div className="flex flex-col gap-1">
                {sec.items.length === 0 ? (
                  <div className="text-caption text-fg-disabled text-center py-1.5">
                    예측 실행 이력이 없습니다
                  </div>
                ) : (
                  sec.items.map((item) => (
                    <div
                      key={item.id}
                      className="flex items-center gap-1.5"
                      style={{
                        padding: '5px 8px',
                        border: '1px solid var(--stroke-default)',
                        borderRadius: '4px',
                      }}
                    >
                      <input
                        type="checkbox"
                        checked={item.checked}
                        onChange={() => togglePredItem(item.id)}
                        className="shrink-0"
                        style={{ accentColor: sec.color }}
                      />
                      <div className="flex-1 min-w-0">
                        <div className="text-caption font-semibold whitespace-nowrap overflow-hidden text-ellipsis">
                          {item.name}
                        </div>
                        <div className="text-fg-disabled font-mono text-caption">{item.sub}</div>
                      </div>
                      <span
                        onClick={() => removePredItem(item.id)}
                        title="제거"
                        className="text-caption cursor-pointer text-fg-disabled shrink-0"
                      >
                        ✕
                      </span>
                    </div>
                  ))
                )}
              </div>
              <div className="flex items-center gap-1.5 mt-1.5 text-caption text-fg-disabled">
                선택: <b style={{ color: sec.color }}>{checkedCount}건</b> · {sec.totalLabel}
              </div>
            </div>
          );
        })()}

        {/* HNS 대기확산 / 긴급구난 섹션 (미개발 - 구조 유지) */}
        {STATIC_SECTIONS.map((sec) => (
          <div key={sec.key} className="bg-bg-elevated border border-stroke rounded-md p-2.5">
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center gap-1.5">
                {/* <span className="text-body-2">{sec.icon}</span> */}
                <span className="text-caption">{sec.title}</span>
              </div>
              <button
                className="text-caption font-semibold cursor-pointer"
                style={{
                  padding: '3px 10px',
                  borderRadius: '4px',
                  border: '1px solid var(--stroke-default)',
                  color: sec.color,
                }}
              >
                조회
              </button>
            </div>
            <div className="text-caption text-fg-disabled text-center py-1.5">준비 중입니다</div>
            <div className="flex items-center gap-1.5 mt-1.5 text-caption text-fg-disabled">
              선택: <b style={{ color: sec.color }}>0건</b> · 전체 0건
            </div>
          </div>
        ))}

        {/* 민감자원 */}
        <div className="bg-bg-elevated border border-stroke rounded-md p-2.5">
          <div className="flex items-center gap-1.5 mb-2">
            {/* <span className="text-body-2">🐟</span> */}
            <span className="text-caption">민감자원</span>
          </div>
          <div className="flex flex-col gap-[3px]">
            {sensCategories.length === 0 ? (
              <div className="text-caption text-fg-disabled text-center py-1.5">
                해당 사고 영역의 민감자원이 없습니다
              </div>
            ) : (
              sensCategories.map((cat) => {
                const areaLabel =
                  cat.totalArea != null
                    ? `${cat.totalArea.toLocaleString('ko-KR', { maximumFractionDigits: 0 })}ha`
                    : `${cat.count}개소`;
                return (
                  <label
                    key={cat.category}
                    className="flex items-center cursor-pointer text-caption gap-[5px]"
                    style={{ padding: '3px 0' }}
                  >
                    <input
                      type="checkbox"
                      checked={checkedSensCategories.has(cat.category)}
                      onChange={() => toggleSensCategory(cat.category)}
                      style={{ accentColor: 'var(--color-accent)' }}
                    />
                    <span
                      style={{
                        width: 6,
                        height: 6,
                        borderRadius: '50%',
                        background: 'var(--color-accent)',
                        flexShrink: 0,
                        display: 'inline-block',
                      }}
                    />
                    <span className="flex-1">{cat.category}</span>
                    <span className="text-fg-disabled font-mono shrink-0">({areaLabel})</span>
                  </label>
                );
              })
            )}
          </div>
        </div>

        {/* 근처 방제자원 */}
        <div className="bg-bg-elevated border border-stroke rounded-md p-2.5">
          <div className="flex items-center gap-1.5 mb-2">
            <span className="text-caption font-bold text-color-accent">근처 방제자원</span>
            {nearbyOrgs.length > 0 && (
              <span className="ml-auto text-caption font-mono text-color-accent">
                {nearbyOrgs.length}개
              </span>
            )}
          </div>

          {!selectedVessel ? (
            <div className="py-2.5 text-center text-fg-disabled text-caption leading-[1.7]">
              <div className="text-xl mb-1 opacity-40">🚢</div>
              지도에서 선박을 클릭하면
              <br />
              부근 방제자원이 표시됩니다
            </div>
          ) : nearbyLoading ? (
            <div className="py-2.5 text-center text-fg-disabled text-caption">조회 중...</div>
          ) : nearbyOrgs.length === 0 ? (
            <div className="py-2.5 text-center text-fg-disabled text-caption">
              반경 내 방제자원 없음
            </div>
          ) : (
            <div className="flex flex-col max-h-[200px] overflow-y-auto">
              {nearbyOrgs.map((org) => (
                <div
                  key={org.orgSn}
                  className="flex items-start gap-1.5 px-[2px] py-[5px]"
                  style={{ borderBottom: '1px solid var(--stroke-default)' }}
                >
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-1 mb-[2px]">
                      <span
                        className="text-caption px-[4px] py-[1px] rounded-[2px] font-bold shrink-0 text-color-accent"
                        style={{ background: 'rgba(6,182,212,0.1)' }}
                      >
                        {org.orgTp}
                      </span>
                      <span className="text-caption font-bold text-fg truncate">{org.orgNm}</span>
                    </div>
                    <div className="text-caption text-fg-disabled">
                      {org.areaNm}
                      {org.totalAssets > 0 ? ` · 장비 ${org.totalAssets}개` : ''}
                    </div>
                  </div>
                  <span className="text-caption font-mono text-color-accent shrink-0">
                    {org.distanceNm.toFixed(1)} nm
                  </span>
                </div>
              ))}
            </div>
          )}

          {/* Radius slider */}
          <div className="mt-2 pt-2" style={{ borderTop: '1px solid var(--stroke-default)' }}>
            <div className="flex items-center justify-between mb-[5px]">
              <span className="text-caption text-fg-disabled">탐색 반경</span>
              <span className="text-caption font-bold font-mono text-color-accent">
                {nearbyRadius} nm
              </span>
            </div>
            <input
              type="range"
              min={10}
              max={150}
              value={nearbyRadius}
              step={10}
              onChange={(e) => setNearbyRadius(Number(e.target.value))}
              className="w-full outline-none cursor-pointer"
              style={{
                height: '4px',
                background: 'var(--stroke-default)',
                borderRadius: '2px',
                accentColor: 'var(--color-accent)',
              }}
            />
          </div>
        </div>
      </div>

      {/* Footer */}
      <div className="flex flex-col gap-1.5 p-2.5 border-t border-stroke shrink-0">
        {/* View Mode */}
        <div className="flex gap-1">
          {[
            { mode: 'overlay' as ViewMode, icon: '🗂', label: '오버레이' },
            { mode: 'split2' as ViewMode, icon: '◫', label: '2분할' },
            { mode: 'split3' as ViewMode, icon: '⊞', label: '3분할' },
          ].map((v) => {
            const isActive = viewMode === v.mode;
            return (
              <button
                key={v.mode}
                onClick={() => onViewModeChange(v.mode)}
                className="flex-1 text-caption cursor-pointer"
                style={{
                  padding: '6px',
                  borderRadius: 'var(--radius-sm)',
                  fontWeight: isActive ? 700 : 600,
                  background: isActive ? 'rgba(6,182,212,0.1)' : 'var(--bg-card)',
                  border: isActive
                    ? '1px solid rgba(6,182,212,0.3)'
                    : '1px solid var(--stroke-default)',
                  color: isActive ? 'var(--color-accent)' : 'var(--fg-disabled)',
                }}
              >
                {/* {v.icon} */}
                {v.label}
              </button>
            );
          })}
        </div>

        {/* Execute */}
        <button
          onClick={() => {
            if (analysisActive) {
              onCloseAnalysis();
              return;
            }
            const checkedOilItems = oilSection.items.filter((it) => it.checked);
            const checkedSections =
              checkedOilItems.length > 0 ? [{ ...oilSection, items: checkedOilItems }] : [];
            const sensChecked = checkedSensCategories.size;
            onRunAnalysis(checkedSections, sensChecked);
          }}
          className="w-full text-label-2 font-bold cursor-pointer"
          style={{
            padding: '8px',
            background: analysisActive ? 'rgba(239,68,68,0.1)' : 'rgba(6,182,212,0.1)',
            border: analysisActive
              ? '1px solid rgba(239,68,68,0.3)'
              : '1px solid rgba(6,182,212,0.3)',
            borderRadius: 'var(--radius-sm)',
            color: analysisActive ? '#f87171' : 'var(--color-accent)',
          }}
        >
          {analysisActive ? '✕ 분석 닫기' : '🔬 통합 분석 비교 실행'}
        </button>
      </div>
    </div>
  );
}
