import { useState, useEffect, useCallback } from 'react';

// TODO: 실제 API 연동 시 fetch 호출로 교체
interface VesselMonitorRow {
  institution: string;
  institutionCode: string;
  systemName: string;
  linkInfo: string;
  storagePlace: string;
  linkMethod: string;
  collectionCycle: string;
  collectionCount: string;
  isNormal: boolean;
  lastMessageTime: string;
}

/** 기관코드 → 원천기관명 매핑 */
const INSTITUTION_NAMES: Record<string, string> = {
  BS: '부산항',
  BSN: '부산신항',
  DH: '동해안',
  DS: '대산항',
  GI: '경인항',
  GIC: '경인연안',
  GS: '군산항',
  IC: '인천항',
  JDC: '진도연안',
  JJ: '제주항',
  MP: '목포항',
};

/** Mock 데이터 정의 (스크린샷 기반) */
const MOCK_DATA: Omit<VesselMonitorRow, 'institution'>[] = [
  { institutionCode: 'BS', systemName: 'VTS_AIS', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '439 / 499', isNormal: true, lastMessageTime: '2026-03-25 10:29:09' },
  { institutionCode: 'BS', systemName: 'VTS_RT', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '133 / 463', isNormal: true, lastMessageTime: '2026-03-25 10:29:09' },
  { institutionCode: 'BSN', systemName: 'VTS_AIS', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '255 / 278', isNormal: true, lastMessageTime: '2026-03-25 10:29:09' },
  { institutionCode: 'BSN', systemName: 'VTS_RT', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '133 / 426', isNormal: true, lastMessageTime: '2026-03-25 10:29:09' },
  { institutionCode: 'DH', systemName: 'VTS_AIS', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '수신대기중', collectionCount: '0', isNormal: false, lastMessageTime: '' },
  { institutionCode: 'DH', systemName: 'VTS_RT', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '수신대기중', collectionCount: '0', isNormal: false, lastMessageTime: '' },
  { institutionCode: 'DS', systemName: 'VTS_AIS', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '0', isNormal: false, lastMessageTime: '2026-03-15 15:38:57' },
  { institutionCode: 'DS', systemName: 'VTS_RT', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '0', isNormal: false, lastMessageTime: '2026-03-15 15:38:56' },
  { institutionCode: 'GI', systemName: 'VTS_AIS', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '120 / 136', isNormal: true, lastMessageTime: '2026-03-25 10:29:09' },
  { institutionCode: 'GI', systemName: 'VTS_RT', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '55 / 467', isNormal: true, lastMessageTime: '2026-03-25 10:29:09' },
  { institutionCode: 'GIC', systemName: 'VTS_AIS', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '180 / 216', isNormal: true, lastMessageTime: '2026-03-25 10:29:09' },
  { institutionCode: 'GIC', systemName: 'VTS_RT', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '수신대기중', collectionCount: '0', isNormal: false, lastMessageTime: '' },
  { institutionCode: 'GS', systemName: 'VTS_AIS', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '수신대기중', collectionCount: '0', isNormal: false, lastMessageTime: '' },
  { institutionCode: 'GS', systemName: 'VTS_RT', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '수신대기중', collectionCount: '0', isNormal: false, lastMessageTime: '' },
  { institutionCode: 'IC', systemName: 'VTS_AIS', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '149 / 176', isNormal: true, lastMessageTime: '2026-03-25 10:29:09' },
  { institutionCode: 'IC', systemName: 'VTS_RT', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '55 / 503', isNormal: true, lastMessageTime: '2026-03-25 10:29:09' },
  { institutionCode: 'JDC', systemName: 'VTS_AIS', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '433 / 524', isNormal: true, lastMessageTime: '2026-03-25 10:29:09' },
  { institutionCode: 'JDC', systemName: 'VTS_RT', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '256 / 1619', isNormal: true, lastMessageTime: '2026-03-25 10:29:09' },
  { institutionCode: 'JJ', systemName: 'VTS_AIS', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '429 / 508', isNormal: true, lastMessageTime: '2026-03-25 10:29:09' },
  { institutionCode: 'JJ', systemName: 'VTS_RT', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '00:00:00', collectionCount: '160 / 1592', isNormal: true, lastMessageTime: '2026-03-25 10:29:09' },
  { institutionCode: 'MP', systemName: 'VTS_AIS', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '수신대기중', collectionCount: '0', isNormal: false, lastMessageTime: '' },
  { institutionCode: 'MP', systemName: 'VTS_RT', linkInfo: 'VTS', storagePlace: 'signal.t_dynamic_all_reply', linkMethod: 'KAFKA', collectionCycle: '수신대기중', collectionCount: '0', isNormal: false, lastMessageTime: '' },
];

/** Mock fetch — TODO: 실제 API 연동 시 fetch 호출로 교체 */
function fetchVesselMonitorData(): Promise<VesselMonitorRow[]> {
  return new Promise((resolve) => {
    setTimeout(() => {
      const rows: VesselMonitorRow[] = MOCK_DATA.map((d) => ({
        ...d,
        institution: INSTITUTION_NAMES[d.institutionCode] ?? d.institutionCode,
      }));
      resolve(rows);
    }, 400);
  });
}

/* ── 상태 뱃지 ── */
function StatusBadge({ loading, onCount, total }: { loading: boolean; onCount: number; total: number }) {
  if (loading) {
    return (
      <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-bg-2 text-t2">
        <span className="w-1.5 h-1.5 rounded-full bg-cyan-400 animate-pulse" />
        조회 중...
      </span>
    );
  }
  const offCount = total - onCount;
  if (offCount === total) {
    return (
      <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-red-500/10 text-red-400">
        <span className="w-1.5 h-1.5 rounded-full bg-red-400" />
        전체 OFF
      </span>
    );
  }
  if (offCount > 0) {
    return (
      <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-yellow-500/10 text-yellow-400">
        <span className="w-1.5 h-1.5 rounded-full bg-yellow-400" />
        일부 OFF ({offCount}/{total})
      </span>
    );
  }
  return (
    <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-emerald-500/10 text-emerald-400">
      <span className="w-1.5 h-1.5 rounded-full bg-emerald-400" />
      전체 정상
    </span>
  );
}

/* ── 연결상태 셀 ── */
function ConnectionBadge({ isNormal, lastMessageTime }: { isNormal: boolean; lastMessageTime: string }) {
  if (isNormal) {
    return (
      <div className="flex flex-col items-start gap-0.5">
        <span className="inline-flex items-center px-2 py-0.5 rounded text-[11px] font-semibold bg-blue-600 text-white">
          ON
        </span>
        {lastMessageTime && (
          <span className="text-[10px] text-t3">{lastMessageTime}</span>
        )}
      </div>
    );
  }
  return (
    <div className="flex flex-col items-start gap-0.5">
      <span className="inline-flex items-center px-2 py-0.5 rounded text-[11px] font-semibold bg-orange-500 text-white">
        OFF
      </span>
      {lastMessageTime && (
        <span className="text-[10px] text-t3">{lastMessageTime}</span>
      )}
    </div>
  );
}

/* ── 테이블 ── */
const HEADERS = ['번호', '원천기관', '기관코드', '정보시스템명', '연계정보', '저장장소', '연계방식', '수집주기', '선박건수/신호건수', '연결상태'];

function VesselTable({ rows, loading }: { rows: VesselMonitorRow[]; loading: boolean }) {
  return (
    <div className="overflow-auto">
      <table className="w-full text-xs border-collapse">
        <thead>
          <tr className="bg-bg-2 text-t3 uppercase tracking-wide">
            {HEADERS.map((h) => (
              <th key={h} className="px-3 py-2 text-left font-medium border-b border-border-1 whitespace-nowrap">{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {loading && rows.length === 0
            ? Array.from({ length: 8 }).map((_, i) => (
                <tr key={i} className="border-b border-border-1 animate-pulse">
                  {HEADERS.map((_, j) => (
                    <td key={j} className="px-3 py-2">
                      <div className="h-3 bg-bg-2 rounded w-14" />
                    </td>
                  ))}
                </tr>
              ))
            : rows.map((row, idx) => (
                <tr key={`${row.institutionCode}-${row.systemName}`} className="border-b border-border-1 hover:bg-bg-1/50">
                  <td className="px-3 py-2 text-t2 text-center">{idx + 1}</td>
                  <td className="px-3 py-2 font-medium text-t1 whitespace-nowrap">{row.institution}</td>
                  <td className="px-3 py-2 text-t2">{row.institutionCode}</td>
                  <td className="px-3 py-2 text-t2">{row.systemName}</td>
                  <td className="px-3 py-2 text-t2">{row.linkInfo}</td>
                  <td className="px-3 py-2 text-t2 whitespace-nowrap">{row.storagePlace}</td>
                  <td className="px-3 py-2 text-t2">{row.linkMethod}</td>
                  <td className="px-3 py-2 text-t2">{row.collectionCycle}</td>
                  <td className="px-3 py-2 text-t2 text-center">{row.collectionCount}</td>
                  <td className="px-3 py-2">
                    <ConnectionBadge isNormal={row.isNormal} lastMessageTime={row.lastMessageTime} />
                  </td>
                </tr>
              ))}
        </tbody>
      </table>
    </div>
  );
}

/* ── 메인 패널 ── */
export default function MonitorVesselPanel() {
  const [rows, setRows] = useState<VesselMonitorRow[]>([]);
  const [loading, setLoading] = useState(false);
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null);

  const fetchData = useCallback(async () => {
    setLoading(true);
    const data = await fetchVesselMonitorData();
    setRows(data);
    setLoading(false);
    setLastUpdate(new Date());
  }, []);

  useEffect(() => {
    let isMounted = true;
    if (rows.length === 0) {
      void Promise.resolve().then(() => { if (isMounted) void fetchData(); });
    }
    return () => { isMounted = false; };
  }, [rows.length, fetchData]);

  const onCount = rows.filter((r) => r.isNormal).length;

  return (
    <div className="flex flex-col h-full overflow-hidden">
      {/* 헤더 */}
      <div className="flex items-center justify-between px-5 py-3 border-b border-border-1 shrink-0">
        <h2 className="text-sm font-semibold text-t1">선박위치정보 모니터링</h2>
        <div className="flex items-center gap-3">
          {lastUpdate && (
            <span className="text-xs text-t3">
              갱신: {lastUpdate.toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
            </span>
          )}
          <button
            onClick={fetchData}
            disabled={loading}
            className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded bg-bg-2 hover:bg-bg-3 text-t2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <svg
              className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`}
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            새로고침
          </button>
        </div>
      </div>

      {/* 상태 표시줄 */}
      <div className="flex items-center gap-3 px-5 py-2 shrink-0 border-b border-border-1 bg-bg-0">
        <StatusBadge loading={loading} onCount={onCount} total={rows.length} />
        <span className="text-xs text-t3">
          연계 채널 {rows.length}개 (ON: {onCount} / OFF: {rows.length - onCount})
        </span>
      </div>

      {/* 테이블 */}
      <div className="flex-1 overflow-auto p-5">
        <VesselTable rows={rows} loading={loading} />
      </div>
    </div>
  );
}
