import { useState } from 'react';
import type { GearCorrelationItem } from '../../services/vesselAnalysis';
import type { UseGroupPolygonsResult } from '../../hooks/useGroupPolygons';
import { FONT_MONO } from '../../styles/fonts';
import { MODEL_ORDER, MODEL_COLORS, MODEL_DESC } from './fleetClusterConstants';
import { useGearReplayStore } from '../../stores/gearReplayStore';

interface CorrelationPanelProps {
  selectedGearGroup: string;
  memberCount: number;
  groupPolygons: UseGroupPolygonsResult | undefined;
  correlationByModel: Map<string, GearCorrelationItem[]>;
  availableModels: { name: string; count: number; isDefault: boolean }[];
  enabledModels: Set<string>;
  enabledVessels: Set<string>;
  correlationLoading: boolean;
  hoveredTarget: { mmsi: string; model: string } | null;
  onEnabledModelsChange: (updater: (prev: Set<string>) => Set<string>) => void;
  onEnabledVesselsChange: (updater: (prev: Set<string>) => Set<string>) => void;
  onHoveredTargetChange: (target: { mmsi: string; model: string } | null) => void;
}

// Ensure MODEL_ORDER is treated as string array for Record lookups
const _MODEL_ORDER: string[] = MODEL_ORDER as unknown as string[];

const CorrelationPanel = ({
  selectedGearGroup,
  memberCount,
  groupPolygons,
  correlationByModel,
  availableModels,
  enabledModels,
  enabledVessels,
  correlationLoading,
  hoveredTarget,
  onEnabledModelsChange,
  onEnabledVesselsChange,
  onHoveredTargetChange,
}: CorrelationPanelProps) => {
  const historyActive = useGearReplayStore(s => s.historyFrames.length > 0);

  // Local tooltip state
  const [hoveredModelTip, setHoveredModelTip] = useState<string | null>(null);
  const [pinnedModelTip, setPinnedModelTip] = useState<string | null>(null);
  const activeModelTip = pinnedModelTip ?? hoveredModelTip;

  // Compute identity data from groupPolygons
  const allGroups = groupPolygons
    ? [...groupPolygons.gearInZoneGroups, ...groupPolygons.gearOutZoneGroups]
    : [];
  const group = allGroups.find(g => g.groupKey === selectedGearGroup);
  const identityVessels = group?.members.filter(m => m.isParent) ?? [];
  const identityGear = group?.members.filter(m => !m.isParent) ?? [];

  // Suppress unused MODEL_ORDER warning — used for ordering checks
  void _MODEL_ORDER;

  // Common card styles
  const cardStyle: React.CSSProperties = {
    background: 'rgba(12,24,37,0.95)',
    borderRadius: 6,
    minWidth: 160,
    maxWidth: 200,
    flexShrink: 0,
    border: '1px solid rgba(255,255,255,0.08)',
    position: 'relative',
  };

  const cardScrollStyle: React.CSSProperties = {
    padding: '6px 8px',
    maxHeight: 200,
    overflowY: 'auto',
  };

  // Model title tooltip hover/click handlers
  const handleTipHover = (model: string) => {
    if (!pinnedModelTip) setHoveredModelTip(model);
  };
  const handleTipLeave = () => {
    if (!pinnedModelTip) setHoveredModelTip(null);
  };
  const handleTipClick = (model: string) => {
    setPinnedModelTip(prev => prev === model ? null : model);
    setHoveredModelTip(null);
  };

  const renderModelTip = (model: string, color: string) => {
    if (activeModelTip !== model) return null;
    const desc = MODEL_DESC[model];
    if (!desc) return null;
    return (
      <div style={{
        position: 'absolute',
        bottom: '100%',
        left: 0,
        marginBottom: 4,
        padding: '6px 10px',
        background: 'rgba(15,23,42,0.97)',
        border: `1px solid ${color}66`,
        borderRadius: 5,
        fontSize: 9,
        color: '#e2e8f0',
        zIndex: 30,
        whiteSpace: 'nowrap',
        boxShadow: '0 2px 12px rgba(0,0,0,0.6)',
        pointerEvents: pinnedModelTip === model ? 'auto' : 'none',
      }}>
        <div style={{ fontWeight: 700, color, marginBottom: 4 }}>{desc.summary}</div>
        {desc.details.map((line, i) => (
          <div key={i} style={{ color: '#94a3b8', lineHeight: 1.5 }}>{line}</div>
        ))}
        {pinnedModelTip === model && (
          <div style={{
            color: '#64748b',
            fontSize: 8,
            marginTop: 4,
            borderTop: '1px solid rgba(255,255,255,0.06)',
            paddingTop: 3,
          }}>
            클릭하여 닫기
          </div>
        )}
      </div>
    );
  };

  // Common row renderer (correlation target — with score bar, model-independent hover)
  const toggleVessel = (mmsi: string) => {
    onEnabledVesselsChange(prev => {
      const next = new Set(prev);
      if (next.has(mmsi)) next.delete(mmsi); else next.add(mmsi);
      return next;
    });
  };

  const renderRow = (c: GearCorrelationItem, color: string, modelName: string) => {
    const pct = (c.score * 100).toFixed(0);
    const barW = Math.max(2, c.score * 30);
    const barColor = c.score >= 0.7 ? '#22c55e' : c.score >= 0.5 ? '#eab308' : '#94a3b8';
    const isVessel = c.targetType === 'VESSEL';
    const isEnabled = enabledVessels.has(c.targetMmsi);
    const isHovered = hoveredTarget?.mmsi === c.targetMmsi && hoveredTarget?.model === modelName;
    return (
      <div
        key={c.targetMmsi}
        style={{
          fontSize: 9, marginBottom: 1, display: 'flex', alignItems: 'center', gap: 3,
          padding: '1px 2px', borderRadius: 2, cursor: 'pointer',
          background: isHovered ? `${color}22` : 'transparent',
          opacity: isEnabled ? 1 : 0.5,
        }}
        onClick={() => toggleVessel(c.targetMmsi)}
        onMouseEnter={() => onHoveredTargetChange({ mmsi: c.targetMmsi, model: modelName })}
        onMouseLeave={() => onHoveredTargetChange(null)}
      >
        <input type="checkbox" checked={isEnabled} readOnly title="맵 표시"
          style={{ accentColor: color, width: 9, height: 9, flexShrink: 0, pointerEvents: 'none' }} />
        <span style={{ color: isVessel ? '#60a5fa' : '#f97316', width: 10, textAlign: 'center', flexShrink: 0 }}>
          {isVessel ? '⛴' : '◆'}
        </span>
        <span style={{ color: '#cbd5e1', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {c.targetName || c.targetMmsi}
        </span>
        <div style={{ width: 50, display: 'flex', alignItems: 'center', gap: 2, flexShrink: 0 }}>
          <div style={{ width: 24, height: 3, background: 'rgba(255,255,255,0.08)', borderRadius: 2, overflow: 'hidden' }}>
            <div style={{ width: barW, height: '100%', background: barColor, borderRadius: 2 }} />
          </div>
          <span style={{ color: barColor, fontSize: 8, minWidth: 20, textAlign: 'right' }}>{pct}%</span>
        </div>
      </div>
    );
  };

  // Member row renderer (identity model — no score, independent hover)
  const renderMemberRow = (m: { mmsi: string; name: string }, icon: string, iconColor: string) => {
    const isHovered = hoveredTarget?.mmsi === m.mmsi && hoveredTarget?.model === 'identity';
    return (
      <div
        key={m.mmsi}
        style={{
          fontSize: 9,
          marginBottom: 1,
          display: 'flex',
          alignItems: 'center',
          gap: 4,
          padding: '1px 2px',
          borderRadius: 2,
          cursor: 'default',
          background: isHovered ? 'rgba(249,115,22,0.15)' : 'transparent',
        }}
        onMouseEnter={() => onHoveredTargetChange({ mmsi: m.mmsi, model: 'identity' })}
        onMouseLeave={() => onHoveredTargetChange(null)}
      >
        <span style={{ color: iconColor, width: 10, textAlign: 'center', flexShrink: 0 }}>{icon}</span>
        <span style={{ color: '#cbd5e1', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {m.name || m.mmsi}
        </span>
      </div>
    );
  };

  return (
    <div style={{
      position: 'absolute',
      bottom: historyActive ? 120 : 20,
      left: 'calc(50% - 210px)',
      display: 'flex',
      gap: 6,
      alignItems: 'flex-start',
      zIndex: 21,
      fontFamily: FONT_MONO,
      fontSize: 10,
      color: '#e2e8f0',
      pointerEvents: 'auto',
      maxWidth: 'calc(100vw - 40px)',
      overflowX: 'auto',
      overflowY: 'visible',
    }}>
      {/* 고정: 토글 패널 */}
      <div style={{
        background: 'rgba(12,24,37,0.95)',
        border: '1px solid rgba(249,115,22,0.3)',
        borderRadius: 8,
        padding: '8px 10px',
        position: 'sticky',
        left: 0,
        minWidth: 165,
        flexShrink: 0,
        boxShadow: '0 4px 16px rgba(0,0,0,0.5)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
          <span style={{ fontWeight: 700, color: '#f97316', fontSize: 11 }}>{selectedGearGroup}</span>
          <span style={{ color: '#64748b', fontSize: 9 }}>{memberCount}개</span>
        </div>
        <div style={{ fontSize: 9, fontWeight: 700, color: '#93c5fd', marginBottom: 4 }}>폴리곤 오버레이</div>
        <label style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 9, cursor: 'pointer', marginBottom: 3 }}>
          <input
            type="checkbox"
            checked={enabledModels.has('identity')}
            onChange={() => onEnabledModelsChange(prev => {
              const next = new Set(prev);
              if (next.has('identity')) next.delete('identity');
              else next.add('identity');
              return next;
            })}
            style={{ accentColor: '#f97316', width: 11, height: 11 }}
            title="이름 기반"
          />
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#f97316', flexShrink: 0 }} />
          <span style={{ color: '#e2e8f0' }}>이름 기반</span>
          <span style={{ color: '#64748b', marginLeft: 'auto' }}>{memberCount}</span>
        </label>
        {correlationLoading && <div style={{ fontSize: 8, color: '#64748b' }}>로딩...</div>}
        {availableModels.map(m => {
          const color = MODEL_COLORS[m.name] ?? '#94a3b8';
          const modelItems = correlationByModel.get(m.name) ?? [];
          const vc = modelItems.filter(c => c.targetType === 'VESSEL').length;
          const gc = modelItems.filter(c => c.targetType !== 'VESSEL').length;
          return (
            <label key={m.name} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 9, cursor: 'pointer', marginBottom: 3 }}>
              <input type="checkbox" checked={enabledModels.has(m.name)}
                onChange={() => onEnabledModelsChange(prev => {
                  const next = new Set(prev);
                  if (next.has(m.name)) next.delete(m.name); else next.add(m.name);
                  return next;
                })}
                style={{ accentColor: color, width: 11, height: 11 }} title={m.name} />
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: color, flexShrink: 0 }} />
              <span style={{ color: '#e2e8f0', flex: 1 }}>{m.name}{m.isDefault ? '*' : ''}</span>
              <span style={{ color: '#64748b', fontSize: 8 }}>{vc}⛴{gc}◆</span>
            </label>
          );
        })}
      </div>

      {/* 이름 기반 카드 (체크 시) */}
      {enabledModels.has('identity') && (identityVessels.length > 0 || identityGear.length > 0) && (
        <div style={{ ...cardStyle, borderColor: 'rgba(249,115,22,0.25)' }}>
          {renderModelTip('identity', '#f97316')}
          <div style={cardScrollStyle}>
            <div
              style={{ display: 'flex', alignItems: 'center', gap: 4, marginBottom: 4, cursor: 'help' }}
              onMouseEnter={() => handleTipHover('identity')}
              onMouseLeave={handleTipLeave}
              onClick={() => handleTipClick('identity')}
            >
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#f97316', flexShrink: 0 }} />
              <span style={{ fontSize: 9, fontWeight: 700, color: '#f97316' }}>이름 기반</span>
            </div>
            {identityVessels.length > 0 && (
              <>
                <div style={{ fontSize: 8, color: '#64748b', marginBottom: 2 }}>연관 선박 ({identityVessels.length})</div>
                {identityVessels.map(m => renderMemberRow(m, '⛴', '#60a5fa'))}
              </>
            )}
            {identityGear.length > 0 && (
              <>
                <div style={{ fontSize: 8, color: '#64748b', marginBottom: 2, marginTop: 3 }}>연관 어구 ({identityGear.length})</div>
                {identityGear.slice(0, 12).map(m => renderMemberRow(m, '◆', '#f97316'))}
                {identityGear.length > 12 && (
                  <div style={{ fontSize: 8, color: '#4a6b82' }}>+{identityGear.length - 12}개 더</div>
                )}
              </>
            )}
          </div>
        </div>
      )}

      {/* 각 Correlation 모델 카드 (체크 시 우측에 추가) */}
      {availableModels.filter(m => enabledModels.has(m.name)).map(m => {
        const color = MODEL_COLORS[m.name] ?? '#94a3b8';
        const items = correlationByModel.get(m.name) ?? [];
        const vessels = items.filter(c => c.targetType === 'VESSEL');
        const gears = items.filter(c => c.targetType !== 'VESSEL');
        if (vessels.length === 0 && gears.length === 0) return null;
        return (
          <div key={m.name} style={{ ...cardStyle, borderColor: `${color}40` }}>
            {renderModelTip(m.name, color)}
            <div style={cardScrollStyle}>
              <div
                style={{ display: 'flex', alignItems: 'center', gap: 4, marginBottom: 4, cursor: 'help' }}
                onMouseEnter={() => handleTipHover(m.name)}
                onMouseLeave={handleTipLeave}
                onClick={() => handleTipClick(m.name)}
              >
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: color, flexShrink: 0 }} />
                <span style={{ fontSize: 9, fontWeight: 700, color }}>{m.name}{m.isDefault ? '*' : ''}</span>
              </div>
              {vessels.length > 0 && (
                <>
                  <div style={{ fontSize: 8, color: '#64748b', marginBottom: 2 }}>연관 선박 ({vessels.length})</div>
                  {vessels.slice(0, 10).map(c => renderRow(c, color, m.name))}
                  {vessels.length > 10 && (
                    <div style={{ fontSize: 8, color: '#4a6b82' }}>+{vessels.length - 10}건 더</div>
                  )}
                </>
              )}
              {gears.length > 0 && (
                <>
                  <div style={{ fontSize: 8, color: '#64748b', marginBottom: 2, marginTop: 3 }}>연관 어구 ({gears.length})</div>
                  {gears.slice(0, 10).map(c => renderRow(c, color, m.name))}
                  {gears.length > 10 && (
                    <div style={{ fontSize: 8, color: '#4a6b82' }}>+{gears.length - 10}건 더</div>
                  )}
                </>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
};

export default CorrelationPanel;
