import { useQuery } from '@tanstack/react-query'
import { getWorks } from '../api/client'

const statusColor: Record<string, string> = {
  SCHEDULED:   'bg-blue-500/20 text-blue-400',
  IN_PROGRESS: 'bg-yellow-500/20 text-yellow-400',
  COMPLETED:   'bg-green-500/20 text-green-400',
  CANCELLED:   'bg-gray-500/20 text-gray-400',
}

export default function WorkHistory() {
  const { data: works = [], isLoading } = useQuery({
    queryKey: ['works'],
    queryFn:  () => getWorks(),
  })

  if (isLoading) return <div className="text-gray-400 p-8">로딩 중...</div>

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-semibold text-white">작업 이력</h1>

      <div className="bg-card border border-edge rounded-lg overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-panel border-b border-edge">
            <tr>
              {['테넌트','매장','작업유형','작업내용','담당자','상태','시작일시','완료일시'].map(h => (
                <th key={h} className="px-4 py-3 text-left text-xs text-gray-400 font-medium">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {(works as any[]).map((w: any) => (
              <tr key={w.id} className="border-b border-edge hover:bg-edge/30">
                <td className="px-4 py-3 text-brand text-xs">{w.tenantCode}</td>
                <td className="px-4 py-3 text-gray-300">{w.storeName || '-'}</td>
                <td className="px-4 py-3 text-gray-300 text-xs">{w.workType}</td>
                <td className="px-4 py-3 text-gray-400 text-xs max-w-xs truncate">{w.workContent}</td>
                <td className="px-4 py-3 text-gray-300">{w.workerName}</td>
                <td className="px-4 py-3">
                  <span className={`px-2 py-0.5 rounded text-xs ${statusColor[w.status] || 'bg-gray-500/20 text-gray-400'}`}>
                    {w.status}
                  </span>
                </td>
                <td className="px-4 py-3 text-gray-500 text-xs">
                  {w.startedAt ? new Date(w.startedAt).toLocaleString('ko-KR') : '-'}
                </td>
                <td className="px-4 py-3 text-gray-500 text-xs">
                  {w.completedAt ? new Date(w.completedAt).toLocaleString('ko-KR') : '-'}
                </td>
              </tr>
            ))}
            {(works as any[]).length === 0 && (
              <tr><td colSpan={8} className="px-4 py-8 text-center text-gray-500">작업 이력이 없습니다</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
