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

export default function PayrollPage() {
  const [payrolls, setPayrolls] = useState<any[]>([])
  const [total, setTotal] = useState(0)
  const [year, setYear] = useState(new Date().getFullYear())
  const [month, setMonth] = useState(new Date().getMonth() + 1)

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

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

  const processPayroll = async () => {
    if (!confirm(`${year}년 ${month}월 급여를 처리하시겠습니까?`)) return
    try {
      await api.post('/payroll/process', null, { params: { year, month } })
      alert('급여 처리 완료')
      load()
    } catch (e: any) {
      alert(e.response?.data?.message || '처리 실패')
    }
  }

  const statusBadge = (s: string) => {
    const m: any = { DRAFT: 'bg-slate-100 text-slate-600', PROCESSED: 'bg-blue-100 text-blue-700', APPROVED: 'bg-green-100 text-green-700' }
    const l: any = { DRAFT: '초안', PROCESSED: '처리완료', APPROVED: '승인완료' }
    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>
        <button className="btn-primary" onClick={processPayroll}>급여 처리 실행</button>
      </div>

      <div className="card flex gap-4 items-center">
        <label className="text-sm text-slate-600">연도</label>
        <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>
        <label className="text-sm text-slate-600">월</label>
        <select value={month} onChange={e => setMonth(+e.target.value)}
          className="border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none">
          {Array.from({length:12},(_,i)=>i+1).map(m => <option key={m} value={m}>{m}월</option>)}
        </select>
        <span className="text-sm text-slate-500">총 {total}건</span>
      </div>

      <div className="card overflow-x-auto">
        <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>
            {payrolls.map((p: any) => (
              <tr key={p.id} className="border-b border-slate-50 hover:bg-slate-50">
                <td className="table-cell font-medium">{p.year}년 {p.month}월</td>
                <td className="table-cell font-mono">{(p.total_amount||0).toLocaleString()}원</td>
                <td className="table-cell">{statusBadge(p.status)}</td>
                <td className="table-cell">{p.processed_by || '-'}</td>
                <td className="table-cell text-xs">{p.processed_at?.slice(0,16) || '-'}</td>
                <td className="table-cell">{p.payslip_count || 0}건</td>
                <td className="table-cell">
                  {p.status === 'PROCESSED' && (
                    <button className="text-green-600 text-xs hover:underline"
                      onClick={async () => { await api.post(`/payroll/${p.id}/approve`); load() }}>승인</button>
                  )}
                </td>
              </tr>
            ))}
            {payrolls.length === 0 && (
              <tr><td colSpan={7} className="text-center py-8 text-slate-400">급여 처리 내역이 없습니다</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
