import { useState, useEffect, useCallback } from 'react';
import { useVesselSignals } from '@common/hooks/useVesselSignals';
import type { MapBounds } from '@/types/vessel';
import { useSubMenu } from '@common/hooks/useSubMenu';
import { MapView } from '@components/common/map/MapView';
import { RescueTheoryView } from './RescueTheoryView';
import { RescueScenarioView } from './RescueScenarioView';
import { fetchGscAccidents } from '@components/prediction/services/predictionApi';
import type { GscAccidentListItem } from '@interfaces/prediction/PredictionInterface';
import { TopInfoBar } from './contents/TopInfoBar';
import { LeftPanel } from './contents/LeftPanel';
import { RightPanel } from './contents/RightPanel';
import { BottomBar } from './contents/BottomBar';
import { RescueListView } from './contents/RescueListView';

import type { AccidentType } from '@/types/rescue/RescueType';
/* eslint-disable react-refresh/only-export-components */

/* ─── Types ─── */
export type AnalysisTab = 'rescue' | 'damageStability' | 'longitudinalStrength';

/* ─── 사고 유형 데이터 ─── */
export const accidentTypes: {
  id: AccidentType;
  label: string;
  eng: string;
  icon: string;
  desc: string;
}[] = [
  { id: 'collision', label: '충돌', eng: 'Collision', icon: '💥', desc: '외력에 의한 선체 손상' },
  { id: 'grounding', label: '좌초', eng: 'Grounding', icon: '🪨', desc: '해저 접촉/암초 좌초' },
  { id: 'turning', label: '선회', eng: 'Turning', icon: '🔄', desc: '급격한 방향전환 사고' },
  { id: 'capsizing', label: '전복', eng: 'Capsizing', icon: '🔃', desc: '복원력 상실에 의한 전복' },
  {
    id: 'sharpTurn',
    label: '급선회',
    eng: 'Hard Turn',
    icon: '↩️',
    desc: '고속 급선회에 의한 경사',
  },
  { id: 'flooding', label: '침수', eng: 'Flooding', icon: '🌊', desc: '해수 유입에 의한 침수' },
  { id: 'sinking', label: '침몰', eng: 'Sinking', icon: '⬇️', desc: '부력 상실에 의한 침몰' },
];

export const analysisTabs: { id: AnalysisTab; label: string; icon: string }[] = [
  { id: 'rescue', label: '구난분석', icon: '🚨' },
  { id: 'damageStability', label: '손상복원성', icon: '⚖' },
  { id: 'longitudinalStrength', label: '종강도', icon: '📏' },
];

/* ─── 사고 유형별 파라미터 ─── */
export const rscTypeData: Record<
  AccidentType,
  {
    zone: string;
    gm: string;
    list: string;
    trim: string;
    buoy: number;
    incident: string;
    survivors: number;
    total: number;
    missing: number;
    oilRate: string;
  }
> = {
  collision: {
    zone: 'PREDICTED\nDAMAGE ZONE',
    gm: '0.8',
    list: '15.0',
    trim: '2.5',
    buoy: 30,
    incident: 'M/V SEA GUARDIAN 충돌 사고',
    survivors: 15,
    total: 20,
    missing: 5,
    oilRate: '100L/min',
  },
  grounding: {
    zone: 'GROUNDING\nIMPACT AREA',
    gm: '1.2',
    list: '8.0',
    trim: '3.8',
    buoy: 45,
    incident: 'M/V OCEAN STAR 좌초 사고',
    survivors: 22,
    total: 25,
    missing: 3,
    oilRate: '50L/min',
  },
  turning: {
    zone: 'PREDICTED\nDRIFT PATH',
    gm: '1.5',
    list: '12.0',
    trim: '0.8',
    buoy: 65,
    incident: 'M/V PACIFIC WAVE 선회 사고',
    survivors: 18,
    total: 18,
    missing: 0,
    oilRate: '0L/min',
  },
  capsizing: {
    zone: 'CAPSIZING\nRISK ZONE',
    gm: '0.2',
    list: '45.0',
    trim: '1.2',
    buoy: 10,
    incident: 'M/V GRAND FORTUNE 전복 사고',
    survivors: 8,
    total: 15,
    missing: 7,
    oilRate: '200L/min',
  },
  sharpTurn: {
    zone: 'VESSEL\nTURNING CIRCLE',
    gm: '0.6',
    list: '25.0',
    trim: '0.5',
    buoy: 50,
    incident: 'M/V BLUE HORIZON 급선회 사고',
    survivors: 20,
    total: 20,
    missing: 0,
    oilRate: '0L/min',
  },
  flooding: {
    zone: 'FLOODING\nSPREAD AREA',
    gm: '0.5',
    list: '18.0',
    trim: '4.2',
    buoy: 20,
    incident: 'M/V EASTERN GLORY 침수 사고',
    survivors: 12,
    total: 16,
    missing: 4,
    oilRate: '80L/min',
  },
  sinking: {
    zone: 'PREDICTED\nSINKING AREA',
    gm: '0.1',
    list: '35.0',
    trim: '6.0',
    buoy: 5,
    incident: 'M/V HARMONY 침몰 사고',
    survivors: 10,
    total: 22,
    missing: 12,
    oilRate: '350L/min',
  },
};

/* ─── 색상 헬퍼 ─── */
export function gmColor(v: string) {
  const n = parseFloat(v);
  return n < 1.0
    ? 'var(--color-danger)'
    : n < 1.5
      ? 'var(--color-caution)'
      : 'var(--color-success)';
}
export function listColor(v: string) {
  const n = parseFloat(v);
  return n > 20 ? 'var(--color-danger)' : n > 10 ? 'var(--color-caution)' : 'var(--color-success)';
}
export function trimColor(v: string) {
  const n = parseFloat(v);
  return n > 3 ? 'var(--color-danger)' : n > 1.5 ? 'var(--color-caution)' : 'var(--color-success)';
}
export function buoyColor(v: number) {
  return v < 30 ? 'var(--color-danger)' : v < 50 ? 'var(--color-caution)' : 'var(--color-success)';
}


export function RescueView() {
  const { activeSubTab } = useSubMenu('rescue');
  const [activeType, setActiveType] = useState<AccidentType>('collision');
  const [activeAnalysis, setActiveAnalysis] = useState<AnalysisTab>('rescue');
  const [incidents, setIncidents] = useState<GscAccidentListItem[]>([]);
  const [selectedAcdnt, setSelectedAcdnt] = useState<GscAccidentListItem | null>(null);
  const [incidentCoord, setIncidentCoord] = useState<{ lon: number; lat: number } | null>(null);
  const [flyToCoord, setFlyToCoord] = useState<{ lon: number; lat: number } | undefined>(undefined);
  const [isSelectingLocation, setIsSelectingLocation] = useState(false);
  const [mapBounds, setMapBounds] = useState<MapBounds | null>(null);
  const vessels = useVesselSignals(mapBounds);

  useEffect(() => {
    fetchGscAccidents()
      .then((items) => setIncidents(items))
      .catch(() => setIncidents([]));
  }, []);

  // 지도 클릭 시 좌표 선택
  const handleMapClick = useCallback((lon: number, lat: number) => {
    setIncidentCoord({ lon, lat });
    setIsSelectingLocation(false);
  }, []);

  // 사고 선택 시 좌표 자동 반영 + 지도 이동
  const handleSelectAcdnt = useCallback(
    (item: GscAccidentListItem | null) => {
      setSelectedAcdnt(item);
      if (item && item.lat != null && item.lon != null) {
        setIncidentCoord({ lon: item.lon, lat: item.lat });
        setFlyToCoord({ lon: item.lon, lat: item.lat });
      }
    },
    [],
  );

  if (activeSubTab === 'list') {
    return (
      <div className="flex flex-1 overflow-hidden">
        <RescueListView />
      </div>
    );
  }

  if (activeSubTab === 'scenario') {
    return <RescueScenarioView />;
  }

  if (activeSubTab === 'theory') {
    return <RescueTheoryView />;
  }

  return (
    <div className="flex flex-col flex-1 overflow-hidden">
      {/* 상단 사고 정보바 */}
      <TopInfoBar activeType={activeType} />

      {/* 3단 레이아웃: 사고유형 | 지도 | 분석 패널 */}
      <div className="flex flex-1 overflow-hidden">
        <LeftPanel
          activeType={activeType}
          onTypeChange={setActiveType}
          incidents={incidents}
          selectedAcdnt={selectedAcdnt}
          onSelectAcdnt={handleSelectAcdnt}
        />
        <div className="flex-1 relative overflow-hidden">
          <MapView
            incidentCoord={incidentCoord ?? undefined}
            flyToIncident={flyToCoord}
            onIncidentFlyEnd={() => setFlyToCoord(undefined)}
            isSelectingLocation={isSelectingLocation}
            onMapClick={handleMapClick}
            oilTrajectory={[]}
            enabledLayers={new Set()}
            showOverlays={false}
            vessels={vessels}
            onBoundsChange={setMapBounds}
          />
        </div>
        <RightPanel
          activeAnalysis={activeAnalysis}
          onAnalysisChange={setActiveAnalysis}
          activeType={activeType}
        />
      </div>

      {/* 하단: 이벤트 로그 + 타임라인 */}
      <BottomBar />
    </div>
  );
}
