import { useState, useEffect, useCallback } from 'react';
import {
  getNumericalDataStatus,
  type NumericalDataStatus,
} from '../services/monitorApi';

type TabId = 'all' | 'ocean' | 'koast';

const TABS: { id: TabId; label: string }[] = [
  { id: 'all', label: '전체' },
  { id: 'ocean', label: '기상·해양 모델' },
  { id: 'koast', label: 'KOAST' },
];

const OCEAN_MODELS = ['HYCOM', 'GFS', 'WW3'];
const KOAST_MODELS = ['KOAST POS_WIND', 'KOAST POS_HYDR', 'KOAST POS_WAVE'];

function filterByTab(rows: NumericalDataStatus[], tab: TabId): NumericalDataStatus[] {
  if (tab === 'ocean') return rows.filter((r) => OCEAN_MODELS.includes(r.modelName));
  if (tab === 'koast') return rows.filter((r) => KOAST_MODELS.includes(r.modelName));
  return rows;
}

function formatDuration(sec: number | null): string {
  if (sec == null) return '-';
  const m = Math.floor(sec / 60);
  const s = sec % 60;
  return m > 0 ? `${m}분 ${s}초` : `${s}초`;
}

function formatDatetime(iso: string | null): string {
  if (!iso) return '-';
  const d = new Date(iso);
  const mm = String(d.getMonth() + 1).padStart(2, '0');
  const dd = String(d.getDate()).padStart(2, '0');
  const hh = String(d.getHours()).padStart(2, '0');
  const min = String(d.getMinutes()).padStart(2, '0');
  return `${mm}-${dd} ${hh}:${min}`;
}

function formatTime(iso: string | null): string {
  if (!iso) return '-';
  const d = new Date(iso);
  const hh = String(d.getHours()).padStart(2, '0');
  const min = String(d.getMinutes()).padStart(2, '0');
  return `${hh}:${min}`;
}

function StatusCell({ row }: { row: NumericalDataStatus }) {
  if (row.lastStatus === 'COMPLETED') {
    return <span className="text-emerald-400 text-xs">정상</span>;
  }
  if (row.lastStatus === 'FAILED') {
    return (
      <span className="text-red-400 text-xs">
        오류{row.consecutiveFailures > 0 ? ` (${row.consecutiveFailures}회 연속)` : ''}
      </span>
    );
  }
  if (row.lastStatus === 'STARTED') {
    return (
      <span className="inline-flex items-center gap-1 text-cyan-400 text-xs">
        <span className="w-1.5 h-1.5 rounded-full bg-cyan-400 animate-pulse" />
        실행 중
      </span>
    );
  }
  return <span className="text-t3 text-xs">-</span>;
}

function StatusBadge({
  loading,
  errorCount,
  total,
}: {
  loading: boolean;
  errorCount: 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>
    );
  }
  if (errorCount === total && total > 0) {
    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" />
        연계 오류
      </span>
    );
  }
  if (errorCount > 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" />
        일부 오류 ({errorCount}/{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>
  );
}

const TABLE_HEADERS = [
  '모델명',
  '데이터 기준일',
  '마지막 다운로드',
  '상태',
  '소요 시간',
  '다음 예정',
];

function ForecastTable({
  rows,
  loading,
}: {
  rows: NumericalDataStatus[];
  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">
            {TABLE_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: 6 }).map((_, i) => (
                <tr key={i} className="border-b border-border-1 animate-pulse">
                  {TABLE_HEADERS.map((_, j) => (
                    <td key={j} className="px-3 py-2">
                      <div className="h-3 bg-bg-2 rounded w-16" />
                    </td>
                  ))}
                </tr>
              ))
            : rows.map((row) => (
                <tr key={row.jobName} className="border-b border-border-1 hover:bg-bg-1/50">
                  <td className="px-3 py-2 font-medium text-t1 whitespace-nowrap">
                    {row.modelName}
                  </td>
                  <td className="px-3 py-2 text-t2">{row.lastDataDate ?? '-'}</td>
                  <td className="px-3 py-2 text-t2">{formatDatetime(row.lastDownloadedAt)}</td>
                  <td className="px-3 py-2">
                    <StatusCell row={row} />
                  </td>
                  <td className="px-3 py-2 text-t2">{formatDuration(row.durationSec)}</td>
                  <td className="px-3 py-2 text-t2">{formatTime(row.nextScheduledAt)}</td>
                </tr>
              ))}
        </tbody>
      </table>
    </div>
  );
}

export default function MonitorForecastPanel() {
  const [activeTab, setActiveTab] = useState<TabId>('all');
  const [rows, setRows] = useState<NumericalDataStatus[]>([]);
  const [loading, setLoading] = useState(false);
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const data = await getNumericalDataStatus();
      setRows(data);
      setLastUpdate(new Date());
    } catch {
      // 오류 시 기존 데이터 유지
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void fetchData();
  }, [fetchData]);

  const visibleRows = filterByTab(rows, activeTab);
  const errorCount = visibleRows.filter(
    (r) => r.lastStatus === 'FAILED'
  ).length;
  const totalCount = visibleRows.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={() => void 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 gap-0 border-b border-border-1 shrink-0 px-5">
        {TABS.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`px-4 py-2.5 text-xs font-medium border-b-2 transition-colors ${
              activeTab === tab.id
                ? 'border-cyan-400 text-cyan-400'
                : 'border-transparent text-t3 hover:text-t2'
            }`}
          >
            {tab.label}
          </button>
        ))}
      </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} errorCount={errorCount} total={totalCount} />
        {!loading && totalCount > 0 && (
          <span className="text-xs text-t3">모델 {totalCount}개</span>
        )}
      </div>

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