import React, { useState } from 'react'
import api from '../api/client'

export default function AiPage() {
  const [tab, setTab] = useState<'turnover'|'performance'|'recruitment'|'orghealth'|'resume'|'insights'>('insights')
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<any>(null)
  const [form, setForm] = useState({ empId: '', deptId: '' })
  const [resumeText, setResumeText] = useState('')

  const call = async (endpoint: string, params?: any) => {
    setLoading(true)
    setResult(null)
    try {
      const r = await api.post(endpoint, params || {}, { params })
      setResult(r.data.data)
    } catch (e: any) {
      setResult({ error: e.response?.data?.message || 'AI 분석 실패' })
    } finally {
      setLoading(false)
    }
  }

  const tabs = [
    { v: 'insights', l: 'HR 인사이트' },
    { v: 'turnover', l: '이직 예측' },
    { v: 'performance', l: '성과 예측' },
    { v: 'recruitment', l: '채용 추천' },
    { v: 'orghealth', l: '조직 건강도' },
    { v: 'resume', l: '이력서 분석' },
  ]

  const renderResult = () => {
    if (loading) return (
      <div className="flex items-center justify-center py-16">
        <div className="text-center space-y-3">
          <div className="w-10 h-10 border-2 border-blue-600 border-t-transparent rounded-full animate-spin mx-auto"></div>
          <p className="text-sm text-slate-500">Ollama AI 분석 중...</p>
        </div>
      </div>
    )
    if (!result) return (
      <div className="py-16 text-center text-slate-400">
        <p className="text-4xl mb-3">AI</p>
        <p className="text-sm">위 버튼을 눌러 AI 분석을 시작하세요</p>
        <p className="text-xs mt-1 text-slate-300">Ollama 온프레미스 AI — 외부 전송 없음</p>
      </div>
    )
    if (result.error) return <div className="p-4 bg-red-50 text-red-600 rounded-lg text-sm">{result.error}</div>

    return (
      <div className="space-y-3">
        {typeof result === 'string' ? (
          <p className="text-sm text-slate-700 whitespace-pre-wrap leading-relaxed">{result}</p>
        ) : (
          <pre className="text-xs bg-slate-50 p-4 rounded-lg overflow-auto whitespace-pre-wrap text-slate-700 leading-relaxed">
            {JSON.stringify(result, null, 2)}
          </pre>
        )}
      </div>
    )
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <h1 className="text-2xl font-bold text-slate-800">AI 인사 분석</h1>
        <span className="badge bg-purple-100 text-purple-700">Ollama 온프레미스</span>
      </div>

      <div className="flex gap-2 border-b border-slate-200 overflow-x-auto">
        {tabs.map(t => (
          <button key={t.v} onClick={() => { setTab(t.v as any); setResult(null) }}
            className={`px-4 py-2 text-sm font-medium border-b-2 whitespace-nowrap transition-colors ${tab===t.v?'border-purple-600 text-purple-600':'border-transparent text-slate-500'}`}>
            {t.l}
          </button>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <div className="card space-y-4">
          {tab === 'insights' && (
            <>
              <h2 className="font-semibold text-slate-700">HR 종합 인사이트</h2>
              <p className="text-sm text-slate-500">전사 HR 데이터를 분석하여 핵심 인사이트와 액션 아이템을 제공합니다.</p>
              <button className="btn-primary w-full" onClick={() => call('/ai/insights')}>인사이트 생성</button>
            </>
          )}
          {tab === 'turnover' && (
            <>
              <h2 className="font-semibold text-slate-700">이직 예측</h2>
              <p className="text-sm text-slate-500">사원별 이직 위험도를 분석하고 예방 방안을 제시합니다.</p>
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">사원 ID (선택)</label>
                <input type="number" value={form.empId} onChange={e => setForm({...form, empId: e.target.value})}
                  placeholder="미입력 시 전체 분석" className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none" />
              </div>
              <button className="btn-primary w-full" onClick={() => call('/ai/turnover-prediction', form.empId ? {empId: +form.empId} : {})}>이직 위험도 분석</button>
            </>
          )}
          {tab === 'performance' && (
            <>
              <h2 className="font-semibold text-slate-700">성과 예측</h2>
              <p className="text-sm text-slate-500">사원의 역량·출결·교육이력을 기반으로 성과를 예측합니다.</p>
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">사원 ID*</label>
                <input type="number" value={form.empId} onChange={e => setForm({...form, empId: e.target.value})}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none" />
              </div>
              <button className="btn-primary w-full" onClick={() => call('/ai/performance-prediction', form.empId ? {empId: +form.empId} : {})}>성과 예측 실행</button>
            </>
          )}
          {tab === 'recruitment' && (
            <>
              <h2 className="font-semibold text-slate-700">채용 추천</h2>
              <p className="text-sm text-slate-500">부서별 인력 현황과 업무 부하를 분석하여 최적 채용 계획을 추천합니다.</p>
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">부서 ID (선택)</label>
                <input type="number" value={form.deptId} onChange={e => setForm({...form, deptId: e.target.value})}
                  placeholder="미입력 시 전체" className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none" />
              </div>
              <button className="btn-primary w-full" onClick={() => call('/ai/recruitment-recommendation', form.deptId ? {deptId: +form.deptId} : {})}>채용 계획 추천</button>
            </>
          )}
          {tab === 'orghealth' && (
            <>
              <h2 className="font-semibold text-slate-700">조직 건강도</h2>
              <p className="text-sm text-slate-500">조직의 전반적인 건강도와 위험 요인을 AI로 진단합니다.</p>
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">부서 ID (선택)</label>
                <input type="number" value={form.deptId} onChange={e => setForm({...form, deptId: e.target.value})}
                  placeholder="미입력 시 전체" className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none" />
              </div>
              <button className="btn-primary w-full" onClick={() => call('/ai/org-health', form.deptId ? {deptId: +form.deptId} : {})}>조직 건강도 진단</button>
            </>
          )}
          {tab === 'resume' && (
            <>
              <h2 className="font-semibold text-slate-700">이력서 분석</h2>
              <p className="text-sm text-slate-500">지원자 이력서를 AI가 분석하여 적합도와 주요 역량을 추출합니다.</p>
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">이력서 내용</label>
                <textarea value={resumeText} onChange={e => setResumeText(e.target.value)}
                  placeholder="이력서 내용을 붙여넣으세요..."
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none" rows={6} />
              </div>
              <button className="btn-primary w-full" onClick={() => call('/ai/analyze-resume', { resumeText })}>이력서 분석</button>
            </>
          )}
        </div>

        <div className="card min-h-[300px]">
          <div className="flex items-center gap-2 mb-4">
            <div className="w-2 h-2 rounded-full bg-purple-500 animate-pulse"></div>
            <h3 className="text-sm font-semibold text-slate-700">AI 분석 결과</h3>
          </div>
          {renderResult()}
        </div>
      </div>

      <div className="card bg-slate-50 border border-slate-200">
        <div className="flex items-start gap-3">
          <div className="w-8 h-8 rounded-lg bg-purple-100 flex items-center justify-center text-purple-700 text-sm font-bold flex-shrink-0">AI</div>
          <div>
            <p className="text-sm font-medium text-slate-700">온프레미스 AI 사용 중</p>
            <p className="text-xs text-slate-500 mt-0.5">모든 분석은 내부 Ollama 서버(localhost:11434)에서 처리됩니다. 사원 정보가 외부로 전송되지 않습니다.</p>
          </div>
        </div>
      </div>
    </div>
  )
}
