import { useEffect, useState } from 'react'
import { personalWorkStats, companyWorkStats } from '../../api/uiws'
import { PageHeader, SearchBar, Input, Button, Spinner } from '../../components/uiws/ui'

interface PivotColumn { key: string; label: string }
interface PivotResponse { fixedColumns: PivotColumn[]; dynamicColumns: PivotColumn[]; rows: Record<string, unknown>[] }

type Mode = 'personal' | 'company'

export default function StatsPivot() {
  const [mode, setMode] = useState<Mode>('personal')
  const [data, setData] = useState<PivotResponse | null>(null)
  const [loading, setLoading] = useState(false)
  const today = new Date().toISOString().slice(0, 10)
  const weekAgo = new Date(Date.now() - 6 * 864e5).toISOString().slice(0, 10)
  const [fromDate, setFromDate] = useState(weekAgo)
  const [toDate, setToDate] = useState(today)

  const load = async () => {
    setLoading(true)
    try {
      const fn = mode === 'personal' ? personalWorkStats : companyWorkStats
      const res = await fn({ fromDate, toDate })
      setData(res.data.data)
    } finally {
      setLoading(false)
    }
  }
  useEffect(() => { load() }, [mode])

  const cols = data ? [...data.fixedColumns, ...data.dynamicColumns] : []

  return (
    <div className="uiws-scope">
      <PageHeader title="업무통계" subtitle="UIWS 이식 · 근무현황 동적 피벗" />

      <SearchBar>
        <Button variant={mode === 'personal' ? 'primary' : 'ghost'} onClick={() => setMode('personal')}>개인별 근무현황</Button>
        <Button variant={mode === 'company' ? 'primary' : 'ghost'} onClick={() => setMode('company')}>업체별 근무현황</Button>
        <div style={{ flex: 1 }} />
        <Input type="date" value={fromDate} onChange={setFromDate} />
        <span style={{ color: 'var(--uiws-text-muted)' }}>~</span>
        <Input type="date" value={toDate} onChange={setToDate} />
        <Button variant="ghost" onClick={load}>조회</Button>
      </SearchBar>

      {loading ? <Spinner /> : !data || data.rows.length === 0 ? (
        <div style={{ padding: 28, textAlign: 'center', color: 'var(--uiws-text-faint)' }}>집계 데이터가 없습니다.</div>
      ) : (
        <div style={{ background: 'var(--uiws-surface)', border: '1px solid var(--uiws-border)', borderRadius: 12, overflow: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, color: 'var(--uiws-text)' }}>
            <thead>
              <tr style={{ background: 'var(--uiws-surface-2)' }}>
                {cols.map(c => (
                  <th key={c.key} style={{ padding: '11px 14px', textAlign: 'left', fontSize: 12, fontWeight: 600,
                    color: 'var(--uiws-text-muted)', borderBottom: '1px solid var(--uiws-border)', whiteSpace: 'nowrap' }}>{c.label}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {data.rows.map((row, i) => (
                <tr key={i} style={{ borderBottom: '1px solid var(--uiws-border)' }}>
                  {cols.map(c => (
                    <td key={c.key} style={{ padding: '10px 14px' }}>{String(row[c.key] ?? '')}</td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}
