import { useState, useEffect } from 'react'
import { managerApi } from '../api/clients'
import { Btn } from '../components/common/Btn'

interface LogLine { ts: string; ok: boolean; err: boolean; msg: string }

function parseLog(lines: string[]): LogLine[] {
  return lines.map(l => ({
    ts:  l.match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/)?.[0] ?? '',
    ok:  l.includes('완료') || l.includes('DONE') || l.includes('success'),
    err: l.includes('실패') || l.includes('ERROR') || l.includes('FAIL'),
    msg: l.replace(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3} \w+ /, '').trim(),
  }))
}

export default function Deployments() {
  const [logs, setLogs]         = useState<LogLine[]>([])
  const [loading, setLoading]   = useState(true)
  const [triggering, setTrig]   = useState(false)

  const load = () => {
    setLoading(true)
    managerApi.get('/api/deploy/history')
      .then(r => setLogs(parseLog((r.data?.lines ?? []).slice(-50).reverse())))
      .catch(() => setLogs([]))
      .finally(() => setLoading(false))
  }

  useEffect(() => { load() }, [])

  const trigger = async (repo = 'all') => {
    setTrig(true)
    try {
      await managerApi.post(`/api/deploy/trigger/${repo}`)
      setTimeout(load, 3000)
    } catch (e: unknown) {
      alert((e as { response?: { data?: { detail?: string } } }).response?.data?.detail ?? '트리거 실패')
    } finally { setTrig(false) }
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* 액션 바 */}
      <div style={{ display: 'flex', gap: 10, alignItems: 'center',
        background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, padding: '14px 18px' }}>
        <span style={{ fontSize: 13, fontWeight: 600, flex: 1 }}>수동 배포 트리거</span>
        <Btn variant="primary" size="sm" loading={triggering} onClick={() => trigger('zioinfo-web')}>
          🚀 홈페이지 배포
        </Btn>
        <Btn variant="outline" size="sm" loading={triggering} onClick={() => trigger('guardia-itsm')}>
          🛡️ ITSM 배포
        </Btn>
        <Btn size="sm" onClick={load}>↺ 새로고침</Btn>
      </div>

      {/* 배포 로그 */}
      <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, overflow: 'hidden' }}>
        <div style={{ padding: '12px 18px', borderBottom: '1px solid #f1f5f9',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h3 style={{ fontSize: 13, fontWeight: 600, margin: 0 }}>📋 배포 이력 (최근 50건)</h3>
          <span style={{ fontSize: 11, color: '#94a3b8' }}>{logs.length}개 항목</span>
        </div>

        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#94a3b8' }}>로딩 중...</div>
        ) : logs.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#94a3b8' }}>
            <div style={{ fontSize: 32, marginBottom: 12 }}>🚀</div>
            <div>배포 이력이 없습니다.<br />첫 배포를 실행해보세요.</div>
          </div>
        ) : (
          <div style={{ fontFamily: 'monospace', fontSize: 12 }}>
            {logs.map((l, i) => (
              <div key={i} style={{
                display: 'flex', gap: 10, padding: '8px 18px',
                borderBottom: i < logs.length - 1 ? '1px solid #f8fafc' : 'none',
                background: l.err ? '#fff5f5' : l.ok ? '#f0fdf4' : 'transparent',
              }}>
                <span style={{ color: '#94a3b8', whiteSpace: 'nowrap', flexShrink: 0 }}>
                  {l.ts.slice(11) || '--:--:--'}
                </span>
                <span>{l.ok ? '✅' : l.err ? '❌' : '🔄'}</span>
                <span style={{ color: l.err ? '#dc2626' : '#1e293b', wordBreak: 'break-all' }}>{l.msg}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
