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

export default function AttendancePage() {
  const [records, setRecords] = useState<any[]>([])
  const [leaves, setLeaves] = useState<any[]>([])
  const [leaveTypes, setLeaveTypes] = useState<any[]>([])
  const [tab, setTab] = useState<'att'|'leave'>('att')
  const [showLeaveForm, setShowLeaveForm] = useState(false)
  const [leaveForm, setLeaveForm] = useState<any>({ empId: '', leaveTypeId: '', startDate: '', endDate: '', days: 1, reason: '' })

  const loadAtt = () => {
    const today = new Date().toISOString().slice(0,10)
    api.get('/attendance', { params: { date: today } }).then(r => setRecords(r.data.data.items || [])).catch(() => {})
  }

  const loadLeaves = () => {
    api.get('/attendance/leaves/1', { params: { status: 'PENDING', year: new Date().getFullYear() } })
      .then(r => setLeaves(r.data.data || [])).catch(() => {})
    api.get('/attendance/leave-types').then(r => setLeaveTypes(r.data.data || [])).catch(() => {})
  }

  useEffect(() => { loadAtt(); loadLeaves() }, [])

  const applyLeave = async () => {
    try {
      await api.post(`/attendance/leaves/${leaveForm.empId}`, leaveForm)
      setShowLeaveForm(false); loadLeaves()
    } catch (e: any) { alert(e.response?.data?.message || '신청 실패') }
  }

  const statusBadge = (s: string) => {
    const m: any = { PENDING: 'bg-yellow-100 text-yellow-700', APPROVED: 'bg-green-100 text-green-700', REJECTED: 'bg-red-100 text-red-700' }
    const l: any = { PENDING: '승인대기', APPROVED: '승인', 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={() => setShowLeaveForm(true)}>+ 휴가 신청</button>
      </div>

      <div className="flex gap-2 border-b border-slate-200">
        {[{v:'att',l:'출결 현황'},{v:'leave',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 === 'att' && (
        <div className="card overflow-x-auto">
          <h2 className="text-base font-semibold text-slate-700 mb-4">오늘 출결 현황 ({new Date().toLocaleDateString('ko-KR')})</h2>
          <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>
              {records.map((r: any) => (
                <tr key={r.id} className="border-b border-slate-50 hover:bg-slate-50">
                  <td className="table-cell font-mono text-xs">{r.emp_no}</td>
                  <td className="table-cell font-medium">{r.emp_name}</td>
                  <td className="table-cell">{r.dept_name}</td>
                  <td className="table-cell">{r.check_in_time?.slice(11,16) || '-'}</td>
                  <td className="table-cell">{r.check_out_time?.slice(11,16) || '-'}</td>
                  <td className="table-cell">{r.work_minutes ? Math.floor(r.work_minutes/60)+'h '+r.work_minutes%60+'m' : '-'}</td>
                  <td className="table-cell">
                    <span className={`badge ${r.status==='PRESENT'?'bg-green-100 text-green-700':'bg-slate-100 text-slate-600'}`}>
                      {r.status==='PRESENT'?'출근':r.status}
                    </span>
                  </td>
                </tr>
              ))}
              {records.length === 0 && <tr><td colSpan={7} className="text-center py-8 text-slate-400">출결 데이터가 없습니다</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'leave' && (
        <div className="card overflow-x-auto">
          <h2 className="text-base font-semibold text-slate-700 mb-4">휴가 신청 현황</h2>
          <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>
              {leaves.map((l: any) => (
                <tr key={l.id} className="border-b border-slate-50">
                  <td className="table-cell">{l.type_name}</td>
                  <td className="table-cell">{l.start_date}</td>
                  <td className="table-cell">{l.end_date}</td>
                  <td className="table-cell">{l.days}일</td>
                  <td className="table-cell">{l.reason}</td>
                  <td className="table-cell">{statusBadge(l.status)}</td>
                  <td className="table-cell">
                    {l.status === 'PENDING' && (
                      <div className="flex gap-2">
                        <button className="text-green-600 text-xs hover:underline"
                          onClick={async () => { await api.patch(`/attendance/leaves/${l.id}/approve`, null, {params:{status:'APPROVED'}}); loadLeaves() }}>승인</button>
                        <button className="text-red-600 text-xs hover:underline"
                          onClick={async () => { await api.patch(`/attendance/leaves/${l.id}/approve`, null, {params:{status:'REJECTED'}}); loadLeaves() }}>반려</button>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
              {leaves.length === 0 && <tr><td colSpan={7} className="text-center py-8 text-slate-400">휴가 신청 내역이 없습니다</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {showLeaveForm && (
        <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-md 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">사원 ID</label>
                <input type="number" value={leaveForm.empId} onChange={e => setLeaveForm({...leaveForm, empId: e.target.value})}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none" placeholder="사원 ID" />
              </div>
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">휴가 유형</label>
                <select value={leaveForm.leaveTypeId} onChange={e => setLeaveForm({...leaveForm, leaveTypeId: e.target.value})}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm">
                  <option value="">선택</option>
                  {leaveTypes.map((t:any) => <option key={t.id} value={t.id}>{t.type_name}</option>)}
                </select>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-medium text-slate-600 mb-1">시작일</label>
                  <input type="date" value={leaveForm.startDate} onChange={e => setLeaveForm({...leaveForm, 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={leaveForm.endDate} onChange={e => setLeaveForm({...leaveForm, 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={leaveForm.reason} onChange={e => setLeaveForm({...leaveForm, reason: e.target.value})}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none" rows={2} />
              </div>
            </div>
            <div className="flex justify-end gap-3 mt-5">
              <button className="btn-secondary" onClick={() => setShowLeaveForm(false)}>취소</button>
              <button className="btn-primary" onClick={applyLeave}>신청</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
