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

// ─── 타입 ──────────────────────────────────────────────────

interface EtaClct {
  startDate: string;
  endDate: string;
}

interface ResultClct {
  resultDate: string;
  count: number;
}

interface HrCollectItem {
  id: string;
  rootId: string;
  ip: string;
  depth1: string;
  depth2: string;
  depth3: string;
  depth4: string | null;
  clctName: string;
  clctType: string;
  clctTypeName: string;
  trnsmtCycle: string | null;
  receiveCycle: string | null;
  targetTable: string;
  seq: number;
  estmtRqrd: string;
  activeYn: string;
  clctStartDt: string;
  clctEndDt: string;
  clctDate: string | null;
  jobName: string;
  resultClctList: ResultClct[];
  etaClctList: EtaClct[];
}

// ─── Mock 데이터 ────────────────────────────────────────────

// TODO: 실제 API 연동 시 fetch 호출로 교체
const MOCK_DATA: HrCollectItem[] = [
  {
    id: '100200',
    rootId: '2',
    ip: '127.0.0.1',
    depth1: '연계',
    depth2: '해양경찰청',
    depth3: '해경업무포탈시스템(KBP)',
    depth4: null,
    clctName: '사용자부서',
    clctType: '000002',
    clctTypeName: '배치',
    trnsmtCycle: null,
    receiveCycle: '0 20 4 * * *',
    targetTable: 'common.t_dept_info',
    seq: 101,
    estmtRqrd: '1',
    activeYn: 'Y',
    clctStartDt: '2024-12-16',
    clctEndDt: '9999-12-31',
    clctDate: '2024-12-16',
    jobName: 'DeptJob',
    resultClctList: [],
    etaClctList: [{ startDate: '2025-09-12 04:20', endDate: '2025-09-12 04:21' }],
  },
  {
    id: '100200',
    rootId: '2',
    ip: '127.0.0.1',
    depth1: '연계',
    depth2: '해양경찰청',
    depth3: '해경업무포탈시스템(KBP)',
    depth4: null,
    clctName: '사용자계정',
    clctType: '000002',
    clctTypeName: '배치',
    trnsmtCycle: null,
    receiveCycle: '0 20 4 * 1 *',
    targetTable: 'common.t_usr',
    seq: 102,
    estmtRqrd: '5',
    activeYn: 'Y',
    clctStartDt: '2024-12-17',
    clctEndDt: '9999-12-31',
    clctDate: null,
    jobName: 'UserFlowJob',
    resultClctList: [],
    etaClctList: [],
  },
  {
    id: '100201',
    rootId: '2',
    ip: '127.0.0.1',
    depth1: '연계',
    depth2: '해양경찰청',
    depth3: '해경업무포탈시스템(KBP)',
    depth4: null,
    clctName: '사용자직위',
    clctType: '000002',
    clctTypeName: '배치',
    trnsmtCycle: null,
    receiveCycle: '0 30 4 * * *',
    targetTable: 'common.t_position_info',
    seq: 103,
    estmtRqrd: '1',
    activeYn: 'Y',
    clctStartDt: '2024-12-16',
    clctEndDt: '9999-12-31',
    clctDate: '2025-01-10',
    jobName: 'PositionJob',
    resultClctList: [{ resultDate: '2025-09-12 04:30', count: 42 }],
    etaClctList: [{ startDate: '2025-09-12 04:30', endDate: '2025-09-12 04:31' }],
  },
  {
    id: '100202',
    rootId: '2',
    ip: '127.0.0.1',
    depth1: '연계',
    depth2: '해양경찰청',
    depth3: '해경업무포탈시스템(KBP)',
    depth4: null,
    clctName: '조직정보',
    clctType: '000002',
    clctTypeName: '배치',
    trnsmtCycle: null,
    receiveCycle: '0 40 4 * * *',
    targetTable: 'common.t_org_info',
    seq: 104,
    estmtRqrd: '2',
    activeYn: 'Y',
    clctStartDt: '2024-12-18',
    clctEndDt: '9999-12-31',
    clctDate: '2025-03-20',
    jobName: 'OrgJob',
    resultClctList: [{ resultDate: '2025-09-12 04:40', count: 15 }],
    etaClctList: [{ startDate: '2025-09-12 04:40', endDate: '2025-09-12 04:41' }],
  },
  {
    id: '100203',
    rootId: '2',
    ip: '127.0.0.1',
    depth1: '연계',
    depth2: '해양경찰청',
    depth3: '해경업무포탈시스템(KBP)',
    depth4: null,
    clctName: '근무상태',
    clctType: '000002',
    clctTypeName: '배치',
    trnsmtCycle: null,
    receiveCycle: '0 0 5 * * *',
    targetTable: 'common.t_work_status',
    seq: 105,
    estmtRqrd: '3',
    activeYn: 'N',
    clctStartDt: '2025-01-15',
    clctEndDt: '9999-12-31',
    clctDate: null,
    jobName: 'WorkStatusJob',
    resultClctList: [],
    etaClctList: [],
  },
];

function fetchHrCollectData(): Promise<HrCollectItem[]> {
  return new Promise((resolve) => {
    setTimeout(() => resolve(MOCK_DATA), 300);
  });
}

// ─── 상태 뱃지 ─────────────────────────────────────────────

function getCollectStatus(item: HrCollectItem): { label: string; color: string } {
  if (item.activeYn !== 'Y') {
    return { label: '비활성', color: 'text-t3 bg-bg-elevated' };
  }
  if (item.etaClctList.length > 0) {
    return { label: '완료', color: 'text-emerald-400 bg-emerald-500/10' };
  }
  return { label: '대기', color: 'text-yellow-400 bg-yellow-500/10' };
}

// ─── cron 표현식 → 읽기 쉬운 형태 ─────────────────────────

function formatCron(cron: string | null): string {
  if (!cron) return '-';
  const parts = cron.split(' ');
  if (parts.length < 6) return cron;
  const [sec, min, hour, , ,] = parts;
  return `매일 ${hour}:${min.padStart(2, '0')}:${sec.padStart(2, '0')}`;
}

// ─── 테이블 ─────────────────────────────────────────────────

const HEADERS = [
  '번호',
  '수집항목',
  '기관',
  '시스템',
  '유형',
  '수집주기',
  '대상테이블',
  'Job명',
  '활성',
  '수집시작일',
  '최근수집일',
  '상태',
];

function HrTable({ rows, loading }: { rows: HrCollectItem[]; loading: boolean }) {
  return (
    <div className="overflow-auto">
      <table className="w-full text-caption border-collapse">
        <thead>
          <tr className="bg-bg-elevated text-t3 uppercase tracking-wide">
            {HEADERS.map((h) => (
              <th
                key={h}
                className="px-3 py-2 text-left font-medium border-b border-stroke-1 whitespace-nowrap"
              >
                {h}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {loading && rows.length === 0
            ? Array.from({ length: 5 }).map((_, i) => (
                <tr key={i} className="border-b border-stroke-1 animate-pulse">
                  {HEADERS.map((_, j) => (
                    <td key={j} className="px-3 py-2">
                      <div className="h-3 bg-bg-elevated rounded w-14" />
                    </td>
                  ))}
                </tr>
              ))
            : rows.map((row, idx) => {
                const status = getCollectStatus(row);
                return (
                  <tr
                    key={`${row.seq}`}
                    className="border-b border-stroke-1 hover:bg-bg-surface/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.clctName}
                    </td>
                    <td className="px-3 py-2 text-t2 whitespace-nowrap">{row.depth2}</td>
                    <td className="px-3 py-2 text-t2 whitespace-nowrap">{row.depth3}</td>
                    <td className="px-3 py-2 text-t2">{row.clctTypeName}</td>
                    <td className="px-3 py-2 text-t2 whitespace-nowrap font-mono">
                      {formatCron(row.receiveCycle)}
                    </td>
                    <td className="px-3 py-2 text-t2 font-mono">{row.targetTable}</td>
                    <td className="px-3 py-2 text-t2 font-mono">{row.jobName}</td>
                    <td className="px-3 py-2 text-center">
                      <span
                        className={`inline-block px-1.5 py-0.5 rounded text-label-2 font-medium ${
                          row.activeYn === 'Y'
                            ? 'text-emerald-400 bg-emerald-500/10'
                            : 'text-t3 bg-bg-elevated'
                        }`}
                      >
                        {row.activeYn === 'Y' ? 'Y' : 'N'}
                      </span>
                    </td>
                    <td className="px-3 py-2 text-t2 whitespace-nowrap">{row.clctStartDt}</td>
                    <td className="px-3 py-2 text-t2 whitespace-nowrap">{row.clctDate ?? '-'}</td>
                    <td className="px-3 py-2">
                      <span
                        className={`inline-block px-2 py-0.5 rounded text-label-2 font-medium ${status.color}`}
                      >
                        {status.label}
                      </span>
                    </td>
                  </tr>
                );
              })}
        </tbody>
      </table>
    </div>
  );
}

// ─── 메인 패널 ──────────────────────────────────────────────

export default function CollectHrPanel() {
  const [rows, setRows] = useState<HrCollectItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null);

  const fetchData = useCallback(async () => {
    setLoading(true);
    const data = await fetchHrCollectData();
    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 activeCount = rows.filter((r) => r.activeYn === 'Y').length;
  const completedCount = rows.filter((r) => r.etaClctList.length > 0).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-stroke-1 shrink-0">
        <h2 className="text-body-2 font-semibold text-t1">인사정보 수집 현황</h2>
        <div className="flex items-center gap-3">
          {lastUpdate && (
            <span className="text-caption 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-caption rounded bg-bg-elevated hover:bg-bg-card 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-stroke-1 bg-bg-base">
        <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-caption bg-emerald-500/10 text-emerald-400">
          <span className="w-1.5 h-1.5 rounded-full bg-emerald-400" />
          수집 완료 {completedCount}건
        </span>
        <span className="text-caption text-t3">
          전체 {rows.length}건 (활성: {activeCount} / 비활성: {rows.length - activeCount})
        </span>
      </div>

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