import { useState } from 'react'
import type { Incident } from './IncidentsLeftPanel'

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
}

/* ── Analysis section data ───────────────────────── */

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

const SECTION_DATA: {
  key: string
  icon: string
  title: string
  color: string
  colorRgb: string
  totalLabel: string
  items: AnalysisItem[]
}[] = [
  {
    key: 'oil',
    icon: '🛢',
    title: '유출유 확산예측',
    color: '#f97316',
    colorRgb: '249,115,22',
    totalLabel: '전체 8건',
    items: [
      { id: 'o1', name: '여수항 BUNKER-C 확산', sub: 'KOSPS+OpenDrift · 150kL', checked: true },
      { id: 'o2', name: '여수항 DIESEL 확산', sub: 'KOSPS · 30kL', checked: false },
    ],
  },
  {
    key: 'hns',
    icon: '🧪',
    title: 'HNS 대기확산',
    color: '#a855f7',
    colorRgb: '168,85,247',
    totalLabel: '전체 6건',
    items: [
      { id: 'h1', name: '울산 톨루엔 대기확산', sub: 'ALOHA · IDLH 1.2km', checked: true },
    ],
  },
  {
    key: 'rsc',
    icon: '🚨',
    title: '긴급구난',
    color: '#06b6d4',
    colorRgb: '6,182,212',
    totalLabel: '전체 5건',
    items: [
      { id: 'r1', name: '여수 해상구난 SAR #12', sub: 'SAROPS · 확률맵', checked: true },
    ],
  },
]

interface SensitiveResource {
  id: string
  name: string
  area: string
  checked: boolean
}

const MOCK_SENSITIVE: SensitiveResource[] = [
  { id: 's1', name: '돌산 어장 (김·전복)', area: '131ha', checked: true },
  { id: 's2', name: '여수 갯벌 생태계', area: '4,013ha', checked: true },
  { id: 's3', name: '여수 해수욕장 3개소', area: '', checked: false },
  { id: 's4', name: '오동도 해상공원', area: '125ha', checked: false },
  { id: 's5', name: '여수 취수시설', area: '2개소', checked: false },
]

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

export function IncidentsRightPanel({
  incident, viewMode, onViewModeChange, onRunAnalysis, analysisActive, onCloseAnalysis
}: IncidentsRightPanelProps) {
  const [sections, setSections] = useState(SECTION_DATA)
  const [sensitive, setSensitive] = useState(MOCK_SENSITIVE)
  const [nearbyRadius, setNearbyRadius] = useState(50)

  const toggleItem = (sectionKey: string, itemId: string) => {
    setSections(prev =>
      prev.map(s =>
        s.key === sectionKey
          ? { ...s, items: s.items.map(it => (it.id === itemId ? { ...it, checked: !it.checked } : it)) }
          : s
      )
    )
  }

  const removeItem = (sectionKey: string, itemId: string) => {
    setSections(prev =>
      prev.map(s =>
        s.key === sectionKey ? { ...s, items: s.items.filter(it => it.id !== itemId) } : s
      )
    )
  }

  const toggleSensitive = (id: string) => {
    setSensitive(prev => prev.map(s => (s.id === id ? { ...s, checked: !s.checked } : s)))
  }

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

  return (
    <div className="flex flex-col bg-bg-1 border-l border-border overflow-hidden h-full w-[280px] min-w-[280px]">
      {/* Header */}
      <div className="px-[14px] py-2.5 border-b border-border shrink-0">
        <div className="text-xs font-bold mb-0.5">
          🔬 통합분석 조회
        </div>
        <div className="text-[9px] text-text-3">
          선택: <b className="text-primary-cyan">{incident.name}</b>
        </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(--bdL) transparent' }}>
        {/* Analysis Sections (oil / hns / rsc) */}
        {sections.map(sec => {
          const checkedCount = sec.items.filter(it => it.checked).length
          return (
            <div key={sec.key} className="bg-bg-2 border border-border rounded-md p-2.5">
              {/* Section Header */}
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center gap-1.5">
                  <span className="text-sm">{sec.icon}</span>
                  <span className="text-xs font-bold" style={{ color: sec.color }}>
                    {sec.title}
                  </span>
                </div>
                <button className="text-[10px] font-semibold cursor-pointer"
                  style={{
                    padding: '3px 10px', borderRadius: '4px',
                    background: `rgba(${sec.colorRgb},0.1)`,
                    border: `1px solid rgba(${sec.colorRgb},0.25)`,
                    color: sec.color,
                  }}>
                  📋 조회
                </button>
              </div>

              {/* Items */}
              <div className="flex flex-col gap-1">
                {sec.items.map(item => (
                  <div key={item.id} className="flex items-center gap-1.5"
                    style={{
                      padding: '5px 8px',
                      background: `rgba(${sec.colorRgb},0.06)`,
                      border: `1px solid rgba(${sec.colorRgb},0.15)`,
                      borderRadius: '4px',
                    }}>
                    <input
                      type="checkbox"
                      checked={item.checked}
                      onChange={() => toggleItem(sec.key, item.id)}
                      className="shrink-0"
                      style={{ accentColor: sec.color }}
                    />
                    <div className="flex-1 min-w-0">
                      <div className="text-[10px] font-semibold whitespace-nowrap overflow-hidden text-ellipsis">
                        {item.name}
                      </div>
                      <div className="text-text-3 font-mono text-[8px]">
                        {item.sub}
                      </div>
                    </div>
                    <span
                      onClick={() => removeItem(sec.key, item.id)}
                      title="제거"
                      className="text-[10px] cursor-pointer text-text-3 shrink-0"
                    >
                      ✕
                    </span>
                  </div>
                ))}
              </div>

              {/* Status */}
              <div className="flex items-center gap-1.5 mt-1.5 text-[9px] text-text-3">
                선택: <b style={{ color: sec.color }}>{checkedCount}건</b> · {sec.totalLabel}
              </div>
            </div>
          )
        })}

        {/* 민감자원 */}
        <div className="bg-bg-2 border border-border rounded-md p-2.5">
          <div className="flex items-center gap-1.5 mb-2">
            <span className="text-sm">🐟</span>
            <span className="text-xs font-bold text-[#22c55e]">
              민감자원
            </span>
          </div>
          <div className="flex flex-col gap-[3px]">
            {sensitive.map(res => (
              <label key={res.id} className="flex items-center cursor-pointer text-[9px] gap-[5px] rounded-[3px]"
                style={{
                  padding: '4px 6px', background: 'rgba(34,197,94,0.06)',
                }}>
                <input
                  type="checkbox"
                  checked={res.checked}
                  onChange={() => toggleSensitive(res.id)}
                  style={{ accentColor: 'var(--green)' }}
                />
                {res.name}
                {res.area && (
                  <span className="text-text-3 font-mono">({res.area})</span>
                )}
              </label>
            ))}
          </div>
        </div>

        {/* 근처 방제자원 */}
        <div className="bg-bg-2 border border-border rounded-md p-2.5">
          <div className="flex items-center gap-1.5 mb-2">
            <span className="text-sm">🛡</span>
            <span className="text-xs font-bold text-[#f59e0b]">
              근처 방제자원
            </span>
          </div>

          {/* Empty state */}
          <div className="py-2.5 text-center text-text-3 text-[10px] leading-[1.7]">
            <div className="text-xl mb-1 opacity-40">🚢</div>
            지도에서 선박을 클릭하면<br />부근 방제자원이 표시됩니다
          </div>

          {/* Radius slider */}
          <div className="mt-2 pt-2" style={{ borderTop: '1px solid rgba(245,158,11,0.1)' }}>
            <div className="flex items-center justify-between mb-[5px]">
              <span className="text-[9px] text-text-3">탐색 반경</span>
              <span className="text-[10px] font-bold font-mono text-[#f59e0b]">
                {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(--bd)', borderRadius: '2px',
                accentColor: '#f59e0b',
              }}
            />
          </div>
        </div>
      </div>

      {/* Footer */}
      <div className="flex flex-col gap-1.5 p-2.5 border-t border-border 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-[10px] cursor-pointer"
                style={{
                  padding: '6px', borderRadius: 'var(--rS)',
                  fontWeight: isActive ? 700 : 600,
                  background: isActive ? 'rgba(6,182,212,0.1)' : 'var(--bg3)',
                  border: isActive ? '1px solid rgba(6,182,212,0.3)' : '1px solid var(--bd)',
                  color: isActive ? 'var(--cyan)' : 'var(--t3)',
                }}>
                {v.icon} {v.label}
              </button>
            )
          })}
        </div>

        {/* Execute */}
        <button onClick={() => {
          if (analysisActive) { onCloseAnalysis(); return }
          const checkedSections = sections.filter(s => s.items.some(it => it.checked))
          const sensChecked = sensitive.filter(s => s.checked).length
          onRunAnalysis(checkedSections, sensChecked)
        }} className="w-full text-[11px] font-bold cursor-pointer"
          style={{
            padding: '8px',
            background: analysisActive
              ? 'linear-gradient(135deg,rgba(239,68,68,0.15),rgba(239,68,68,0.1))'
              : 'linear-gradient(135deg,rgba(6,182,212,0.15),rgba(59,130,246,0.1))',
            border: analysisActive ? '1px solid rgba(239,68,68,0.3)' : '1px solid rgba(6,182,212,0.3)',
            borderRadius: 'var(--rS)',
            color: analysisActive ? '#f87171' : 'var(--cyan)',
          }}>
          {analysisActive ? '✕ 분석 닫기' : '🔬 통합 분석 비교 실행'}
        </button>
      </div>
    </div>
  )
}
