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

export default function TrainingPage() {
  const [courses, setCourses] = useState<any[]>([])
  const [total, setTotal] = useState(0)
  const [legal, setLegal] = useState<any[]>([])
  const [tab, setTab] = useState<'course'|'legal'>('course')
  const [showForm, setShowForm] = useState(false)
  const [form, setForm] = useState<any>({ courseName: '', category: 'SKILL', provider: '', startDate: '', endDate: '', maxCapacity: 20, description: '' })

  const loadCourses = () => {
    api.get('/training/courses', { params: { page: 1, size: 20 } })
      .then(r => { setCourses(r.data.data.items || []); setTotal(r.data.data.total || 0) })
      .catch(() => {})
  }

  const loadLegal = () => {
    api.get('/training/legal-status', { params: { year: new Date().getFullYear() } })
      .then(r => setLegal(r.data.data || [])).catch(() => {})
  }

  useEffect(() => { loadCourses(); loadLegal() }, [])

  const save = async () => {
    try {
      await api.post('/training/courses', form)
      setShowForm(false); loadCourses()
    } catch (e: any) { alert(e.response?.data?.message || '저장 실패') }
  }

  const enroll = async (courseId: number, empId: number) => {
    try {
      await api.post(`/training/courses/${courseId}/enroll`, null, { params: { empId } })
      alert('수강 신청 완료')
    } catch (e: any) { alert(e.response?.data?.message || '신청 실패') }
  }

  const categoryLabel: any = {
    SKILL: '직무역량', COMPLIANCE: '법정의무', LEADERSHIP: '리더십', SAFETY: '안전', LANGUAGE: '어학'
  }

  const statusBadge = (s: string) => {
    const m: any = { PLANNED: 'bg-slate-100 text-slate-600', ONGOING: 'bg-blue-100 text-blue-700', COMPLETED: 'bg-green-100 text-green-700', CANCELLED: 'bg-red-100 text-red-700' }
    const l: any = { PLANNED: '예정', ONGOING: '진행중', COMPLETED: '완료', CANCELLED: '취소' }
    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={() => setShowForm(true)}>+ 교육과정 등록</button>
      </div>

      <div className="flex gap-2 border-b border-slate-200">
        {[{v:'course',l:`교육과정 (${total}건)`},{v:'legal',l:'법정교육 현황'}].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 === 'course' && (
        <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>
              {courses.map((c: any) => (
                <tr key={c.id} className="border-b border-slate-50 hover:bg-slate-50">
                  <td className="table-cell font-medium">{c.course_name}</td>
                  <td className="table-cell"><span className="badge bg-slate-100 text-slate-700">{categoryLabel[c.category]||c.category}</span></td>
                  <td className="table-cell">{c.provider || '-'}</td>
                  <td className="table-cell text-xs">{c.start_date?.slice(0,10)} ~ {c.end_date?.slice(0,10)}</td>
                  <td className="table-cell">{c.max_capacity || '-'} / {c.enrolled_count || 0}명</td>
                  <td className="table-cell">{statusBadge(c.status)}</td>
                  <td className="table-cell">
                    {c.status === 'ONGOING' && (
                      <button className="text-blue-600 text-xs hover:underline"
                        onClick={() => {
                          const empId = prompt('사원 ID를 입력하세요')
                          if (empId) enroll(c.id, +empId)
                        }}>수강신청</button>
                    )}
                  </td>
                </tr>
              ))}
              {courses.length === 0 && <tr><td colSpan={7} className="text-center py-8 text-slate-400">교육과정이 없습니다</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'legal' && (
        <div className="card overflow-x-auto">
          <h2 className="text-base font-semibold text-slate-700 mb-4">법정의무교육 이수 현황 ({new Date().getFullYear()}년)</h2>
          <table className="w-full">
            <thead className="border-b border-slate-100">
              <tr>{['사원번호','이름','부서','직위','성희롱예방','개인정보보호','산업안전','장애인식','이수율'].map(h=><th key={h} className="table-header text-xs">{h}</th>)}</tr>
            </thead>
            <tbody>
              {legal.map((l: any) => {
                const courses = ['sexual_harassment','privacy','safety','disability']
                const done = courses.filter(c => l[c+'_completed']).length
                return (
                  <tr key={l.emp_id} className="border-b border-slate-50 hover:bg-slate-50">
                    <td className="table-cell font-mono text-xs">{l.emp_no}</td>
                    <td className="table-cell font-medium">{l.emp_name}</td>
                    <td className="table-cell text-xs">{l.dept_name}</td>
                    <td className="table-cell text-xs">{l.position_name}</td>
                    {courses.map(c => (
                      <td key={c} className="table-cell text-center">
                        <span className={`inline-block w-5 h-5 rounded-full text-xs flex items-center justify-center ${l[c+'_completed']?'bg-green-100 text-green-700':'bg-red-100 text-red-600'}`}>
                          {l[c+'_completed']?'O':'X'}
                        </span>
                      </td>
                    ))}
                    <td className="table-cell">
                      <div className="flex items-center gap-2">
                        <div className="w-16 bg-slate-100 rounded-full h-1.5">
                          <div className="bg-blue-500 h-1.5 rounded-full" style={{width:`${done/4*100}%`}}></div>
                        </div>
                        <span className="text-xs text-slate-600">{done}/4</span>
                      </div>
                    </td>
                  </tr>
                )
              })}
              {legal.length === 0 && <tr><td colSpan={9} className="text-center py-8 text-slate-400">법정교육 현황이 없습니다</td></tr>}
            </tbody>
          </table>
        </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">교육과정 등록</h2>
            <div className="space-y-4">
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">과정명*</label>
                <input value={form.courseName} onChange={e => setForm({...form, courseName: e.target.value})}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none" />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-medium text-slate-600 mb-1">카테고리</label>
                  <select value={form.category} onChange={e => setForm({...form, category: e.target.value})}
                    className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm">
                    {Object.entries(categoryLabel).map(([v,l]) => <option key={v} value={v}>{l as string}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-600 mb-1">제공기관</label>
                  <input value={form.provider} onChange={e => setForm({...form, provider: e.target.value})}
                    className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none" />
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-600 mb-1">시작일</label>
                  <input type="date" value={form.startDate} onChange={e => setForm({...form, startDate: e.target.value})}
                    className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none" />
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-600 mb-1">종료일</label>
                  <input type="date" value={form.endDate} onChange={e => setForm({...form, endDate: e.target.value})}
                    className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none" />
                </div>
              </div>
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">정원</label>
                <input type="number" value={form.maxCapacity} onChange={e => setForm({...form, maxCapacity: +e.target.value})}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none" min={1} />
              </div>
            </div>
            <div className="flex justify-end gap-3 mt-5">
              <button className="btn-secondary" onClick={() => setShowForm(false)}>취소</button>
              <button className="btn-primary" onClick={save}>저장</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
