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

export default function RecruitmentPage() {
  const [postings, setPostings] = useState<any[]>([])
  const [total, setTotal] = useState(0)
  const [tab, setTab] = useState<'posting'|'applicant'>('posting')
  const [applicants, setApplicants] = useState<any[]>([])
  const [showForm, setShowForm] = useState(false)
  const [form, setForm] = useState<any>({ title: '', employmentType: 'REGULAR', headcount: 1, startDate: '', endDate: '', description: '' })

  const loadPostings = () => {
    api.get('/recruitment/postings', { params: { page: 1, size: 20 } })
      .then(r => { setPostings(r.data.data.items || []); setTotal(r.data.data.total || 0) })
      .catch(() => {})
  }

  const loadApplicants = () => {
    api.get('/recruitment/applicants', { params: { status: '' } })
      .then(r => setApplicants(r.data.data || [])).catch(() => {})
  }

  useEffect(() => { loadPostings(); loadApplicants() }, [])

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

  const statusBadge = (s: string) => {
    const m: any = { DRAFT:'bg-slate-100 text-slate-600', PUBLISHED:'bg-green-100 text-green-700', CLOSED:'bg-red-100 text-red-700' }
    const l: any = { DRAFT:'초안', PUBLISHED:'공개중', CLOSED:'마감' }
    return <span className={`badge ${m[s]||''}`}>{l[s]||s}</span>
  }

  const appStatusBadge = (s: string) => {
    const m: any = { APPLIED:'bg-blue-100 text-blue-700', REVIEWED:'bg-yellow-100 text-yellow-700',
      INTERVIEW:'bg-purple-100 text-purple-700', OFFER:'bg-green-100 text-green-700',
      HIRED:'bg-emerald-100 text-emerald-700', REJECTED:'bg-red-100 text-red-700' }
    const l: any = { APPLIED:'지원', REVIEWED:'서류검토', INTERVIEW:'면접', OFFER:'합격통보', HIRED:'채용확정', REJECTED:'불합격' }
    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:'posting',l:`채용공고 (${total}건)`},{v:'applicant',l:`지원자 (${applicants.length}명)`}].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 === 'posting' && (
        <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>
              {postings.map((p: any) => (
                <tr key={p.id} className="border-b border-slate-50 hover:bg-slate-50">
                  <td className="table-cell font-medium">{p.title}</td>
                  <td className="table-cell">{p.dept_name || '-'}</td>
                  <td className="table-cell">{p.employment_type === 'REGULAR' ? '정규직' : '계약직'}</td>
                  <td className="table-cell">{p.headcount}명</td>
                  <td className="table-cell">{p.applicant_count || 0}명</td>
                  <td className="table-cell text-xs">{p.start_date} ~ {p.end_date}</td>
                  <td className="table-cell">{statusBadge(p.status)}</td>
                  <td className="table-cell">
                    {p.status === 'DRAFT' && (
                      <button className="text-blue-600 text-xs hover:underline"
                        onClick={async () => { await api.post(`/recruitment/postings/${p.id}/publish`); loadPostings() }}>공개</button>
                    )}
                    {p.status === 'PUBLISHED' && (
                      <button className="text-red-600 text-xs hover:underline"
                        onClick={async () => { await api.post(`/recruitment/postings/${p.id}/close`); loadPostings() }}>마감</button>
                    )}
                  </td>
                </tr>
              ))}
              {postings.length === 0 && <tr><td colSpan={8} className="text-center py-8 text-slate-400">채용공고가 없습니다</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'applicant' && (
        <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>
              {applicants.map((a: any) => (
                <tr key={a.id} className="border-b border-slate-50 hover:bg-slate-50">
                  <td className="table-cell font-medium">{a.applicant_name}</td>
                  <td className="table-cell">{a.email}</td>
                  <td className="table-cell text-xs">{a.apply_date?.slice(0,10)}</td>
                  <td className="table-cell">{appStatusBadge(a.status)}</td>
                  <td className="table-cell">
                    <select value={a.status}
                      onChange={async e => {
                        await api.patch(`/recruitment/applicants/${a.id}/status`, null, {params:{status:e.target.value}})
                        loadApplicants()
                      }}
                      className="border border-slate-200 rounded px-2 py-1 text-xs">
                      {['APPLIED','REVIEWED','INTERVIEW','OFFER','HIRED','REJECTED'].map(s => <option key={s} value={s}>{s}</option>)}
                    </select>
                  </td>
                </tr>
              ))}
              {applicants.length === 0 && <tr><td colSpan={5} 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.title} onChange={e => setForm({...form, title: 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.employmentType} 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>
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-600 mb-1">모집인원</label>
                  <input type="number" value={form.headcount} onChange={e => setForm({...form, headcount: +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>
                  <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>
                <textarea value={form.description} onChange={e => setForm({...form, description: e.target.value})}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none" rows={3} />
              </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>
  )
}
