import { useApi } from '../hooks/useApi'
import { managerApi } from '../api/clients'

interface OllamaTagsResp { models: Array<{ name: string; size: number; modified_at: string; details?: { parameter_size?: string; family?: string } }> }

function bytes(n: number) {
  if (n > 1e9) return `${(n / 1e9).toFixed(1)} GB`
  return `${(n / 1e6).toFixed(0)} MB`
}

export default function LLMManager() {
  const { data, loading } = useApi<OllamaTagsResp>(managerApi, '/api/llm/models')
  const models = data?.models ?? []

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ background: '#fff3cd', border: '1px solid #ffc107', borderRadius: 8,
        padding: '12px 16px', fontSize: 13, color: '#856404' }}>
        🤖 온프레미스 전용 — 외부 AI API 사용 불가. Ollama(localhost:11434)만 허용.
      </div>

      {loading ? <div style={{ color: '#94a3b8', padding: 24 }}>모델 목록 로딩 중...</div> : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px,1fr))', gap: 14 }}>
          {models.map(m => (
            <div key={m.name} style={{ background: '#fff', border: '1px solid #e2e8f0',
              borderRadius: 10, padding: '18px 20px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                <span style={{ fontSize: 24 }}>🤖</span>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{m.name}</div>
                  {m.details?.family && <div style={{ fontSize: 11, color: '#94a3b8' }}>{m.details.family}</div>}
                </div>
                <span style={{ marginLeft: 'auto', background: '#dcfce7', color: '#16a34a',
                  padding: '2px 8px', borderRadius: 10, fontSize: 10, fontWeight: 600 }}>LOADED</span>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, fontSize: 12 }}>
                <div><span style={{ color: '#94a3b8' }}>크기</span><div style={{ fontWeight: 600 }}>{bytes(m.size)}</div></div>
                <div><span style={{ color: '#94a3b8' }}>파라미터</span><div style={{ fontWeight: 600 }}>{m.details?.parameter_size ?? '-'}</div></div>
                <div style={{ gridColumn: 'span 2' }}>
                  <span style={{ color: '#94a3b8' }}>수정일</span>
                  <div>{m.modified_at?.slice(0, 10)}</div>
                </div>
              </div>
            </div>
          ))}
          {models.length === 0 && (
            <div style={{ padding: 40, color: '#94a3b8', textAlign: 'center' }}>
              <div style={{ fontSize: 40, marginBottom: 12 }}>🤖</div>
              <div>설치된 Ollama 모델이 없거나 연결할 수 없습니다.</div>
            </div>
          )}
        </div>
      )}
    </div>
  )
}
