import { useState } from 'react'

export interface Col<T> {
  key: string
  header: string
  width?: string | number
  render?: (row: T) => React.ReactNode
  sortable?: boolean
}

interface Props<T extends { id: string | number }> {
  cols: Col<T>[]
  rows: T[]
  loading?: boolean
  empty?: string
  selectable?: boolean
  onSelect?: (rows: T[]) => void
  onRowClick?: (row: T) => void
  toolbar?: React.ReactNode
}

export function DataTable<T extends { id: string | number }>({
  cols, rows, loading, empty = '데이터가 없습니다.',
  selectable, onSelect, onRowClick, toolbar,
}: Props<T>) {
  const [sel, setSel] = useState<Set<string | number>>(new Set())

  const toggleAll = () => {
    const next = sel.size === rows.length ? new Set<string | number>() : new Set(rows.map(r => r.id))
    setSel(next); onSelect?.(rows.filter(r => next.has(r.id)))
  }
  const toggle = (id: string | number) => {
    const next = new Set(sel); next.has(id) ? next.delete(id) : next.add(id)
    setSel(next); onSelect?.(rows.filter(r => next.has(r.id)))
  }

  return (
    <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, overflow: 'hidden' }}>
      {toolbar && (
        <div style={{ padding: '12px 16px', borderBottom: '1px solid #f1f5f9',
          display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          {sel.size > 0 && <span style={{ fontSize: 12, color: '#4f6ef7', fontWeight: 600 }}>{sel.size}개 선택</span>}
          {toolbar}
        </div>
      )}
      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: '#f8fafc' }}>
              {selectable && (
                <th style={{ width: 40, padding: '10px 12px', textAlign: 'center', borderBottom: '1px solid #e2e8f0' }}>
                  <input type="checkbox" checked={sel.size === rows.length && rows.length > 0} onChange={toggleAll} />
                </th>
              )}
              {cols.map(c => (
                <th key={c.key} style={{
                  padding: '10px 14px', textAlign: 'left',
                  borderBottom: '1px solid #e2e8f0', fontWeight: 600,
                  fontSize: 11, textTransform: 'uppercase', letterSpacing: '.04em',
                  color: '#64748b', width: c.width, whiteSpace: 'nowrap',
                }}>{c.header}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr><td colSpan={cols.length + (selectable ? 1 : 0)} style={{ padding: 40, textAlign: 'center', color: '#94a3b8' }}>
                로딩 중...
              </td></tr>
            ) : rows.length === 0 ? (
              <tr><td colSpan={cols.length + (selectable ? 1 : 0)} style={{ padding: 40, textAlign: 'center', color: '#94a3b8' }}>
                {empty}
              </td></tr>
            ) : rows.map((row, i) => (
              <tr key={row.id}
                onClick={() => onRowClick?.(row)}
                style={{
                  borderBottom: i < rows.length - 1 ? '1px solid #f1f5f9' : 'none',
                  cursor: onRowClick ? 'pointer' : 'default',
                  background: sel.has(row.id) ? '#f0f4ff' : 'transparent',
                  transition: 'background .1s',
                }}
                onMouseEnter={e => { if (!sel.has(row.id)) (e.currentTarget as HTMLTableRowElement).style.background = '#f8fafc' }}
                onMouseLeave={e => { (e.currentTarget as HTMLTableRowElement).style.background = sel.has(row.id) ? '#f0f4ff' : 'transparent' }}
              >
                {selectable && (
                  <td style={{ padding: '10px 12px', textAlign: 'center' }}
                    onClick={e => { e.stopPropagation(); toggle(row.id) }}>
                    <input type="checkbox" checked={sel.has(row.id)} onChange={() => {}} />
                  </td>
                )}
                {cols.map(c => (
                  <td key={c.key} style={{ padding: '11px 14px', verticalAlign: 'middle' }}>
                    {c.render ? c.render(row) : String((row as Record<string, unknown>)[c.key] ?? '')}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
