import { useState } from 'react';
import type { VesselPosition } from '@/types/vessel';
import { getShipKindLabel } from '@components/common/map/VesselLayer';
import { formatDateTime, displayVal } from '../IncidentsView';

type DetTab = 'info' | 'nav' | 'spec' | 'ins' | 'dg';
const TAB_LABELS: { key: DetTab; label: string }[] = [
  { key: 'info', label: '상세정보' },
  { key: 'nav', label: '항해정보' },
  { key: 'spec', label: '선박제원' },
  { key: 'ins', label: '보험정보' },
  { key: 'dg', label: '위험물정보' },
];

export function VesselDetailModal({
  vessel: v,
  onClose,
}: {
  vessel: VesselPosition;
  onClose: () => void;
}) {
  const [tab, setTab] = useState<DetTab>('info');

  return (
    <div
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
      className="fixed inset-0 z-[10000] flex items-center justify-center"
      style={{
        background: 'rgba(0,0,0,0.65)',
        backdropFilter: 'blur(6px)',
      }}
    >
      <div
        className="flex flex-col overflow-hidden bg-bg-surface border border-stroke"
        style={{
          width: 560,
          height: '85vh',
          borderRadius: 14,
          boxShadow: '0 24px 64px rgba(0,0,0,0.7)',
        }}
      >
        {/* Header */}
        <div
          className="shrink-0 flex items-center justify-between bg-bg-surface border-b border-stroke"
          style={{ padding: '14px 18px' }}
        >
          <div className="flex items-center gap-[10px]">
            <span className="text-lg">{v.nationalCode ?? '🚢'}</span>
            <div>
              <div className="text-title-3 font-[800] text-fg">
                {v.shipNm ?? '(이름 없음)'}
              </div>
              <div className="text-caption text-fg-disabled font-mono">
                MMSI: {v.mmsi} · IMO: {displayVal(v.imo)}
              </div>
            </div>
          </div>
          <span onClick={onClose} className="text-title-2 cursor-pointer text-fg-disabled">
            ✕
          </span>
        </div>

        {/* Tabs */}
        <div
          className="shrink-0 flex gap-0.5 overflow-x-auto bg-bg-base border-b border-stroke"
          style={{ padding: '0 18px' }}
        >
          {TAB_LABELS.map((t) => (
            <button
              key={t.key}
              onClick={() => setTab(t.key)}
              className="text-label-2 cursor-pointer whitespace-nowrap"
              style={{
                padding: '8px 11px',
                fontWeight: tab === t.key ? 600 : 400,
                color: tab === t.key ? 'var(--color-accent)' : 'var(--fg-disabled)',
                borderBottom:
                  tab === t.key ? '2px solid var(--color-accent)' : '2px solid transparent',
                background: 'none',
                border: 'none',
                transition: '0.15s',
              }}
            >
              {t.label}
            </button>
          ))}
        </div>

        {/* Body */}
        <div
          className="flex-1 overflow-y-auto flex flex-col"
          style={{
            padding: '16px 18px',
            gap: 14,
            scrollbarWidth: 'thin',
            scrollbarColor: 'var(--stroke-default) transparent',
          }}
        >
          {tab === 'info' && <TabInfo v={v} />}
          {tab === 'nav' && <TabNav v={v} />}
          {tab === 'spec' && <TabSpec v={v} />}
          {tab === 'ins' && <TabInsurance v={v} />}
          {tab === 'dg' && <TabDangerous v={v} />}
        </div>
      </div>
    </div>
  );
}

/* ── shared section helpers ──────────────────────── */
function Sec({
  title,
  borderColor,
  bgColor,
  badge,
  children,
}: {
  title: string;
  borderColor?: string;
  bgColor?: string;
  badge?: React.ReactNode;
  children: React.ReactNode;
}) {
  return (
    <div
      style={{
        border: `1px solid ${borderColor || 'var(--stroke-default)'}`,
        borderRadius: 8,
        overflow: 'hidden',
      }}
    >
      <div
        className="text-label-2 font-bold text-fg-sub flex items-center justify-between"
        style={{
          padding: '8px 12px',
          background: bgColor || 'var(--bg-base)',
          borderBottom: `1px solid ${borderColor || 'var(--stroke-default)'}`,
        }}
      >
        <span>{title}</span>
        {badge}
      </div>
      {children}
    </div>
  );
}

function Grid({ children }: { children: React.ReactNode }) {
  return <div className="grid grid-cols-2">{children}</div>;
}

function Cell({
  label,
  value,
  span,
  color,
}: {
  label: string;
  value: string;
  span?: boolean;
  color?: string;
}) {
  return (
    <div
      style={{
        padding: '8px 12px',
        borderBottom: '1px solid color-mix(in srgb, var(--stroke-default) 60%, transparent)',
        borderRight: span
          ? 'none'
          : '1px solid color-mix(in srgb, var(--stroke-default) 60%, transparent)',
        gridColumn: span ? '1 / -1' : undefined,
      }}
    >
      <div className="text-caption text-fg-disabled" style={{ marginBottom: 2 }}>
        {label}
      </div>
      <div className="text-label-2 font-semibold font-mono" style={{ color: color || 'var(--fg)' }}>
        {value}
      </div>
    </div>
  );
}

function StatusBadge({ label, color }: { label: string; color: string }) {
  return (
    <span
      className="text-caption font-bold"
      style={{
        padding: '2px 6px',
        borderRadius: 8,
        marginLeft: 'auto',
        background: `color-mix(in srgb, ${color} 25%, transparent)`,
        color,
      }}
    >
      {label}
    </span>
  );
}

/* ── Tab 0: 상세정보 ─────────────────────────────── */
function TabInfo({ v }: { v: VesselPosition }) {
  const speed = v.sog !== undefined ? `${v.sog.toFixed(1)} kn` : '-';
  const heading = v.heading ?? v.cog;
  const headingText = heading !== undefined ? `${Math.round(heading)}°` : '-';
  return (
    <>
      <div
        className="w-full rounded-lg overflow-hidden flex items-center justify-center text-[60px] text-fg-disabled bg-bg-base"
        style={{ height: 160 }}
      >
        🚢
      </div>

      <Sec title="📡 실시간 현황">
        <Grid>
          <Cell label="선박상태" value={displayVal(v.status)} />
          <Cell
            label="속도 / 항로"
            value={`${speed} / ${headingText}`}
            color="var(--color-accent)"
          />
          <Cell label="위도" value={`${v.lat.toFixed(4)}°N`} />
          <Cell label="경도" value={`${v.lon.toFixed(4)}°E`} />
          <Cell label="흘수" value={v.draught !== undefined ? `${v.draught} m` : '-'} />
          <Cell label="수신시간" value={v.lastUpdate ? formatDateTime(v.lastUpdate) : '-'} />
        </Grid>
      </Sec>

      <Sec title="🚢 항해 일정">
        <Grid>
          <Cell label="출항지" value="-" />
          <Cell label="입항지" value={displayVal(v.destination)} />
          <Cell label="출항일시" value="-" />
          <Cell label="입항일시(ETA)" value="-" />
        </Grid>
      </Sec>
    </>
  );
}

/* ── Tab 1: 항해정보 ─────────────────────────────── */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function TabNav(_props: { v: VesselPosition }) {
  const hours = ['08', '09', '10', '11', '12', '13', '14'];
  const heights = [45, 60, 78, 82, 70, 85, 75];
  const colors = [
    'color-mix(in srgb, var(--color-success) 30%, transparent)',
    'color-mix(in srgb, var(--color-success) 40%, transparent)',
    'color-mix(in srgb, var(--color-info) 40%, transparent)',
    'color-mix(in srgb, var(--color-info) 50%, transparent)',
    'color-mix(in srgb, var(--color-info) 50%, transparent)',
    'color-mix(in srgb, var(--color-info) 60%, transparent)',
    'color-mix(in srgb, var(--color-accent) 50%, transparent)',
  ];

  return (
    <>
      <Sec title="🗺 최근 항적 (24h)">
        <div
          className="flex items-center justify-center relative overflow-hidden bg-bg-base"
          style={{ height: 180 }}
        >
          <svg
            width="100%"
            height="100%"
            viewBox="0 0 400 180"
            style={{ position: 'absolute', inset: 0 }}
          >
            <path
              d="M50,150 C80,140 120,100 160,95 S240,70 280,50 S340,30 370,20"
              fill="none"
              stroke="var(--color-accent)"
              strokeWidth="2"
              strokeDasharray="6,3"
              opacity=".6"
            />
            <circle cx="50" cy="150" r="4" fill="var(--fg-disabled)" />
            <circle cx="160" cy="95" r="3" fill="var(--color-accent)" opacity=".5" />
            <circle cx="280" cy="50" r="3" fill="var(--color-accent)" opacity=".5" />
            <circle cx="370" cy="20" r="5" fill="var(--color-accent)" />
            <text
              x="45"
              y="168"
              fill="var(--fg-disabled)"
              fontSize="9"
              fontFamily="var(--font-mono)"
            >
              08:00
            </text>
            <text
              x="150"
              y="113"
              fill="var(--fg-disabled)"
              fontSize="9"
              fontFamily="var(--font-mono)"
            >
              10:30
            </text>
            <text
              x="270"
              y="68"
              fill="var(--fg-disabled)"
              fontSize="9"
              fontFamily="var(--font-mono)"
            >
              12:45
            </text>
            <text
              x="350"
              y="16"
              fill="var(--color-accent)"
              fontSize="9"
              fontFamily="var(--font-mono)"
            >
              현재
            </text>
          </svg>
        </div>
      </Sec>

      <Sec title="📊 속도 이력">
        <div className="p-3 bg-bg-base">
          <div className="flex items-end gap-1.5" style={{ height: 80 }}>
            {hours.map((h, i) => (
              <div key={h} className="flex-1 flex flex-col items-center gap-0.5">
                <div
                  className="w-full"
                  style={{
                    background: colors[i],
                    borderRadius: '2px 2px 0 0',
                    height: `${heights[i]}%`,
                  }}
                />
                <span className="text-caption text-fg-disabled">{h}</span>
              </div>
            ))}
          </div>
          <div className="text-center text-caption text-fg-disabled" style={{ marginTop: 6 }}>
            평균: <b className="text-color-info">8.4 kn</b> · 최대:{' '}
            <b className="text-color-accent">11.2 kn</b>
          </div>
        </div>
      </Sec>

      <div className="flex gap-[8px]">
        <ActionBtn
          icon="🔍"
          label="전체 항적 조회"
          bg="color-mix(in srgb, var(--color-tertiary) 10%, transparent)"
          bd="color-mix(in srgb, var(--color-tertiary) 25%, transparent)"
          fg="var(--color-tertiary)"
        />
        <ActionBtn
          icon="📐"
          label="항로 예측"
          bg="color-mix(in srgb, var(--color-accent) 10%, transparent)"
          bd="color-mix(in srgb, var(--color-accent) 25%, transparent)"
          fg="var(--color-accent)"
        />
      </div>
    </>
  );
}

/* ── Tab 2: 선박제원 ─────────────────────────────── */
function TabSpec({ v }: { v: VesselPosition }) {
  const loa = v.length !== undefined ? `${v.length} m` : '-';
  const beam = v.width !== undefined ? `${v.width} m` : '-';
  return (
    <>
      <Sec title="📐 선체 제원">
        <Grid>
          <Cell label="선종" value={displayVal(getShipKindLabel(v.shipKindCode) ?? v.shipTy)} />
          <Cell label="선적국" value={displayVal(v.nationalCode)} />
          <Cell label="총톤수 (GT)" value="-" />
          <Cell label="재화중량 (DWT)" value="-" />
          <Cell label="전장 (LOA)" value={loa} />
          <Cell label="선폭" value={beam} />
          <Cell label="건조년도" value="-" />
          <Cell label="건조 조선소" value="-" />
        </Grid>
      </Sec>

      <Sec title="📡 통신 / 식별">
        <Grid>
          <Cell label="MMSI" value={String(v.mmsi)} />
          <Cell label="IMO" value={displayVal(v.imo)} />
          <Cell label="호출부호" value="-" />
          <Cell label="선급" value="-" />
        </Grid>
      </Sec>

      <Sec title="⚠ 위험물 적재 정보">
        <div className="p-[10px_12px] bg-bg-base">
          <div
            className="flex items-center gap-2 rounded"
            style={{
              padding: '5px 8px',
              background: 'color-mix(in srgb, var(--color-danger) 6%, transparent)',
              border: '1px solid color-mix(in srgb, var(--color-danger) 12%, transparent)',
            }}
          >
            <span className="text-label-1">🛢</span>
            <div className="flex-1">
              <div className="text-caption font-semibold text-fg">-</div>
              <div className="text-caption text-fg-disabled">정보 없음</div>
            </div>
          </div>
        </div>
      </Sec>
    </>
  );
}

/* ── Tab 3: 보험정보 ─────────────────────────────── */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function TabInsurance(_props: { v: VesselPosition }) {
  return (
    <>
      <Sec title="🏢 선주 / 운항사">
        <Grid>
          <Cell label="선주" value="대한해운(주)" />
          <Cell label="운항사" value="대한해운(주)" />
          <Cell label="P&I Club" value="한국선주상호보험" span />
        </Grid>
      </Sec>

      <Sec
        title="🚢 선체보험 (H&M)"
        borderColor="color-mix(in srgb, var(--color-accent) 20%, transparent)"
        bgColor="color-mix(in srgb, var(--color-accent) 6%, transparent)"
        badge={<StatusBadge label="유효" color="var(--color-success)" />}
      >
        <Grid>
          <Cell label="보험사" value="삼성화재해상보험" />
          <Cell label="보험가액" value="USD 28,500,000" color="var(--color-accent)" />
          <Cell label="보험기간" value="2025.01 ~ 2026.01" color="var(--color-success)" />
          <Cell label="면책금" value="USD 150,000" />
        </Grid>
      </Sec>

      <Sec
        title="📦 화물보험 (Cargo)"
        borderColor="color-mix(in srgb, var(--color-tertiary) 20%, transparent)"
        bgColor="color-mix(in srgb, var(--color-tertiary) 6%, transparent)"
        badge={<StatusBadge label="유효" color="var(--color-success)" />}
      >
        <Grid>
          <Cell label="보험사" value="DB손해보험" />
          <Cell label="보험가액" value="USD 42,100,000" color="var(--color-tertiary)" />
          <Cell label="적하물" value="벙커C유 72,850톤" />
          <Cell label="조건" value="ICC(A) All Risks" />
        </Grid>
      </Sec>

      <Sec
        title="🛢 유류오염배상 (CLC/IOPC)"
        borderColor="color-mix(in srgb, var(--color-danger) 20%, transparent)"
        bgColor="color-mix(in srgb, var(--color-danger) 6%, transparent)"
        badge={<StatusBadge label="유효" color="var(--color-success)" />}
      >
        <Grid>
          <Cell label="배상보증서" value="유효 (2025-12-31)" color="var(--color-success)" />
          <Cell label="발급기관" value="한국선주상호보험" />
          <Cell label="CLC 한도" value="89.77M SDR" color="var(--color-danger)" />
          <Cell label="IOPC 기금" value="203M SDR" />
          <Cell label="추가기금" value="750M SDR" />
          <Cell label="총 배상한도" value="약 1,042.77M SDR" color="var(--color-warning)" />
        </Grid>
      </Sec>

      <div
        className="rounded-sm text-caption text-fg-disabled"
        style={{
          padding: '8px 10px',
          background: 'color-mix(in srgb, var(--color-info) 4%, transparent)',
          border: '1px solid color-mix(in srgb, var(--color-info) 10%, transparent)',
          lineHeight: 1.6,
        }}
      >
        💡 보험정보는 한국해운조합(KSA) Open API 및 해양수산부 선박정보시스템 연동 데이터입니다.
        실시간 갱신 주기: 24시간
      </div>
    </>
  );
}

/* ── Tab 4: 위험물정보 ───────────────────────────── */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function TabDangerous(_props: { v: VesselPosition }) {
  return (
    <>
      <Sec
        title="⚠ 위험물 화물 신고정보"
        bgColor="color-mix(in srgb, var(--color-warning) 6%, transparent)"
        badge={
          <span
            className="text-caption font-bold text-color-danger"
            style={{
              padding: '2px 6px',
              background: 'color-mix(in srgb, var(--color-danger) 15%, transparent)',
              borderRadius: 8,
            }}
          >
            PORT-MIS
          </span>
        }
      >
        <Grid>
          <Cell label="화물명" value="-" color="var(--color-warning)" />
          <Cell label="컨테이너갯수/총량" value="— / 72,850 톤" />
          <Cell label="하역업체코드" value="KRY-2847" />
          <Cell label="하역기간" value="02-26 ~ 02-28" />
          <Cell label="신고업체코드" value="DHW-0412" />
          <Cell label="사용장소(부두)" value="여수 1부두 2선석" />
          <Cell label="신고일시" value="2026-02-24 09:30" />
          <Cell label="전출항지" value="울산항" />
          <Cell label="EDI ID" value="EDI-2026022400187" />
          <Cell label="수리일시" value="2026-02-24 10:15" />
        </Grid>
      </Sec>

      <Sec title="📋 화물창 및 첨부">
        <div
          className="flex items-center justify-between gap-2 bg-bg-base"
          style={{ padding: '12px' }}
        >
          <div className="flex items-center gap-2 text-label-2 whitespace-nowrap">
            <span className="text-fg-disabled">화물창 2개이상 여부</span>
            <span className="inline-flex items-center gap-1">
              <span
                className="flex items-center justify-center text-caption text-color-accent"
                style={{
                  width: 14,
                  height: 14,
                  borderRadius: '50%',
                  border: '2px solid var(--color-accent)',
                }}
              >
                ✓
              </span>
              <span className="font-semibold text-caption text-color-accent">예</span>
            </span>
          </div>
          <button
            className="text-caption font-semibold text-color-info cursor-pointer whitespace-nowrap shrink-0 rounded"
            style={{
              padding: '6px 14px',
              background: 'color-mix(in srgb, var(--color-info) 10%, transparent)',
              border: '1px solid color-mix(in srgb, var(--color-info) 20%, transparent)',
            }}
          >
            📎 첨부[화물적부도]
          </button>
        </div>
      </Sec>

      <Sec
        title="🔥 IMO 위험물 분류"
        borderColor="color-mix(in srgb, var(--color-danger) 20%, transparent)"
        bgColor="color-mix(in srgb, var(--color-danger) 6%, transparent)"
      >
        <Grid>
          <Cell label="IMO Class" value="Class 3" color="var(--color-danger)" />
          <Cell label="분류" value="인화성 액체" />
          <Cell label="UN No." value="UN 1993" />
          <Cell label="포장등급" value="III" />
          <Cell label="인화점" value="60°C 이상" color="var(--color-warning)" />
          <Cell label="해양오염물질" value="해당 (P)" color="var(--color-danger)" />
        </Grid>
      </Sec>

      <Sec
        title="🚨 비상 대응 요약 (EmS)"
        bgColor="color-mix(in srgb, var(--color-caution) 6%, transparent)"
      >
        <div className="flex flex-col gap-1.5 bg-bg-base" style={{ padding: '10px 12px' }}>
          <EmsRow
            icon="🔥"
            label="화재시"
            value="포말소화제, CO₂ 소화기 사용 · 물분무 냉각"
            bg="color-mix(in srgb, var(--color-danger) 5%, transparent)"
            bd="color-mix(in srgb, var(--color-danger) 12%, transparent)"
          />
          <EmsRow
            icon="🌊"
            label="유출시"
            value="오일펜스 전개 · 유흡착재 투입 · 해상 기름 회수"
            bg="color-mix(in srgb, var(--color-info) 5%, transparent)"
            bd="color-mix(in srgb, var(--color-info) 12%, transparent)"
          />
          <EmsRow
            icon="🫁"
            label="보호장비"
            value="내화학장갑, 보안경, 방독마스크 · 레벨C 보호복"
            bg="color-mix(in srgb, var(--color-tertiary) 5%, transparent)"
            bd="color-mix(in srgb, var(--color-tertiary) 12%, transparent)"
          />
        </div>
      </Sec>

      <div
        className="rounded-sm text-caption text-fg-disabled"
        style={{
          padding: '8px 10px',
          background: 'color-mix(in srgb, var(--color-warning) 4%, transparent)',
          border: '1px solid color-mix(in srgb, var(--color-warning) 10%, transparent)',
          lineHeight: 1.6,
        }}
      >
        💡 위험물정보는 PORT-MIS(항만운영정보시스템) 위험물 반입신고 데이터 연동입니다. IMDG Code
        최신 개정판(Amendment 42-24) 기준.
      </div>
    </>
  );
}

function EmsRow({
  icon,
  label,
  value,
  bg,
  bd,
}: {
  icon: string;
  label: string;
  value: string;
  bg: string;
  bd: string;
}) {
  return (
    <div
      className="flex items-center gap-2 rounded"
      style={{
        padding: '6px 10px',
        background: bg,
        border: `1px solid ${bd}`,
      }}
    >
      <span className="text-title-4">{icon}</span>
      <div>
        <div className="text-caption text-fg-disabled">{label}</div>
        <div className="text-caption font-semibold text-fg">{value}</div>
      </div>
    </div>
  );
}

function ActionBtn({
  icon,
  label,
  bg,
  bd,
  fg,
}: {
  icon: string;
  label: string;
  bg: string;
  bd: string;
  fg: string;
}) {
  return (
    <button
      className="flex-1 text-caption font-bold cursor-pointer text-center rounded-sm"
      style={{
        padding: 6,
        background: bg,
        border: `1px solid ${bd}`,
        color: fg,
      }}
    >
      {icon} {label}
    </button>
  );
}
