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

export default function EmployeePage() {
  const [employees, setEmployees] = useState<any[]>([])
  const [total, setTotal] = useState(0)
  const [keyword, setKeyword] = useState('')
  const [status, setStatus] = useState('ACTIVE')
  const [page, setPage] = useState(1)
  const [showForm, setShowForm] = useState(false)
  const [selected, setSelected] = useState<any>(null)
  const [form, setForm] = useState<any>({ name: '', email: '', employmentType: 'REGULAR', hireDate: '', status: 'ACTIVE' })

  const load = () => {
    api.get('/employees', { params: { keyword, status, page, size: 20 } })
      .then(r => { setEmployees(r.data.data.items); setTotal(r.data.data.total) })
      .catch(() => {})
  }

  useEffect(() => { load() }, [keyword, status, page])

  const save = async () => {
    try {
      if (selected) {
        await api.put(`/employees/${selected.id}`, form)
      } else {
        await api.post('/employees', form)
      }
      setShowForm(false); setSelected(null); load()
    } catch (e: any) {
      alert(e.response?.data?.message || '저장 실패')
    }
  }

  const statusBadge = (s: string) => {
    const m: any = { ACTIVE: 'bg-green-100 text-green-700', LEAVE: 'bg-yellow-100 text-yellow-700', RETIRED: 'bg-slate-100 text-slate-600' }
    const l: any = { ACTIVE: '재직', LEAVE: '휴직', RETIRED: '퇴직' }
    return <span className={`badge ${m[s]||'bg-slate-100 text-slate-600'}`}>{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={() => { setSelected(null); setForm({ name:'',email:'',employmentType:'REGULAR',hireDate:'',status:'ACTIVE' }); setShowForm(true) }}>+ 사원 등록</button>
      </div>

      {/* 검색 */}
      <div className="card flex gap-4">
        <input value={keyword} onChange={e => setKeyword(e.target.value)} placeholder="이름/사원번호 검색"
          className="border border-slate-200 rounded-lg px-3 py-2 text-sm flex-1 focus:outline-none focus:ring-2 focus:ring-blue-400" />
        <select value={status} onChange={e => setStatus(e.target.value)}
          className="border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none">
          <option value="">전체</option>
          <option value="ACTIVE">재직</option>
          <option value="LEAVE">휴직</option>
          <option value="RETIRED">퇴직</option>
        </select>
      </div>

      {/* 테이블 */}
      <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>
              ))}
              <th className="table-header">관리</th>
            </tr>
          </thead>
          <tbody>
            {employees.map(e => (
              <tr key={e.id} className="border-b border-slate-50 hover:bg-slate-50">
                <td className="table-cell font-mono text-xs">{e.empNo}</td>
                <td className="table-cell font-medium">{e.name}</td>
                <td className="table-cell">{e.departmentName || '-'}</td>
                <td className="table-cell">{e.positionName || '-'}</td>
                <td className="table-cell">{e.gradeName || '-'}</td>
                <td className="table-cell">{e.employmentType === 'REGULAR' ? '정규직' : e.employmentType === 'CONTRACT' ? '계약직' : '파트타임'}</td>
                <td className="table-cell">{statusBadge(e.status)}</td>
                <td className="table-cell text-xs">{e.hireDate}</td>
                <td className="table-cell">
                  <button className="text-blue-600 text-xs hover:underline"
                    onClick={() => { setSelected(e); setForm(e); setShowForm(true) }}>수정</button>
                </td>
              </tr>
            ))}
            {employees.length === 0 && (
              <tr><td colSpan={9} className="text-center py-8 text-slate-400">검색 결과가 없습니다</td></tr>
            )}
          </tbody>
        </table>
        <div className="flex justify-center gap-2 mt-4">
          {Array.from({ length: Math.ceil(total / 20) }, (_, i) => i + 1).map(p => (
            <button key={p} onClick={() => setPage(p)}
              className={`px-3 py-1 rounded text-sm ${page===p?'bg-blue-600 text-white':'bg-slate-100 text-slate-700 hover:bg-slate-200'}`}>
              {p}
            </button>
          ))}
        </div>
      </div>

      {/* 모달 */}
      {showForm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg p-6">
            <h2 className="text-lg font-bold text-slate-800 mb-5">{selected ? '사원 수정' : '사원 등록'}</h2>
            <div className="grid grid-cols-2 gap-4">
              {[
                { label: '이름*', key: 'name', type: 'text' },
                { label: '이메일', key: 'email', type: 'email' },
                { label: '입사일*', key: 'hireDate', type: 'date' },
              ].map(f => (
                <div key={f.key}>
                  <label className="block text-xs font-medium text-slate-600 mb-1">{f.label}</label>
                  <input type={f.type} value={form[f.key] || ''} onChange={e => setForm({ ...form, [f.key]: e.target.value })}
                    className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400" />
                </div>
              ))}
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">고용형태</label>
                <select value={form.employmentType || 'REGULAR'} onChange={e => setForm({ ...form, employmentType: e.target.value })}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm">
                  <option value="REGULAR">정규직</option>
                  <option value="CONTRACT">계약직</option>
                  <option value="PARTTIME">파트타임</option>
                </select>
              </div>
            </div>
            <div className="flex justify-end gap-3 mt-6">
              <button className="btn-secondary" onClick={() => { setShowForm(false); setSelected(null) }}>취소</button>
              <button className="btn-primary" onClick={save}>저장</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
