import React, { useEffect, useState } from 'react'
import { RadarChart, Radar, PolarGrid, PolarAngleAxis, ResponsiveContainer } from 'recharts'
import api from '../api/client'

export default function PerformancePage() {
  const [reviews, setReviews] = useState<any[]>([])
  const [total, setTotal] = useState(0)
  const [year, setYear] = useState(new Date().getFullYear())
  const [tab, setTab] = useState<'review'|'goal'>('review')

  const load = () => {
    api.get('/performance/reviews', { params: { year, page: 1, size: 20 } })
      .then(r => { setReviews(r.data.data.items || []); setTotal(r.data.data.total || 0) })
      .catch(() => {})
  }
  useEffect(() => { load() }, [year])

  const gradeBadge = (g: string) => {
    const m: any = { S: 'bg-purple-100 text-purple-700', A: 'bg-blue-100 text-blue-700', B: 'bg-green-100 text-green-700', C: 'bg-yellow-100 text-yellow-700', D: 'bg-red-100 text-red-700' }
    return g ? <span className={`badge font-bold ${m[g]||''}`}>{g}등급</span> : <span className="text-slate-400 text-xs">미평가</span>
  }

  const statusBadge = (s: string) => {
    const m: any = { DRAFT: 'bg-slate-100 text-slate-600', SUBMITTED: 'bg-blue-100 text-blue-700', COMPLETED: 'bg-green-100 text-green-700' }
    const l: any = { DRAFT: '작성중', SUBMITTED: '제출완료', COMPLETED: '최종확정' }
    return <span className={`badge ${m[s]||''}`}>{l[s]||s}</span>
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-slate-800">성과평가</h1>
        <div className="flex items-center gap-3">
          <select value={year} onChange={e => setYear(+e.target.value)}
            className="border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none">
            {[2024,2025,2026].map(y => <option key={y} value={y}>{y}년</option>)}
          </select>
          <button className="btn-primary" onClick={() => api.post('/performance/reviews', { year, period: 'ANNUAL' }).then(load)}>
            + 평가 생성
          </button>
        </div>
      </div>

      <div className="flex gap-2 border-b border-slate-200">
        {[{v:'review',l:'성과 평가표'},{v:'goal',l:'MBO 목표'}].map(t => (
          <button key={t.v} onClick={() => setTab(t.v as any)}
            className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${tab===t.v?'border-blue-600 text-blue-600':'border-transparent text-slate-500'}`}>
            {t.l}
          </button>
        ))}
      </div>

      {tab === 'review' && (
        <div className="card overflow-x-auto">
          <div className="flex justify-between items-center mb-3">
            <p className="text-sm text-slate-500">총 <span className="font-bold text-blue-600">{total}</span>건</p>
          </div>
          <table className="w-full">
            <thead className="border-b border-slate-100">
              <tr>{['사원','사원번호','연도/기간','등급','점수','상태','관리'].map(h=><th key={h} className="table-header">{h}</th>)}</tr>
            </thead>
            <tbody>
              {reviews.map((r: any) => (
                <tr key={r.id} className="border-b border-slate-50 hover:bg-slate-50">
                  <td className="table-cell font-medium">{r.emp_name}</td>
                  <td className="table-cell font-mono text-xs">{r.emp_no}</td>
                  <td className="table-cell">{r.year} / {r.period}</td>
                  <td className="table-cell">{gradeBadge(r.final_grade)}</td>
                  <td className="table-cell">{r.score ? r.score.toFixed(1) : '-'}</td>
                  <td className="table-cell">{statusBadge(r.status)}</td>
                  <td className="table-cell">
                    <div className="flex gap-2">
                      {r.status === 'DRAFT' && (
                        <button className="text-blue-600 text-xs hover:underline"
                          onClick={async () => { await api.post(`/performance/reviews/${r.id}/submit`); load() }}>제출</button>
                      )}
                      {r.status === 'SUBMITTED' && (
                        <button className="text-green-600 text-xs hover:underline"
                          onClick={async () => { await api.post(`/performance/reviews/${r.id}/approve`); load() }}>확정</button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
              {reviews.length === 0 && <tr><td colSpan={7} className="text-center py-8 text-slate-400">평가 데이터가 없습니다</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'goal' && (
        <div className="card">
          <p className="text-sm text-slate-500 mb-4">사원 ID 선택 후 MBO 목표를 조회합니다</p>
          <div className="flex gap-4 items-center">
            <input type="number" id="goalEmpId" placeholder="사원 ID 입력"
              className="border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none w-40" />
            <button className="btn-primary" onClick={() => {
              const id = (document.getElementById('goalEmpId') as HTMLInputElement).value
              if (id) window.location.href = `/performance?empId=${id}`
            }}>조회</button>
          </div>
          <div className="mt-6 p-8 bg-slate-50 rounded-xl text-center text-slate-400">
            역량 레이더 차트는 사원 선택 후 표시됩니다
          </div>
        </div>
      )}
    </div>
  )
}
