import type { FleetCompany } from '../../services/vesselAnalysis';
import type { VesselAnalysisDto } from '../../types';
import type { UseGroupPolygonsResult } from '../../hooks/useGroupPolygons';
import type { FleetListItem } from './fleetClusterTypes';
import { panelStyle, headerStyle, toggleButtonStyle } from './fleetClusterConstants';
import GearGroupSection from './GearGroupSection';

interface FleetGearListPanelProps {
  fleetList: FleetListItem[];
  companies: Map<number, FleetCompany>;
  analysisMap: Map<string, VesselAnalysisDto>;
  inZoneGearGroups: UseGroupPolygonsResult['gearInZoneGroups'];
  outZoneGearGroups: UseGroupPolygonsResult['gearOutZoneGroups'];
  activeSection: string | null;
  expandedFleet: number | null;
  expandedGearGroup: string | null;
  hoveredFleetId: number | null;
  onToggleSection: (key: string) => void;
  onExpandFleet: (id: number | null) => void;
  onHoverFleet: (id: number | null) => void;
  onFleetZoom: (id: number) => void;
  onGearGroupZoom: (name: string) => void;
  onExpandGearGroup: (name: string | null) => void;
  onShipSelect: (mmsi: string) => void;
}

const FleetGearListPanel = ({
  fleetList,
  companies,
  analysisMap,
  inZoneGearGroups,
  outZoneGearGroups,
  activeSection,
  expandedFleet,
  expandedGearGroup,
  hoveredFleetId,
  onToggleSection,
  onExpandFleet,
  onHoverFleet,
  onFleetZoom,
  onGearGroupZoom,
  onExpandGearGroup,
  onShipSelect,
}: FleetGearListPanelProps) => {
  return (
    <div style={panelStyle}>
      {/* ── 선단 현황 섹션 ── */}
      <div style={{ ...headerStyle, cursor: 'pointer' }} onClick={() => onToggleSection('fleet')}>
        <span style={{ fontWeight: 700, color: '#63b3ed', letterSpacing: 0.5 }}>
          선단 현황 ({fleetList.length}개)
        </span>
        <button type="button" style={toggleButtonStyle} aria-label="선단 현황 접기/펴기">
          {activeSection === 'fleet' ? '▲' : '▼'}
        </button>
      </div>
      {activeSection === 'fleet' && (
        <div style={{ padding: '4px 0', overflowY: 'auto', flex: 1 }}>
          {fleetList.length === 0 ? (
            <div style={{ color: '#64748b', textAlign: 'center', padding: '8px 10px' }}>
              선단 데이터 없음
            </div>
          ) : (
            fleetList.map(({ id, mmsiList, label, color, members }) => {
              const company = companies.get(id);
              const companyName = company?.nameCn ?? label ?? `선단 #${id}`;
              const isOpen = expandedFleet === id;
              const isHovered = hoveredFleetId === id;

              const mainMembers = members.filter(m => {
                const dto = analysisMap.get(m.mmsi);
                return dto?.algorithms.fleetRole.role === 'LEADER' || dto?.algorithms.fleetRole.role === 'MEMBER';
              });
              const displayMembers = mainMembers.length > 0 ? mainMembers : members;

              return (
                <div key={id}>
                  <div
                    onMouseEnter={() => onHoverFleet(id)}
                    onMouseLeave={() => onHoverFleet(null)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 4, padding: '4px 10px',
                      cursor: 'pointer',
                      backgroundColor: isHovered ? 'rgba(255,255,255,0.06)' : 'transparent',
                      borderLeft: isOpen ? `2px solid ${color}` : '2px solid transparent',
                      transition: 'background-color 0.1s',
                    }}
                  >
                    <span onClick={() => onExpandFleet(isOpen ? null : id)}
                      style={{ color: '#94a3b8', fontSize: 9, flexShrink: 0, cursor: 'pointer' }}>
                      {isOpen ? '▾' : '▸'}
                    </span>
                    <span style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: color, flexShrink: 0 }} />
                    <span onClick={() => onExpandFleet(isOpen ? null : id)}
                      style={{ flex: 1, color: '#e2e8f0', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', cursor: 'pointer' }}
                      title={company ? `${company.nameCn} / ${company.nameEn}` : companyName}>
                      {companyName}
                    </span>
                    <span style={{ color: '#64748b', fontSize: 10, flexShrink: 0 }}>({mmsiList.length}척)</span>
                    <button type="button" onClick={e => { e.stopPropagation(); onFleetZoom(id); }}
                      style={{ background: 'none', border: '1px solid rgba(99,179,237,0.3)', borderRadius: 3, color: '#63b3ed', fontSize: 9, cursor: 'pointer', padding: '1px 4px', flexShrink: 0 }}
                      title="이 선단으로 지도 이동">
                      zoom
                    </button>
                  </div>

                  {isOpen && (
                    <div style={{ paddingLeft: 22, paddingRight: 10, paddingBottom: 6, fontSize: 10, color: '#94a3b8', borderLeft: `2px solid ${color}33`, marginLeft: 10 }}>
                      <div style={{ color: '#64748b', fontSize: 9, marginBottom: 3 }}>선박:</div>
                      {displayMembers.map(m => {
                        const dto = analysisMap.get(m.mmsi);
                        const role = dto?.algorithms.fleetRole.role ?? m.role;
                        const displayName = m.name || m.mmsi;
                        return (
                          <div key={m.mmsi} style={{ display: 'flex', alignItems: 'center', gap: 4, marginBottom: 2 }}>
                            <span style={{ flex: 1, color: '#cbd5e1', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                              {displayName}
                            </span>
                            <span style={{ color: role === 'LEADER' ? '#fbbf24' : '#64748b', fontSize: 9, flexShrink: 0 }}>
                              ({role === 'LEADER' ? 'MAIN' : 'SUB'})
                            </span>
                            <button type="button" onClick={() => onShipSelect(m.mmsi)}
                              style={{ background: 'none', border: 'none', color: '#63b3ed', fontSize: 10, cursor: 'pointer', padding: '0 2px', flexShrink: 0 }}
                              title="선박으로 이동" aria-label={`${displayName} 선박으로 이동`}>
                              ▶
                            </button>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              );
            })
          )}
        </div>
      )}

      {/* ── 조업구역내 어구 ── */}
      <GearGroupSection
        groups={inZoneGearGroups}
        sectionKey="inZone"
        sectionLabel={`조업구역내 어구 (${inZoneGearGroups.length}개)`}
        accentColor="#dc2626"
        hoverBgColor="rgba(220,38,38,0.06)"
        isActive={activeSection === 'inZone'}
        expandedGroup={expandedGearGroup}
        onToggleSection={() => onToggleSection('inZone')}
        onToggleGroup={(name) => onExpandGearGroup(expandedGearGroup === name ? null : name)}
        onGroupZoom={onGearGroupZoom}
        onShipSelect={onShipSelect}
      />

      {/* ── 비허가 어구 ── */}
      <GearGroupSection
        groups={outZoneGearGroups}
        sectionKey="outZone"
        sectionLabel={`비허가 어구 (${outZoneGearGroups.length}개)`}
        accentColor="#f97316"
        hoverBgColor="rgba(255,255,255,0.04)"
        isActive={activeSection === 'outZone'}
        expandedGroup={expandedGearGroup}
        onToggleSection={() => onToggleSection('outZone')}
        onToggleGroup={(name) => onExpandGearGroup(expandedGearGroup === name ? null : name)}
        onGroupZoom={onGearGroupZoom}
        onShipSelect={onShipSelect}
      />
    </div>
  );
};

export default FleetGearListPanel;
