'use client'

import { Plus, Trash2 } from 'lucide-react'

interface RowTableProps {
  rows: Record<string, unknown>[]
  onChange: (rows: Record<string, unknown>[]) => void
  columns?: { key: string; label: string; type?: 'text' | 'number' }[]
  addLabel?: string
}

export default function RowTable({ rows, onChange, columns, addLabel }: RowTableProps) {
  // Auto-detect columns from first row if not provided
  const cols = columns || (rows.length > 0
    ? Object.keys(rows[0]).filter(k => k !== 'id' && k !== 'sort_order').map(k => ({
        key: k,
        label: k.replace(/_/g, ' '),
        type: (typeof rows[0][k] === 'number' ? 'number' : 'text') as 'text' | 'number',
      }))
    : [])

  function updateCell(rowIdx: number, key: string, value: string) {
    const col = cols.find(c => c.key === key)
    const parsedValue = col?.type === 'number' ? (Number(value) || 0) : value
    onChange(rows.map((r, i) => i === rowIdx ? { ...r, [key]: parsedValue } : r))
  }

  function addRow() {
    const newRow: Record<string, unknown> = {}
    cols.forEach(c => { newRow[c.key] = c.type === 'number' ? 0 : '' })
    // Carry over id-like fields
    if (rows.length > 0 && 'id' in rows[0]) {
      newRow.id = (rows.length + 1)
    }
    if (rows.length > 0 && 'sort_order' in rows[0]) {
      newRow.sort_order = rows.length
    }
    onChange([...rows, newRow])
  }

  function removeRow(idx: number) {
    onChange(rows.filter((_, i) => i !== idx))
  }

  if (cols.length === 0) return <div className="text-white/40 text-sm">No columns detected</div>

  return (
    <div>
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-white/[0.08]">
              {cols.map(c => (
                <th key={c.key} className="text-left py-2 px-2 text-[10px] text-white/40 font-medium uppercase tracking-wider whitespace-nowrap">
                  {c.label}
                </th>
              ))}
              <th className="w-8" />
            </tr>
          </thead>
          <tbody>
            {rows.map((row, ri) => (
              <tr key={ri} className="border-b border-white/[0.04] hover:bg-white/[0.02]">
                {cols.map(c => (
                  <td key={c.key} className="py-1 px-2">
                    <input
                      type={c.type || 'text'}
                      value={(row[c.key] as string | number) ?? ''}
                      onChange={e => updateCell(ri, c.key, e.target.value)}
                      className="w-full bg-transparent border-b border-transparent hover:border-white/10 focus:border-indigo-500/50 text-white font-mono text-xs py-1 focus:outline-none min-w-[60px]"
                    />
                  </td>
                ))}
                <td className="py-1 px-1">
                  <button onClick={() => removeRow(ri)} className="text-white/30 hover:text-rose-400 p-1" title="Remove">
                    <Trash2 className="w-3 h-3" />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <button
        onClick={addRow}
        className="mt-2 text-xs text-white/50 hover:text-white flex items-center gap-1 px-2 py-1 rounded hover:bg-white/[0.04]"
      >
        <Plus className="w-3 h-3" /> {addLabel || 'Add row'}
      </button>
    </div>
  )
}
