'use client'

import { useState, useRef, useEffect } from 'react'

interface Column {
  key: string
  label: string
  sortable?: boolean
}

interface Row {
  id: string
  [key: string]: any
}

export interface RowAction {
  key: string
  label: string
  icon?: React.ReactNode
  destructive?: boolean
  onClick: (row: Row) => void
}

export interface DataTableProps {
  columns: Column[]
  rows: Row[]
  selectedIds: string[]
  onSelectionChange: (ids: string[]) => void
  sortField?: string
  sortDir?: 'asc' | 'desc'
  onSort?: (field: string) => void
  rowActions?: RowAction[]
  onRowClick?: (row: Row) => void
}

export function DataTable({
  columns,
  rows,
  selectedIds,
  onSelectionChange,
  sortField,
  sortDir,
  onSort,
  rowActions,
  onRowClick,
}: DataTableProps) {
  const allSelected = rows.length > 0 && selectedIds.length === rows.length

  function toggleAll() {
    onSelectionChange(allSelected ? [] : rows.map((r) => r.id))
  }

  function toggleRow(id: string) {
    onSelectionChange(
      selectedIds.includes(id) ? selectedIds.filter((s) => s !== id) : [...selectedIds, id],
    )
  }

  return (
    <div className="overflow-x-auto rounded-lg border border-[var(--border)]">
      <table className="w-full text-left text-sm">
        <thead className="border-b border-[var(--border)] bg-[var(--muted)]">
          <tr>
            <th className="w-10 px-4 py-3">
              <input
                type="checkbox"
                checked={allSelected}
                onChange={toggleAll}
                className="rounded border-[var(--border)]"
              />
            </th>
            {columns.map((col) => (
              <th key={col.key} className="px-4 py-3 font-medium">
                {col.sortable && onSort ? (
                  <button
                    onClick={() => onSort(col.key)}
                    className="inline-flex items-center gap-1 hover:text-[var(--foreground)]"
                  >
                    {col.label}
                    {sortField === col.key && (
                      <span className="text-xs">{sortDir === 'asc' ? '↑' : '↓'}</span>
                    )}
                  </button>
                ) : (
                  col.label
                )}
              </th>
            ))}
            {rowActions && rowActions.length > 0 && <th className="w-20 px-4 py-3" />}
          </tr>
        </thead>
        <tbody className="divide-y divide-[var(--border)]">
          {rows.map((row) => (
            <tr
              key={row.id}
              className={`hover:bg-[var(--accent)] ${selectedIds.includes(row.id) ? 'bg-[var(--accent)]' : ''}`}
              onClick={() => onRowClick?.(row)}
              style={onRowClick ? { cursor: 'pointer' } : undefined}
            >
              <td className="px-4 py-3" onClick={(e) => e.stopPropagation()}>
                <input
                  type="checkbox"
                  checked={selectedIds.includes(row.id)}
                  onChange={() => toggleRow(row.id)}
                  className="rounded border-[var(--border)]"
                />
              </td>
              {columns.map((col) => (
                <td key={col.key} className="px-4 py-3">
                  {row[col.key]}
                </td>
              ))}
              {rowActions && rowActions.length > 0 && (
                <td className="px-4 py-3" onClick={(e) => e.stopPropagation()}>
                  <RowActionsMenu actions={rowActions} row={row} />
                </td>
              )}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

function RowActionsMenu({ actions, row }: { actions: RowAction[]; row: Row }) {
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!open) return
    function handleClickOutside(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [open])

  return (
    <div className="relative flex items-center justify-end gap-1" ref={ref}>
      {actions
        .filter((a) => a.icon)
        .map((action) => (
          <button
            key={action.key}
            onClick={() => action.onClick(row)}
            className="rounded p-1 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
            aria-label={action.label}
            title={action.label}
          >
            {action.icon}
          </button>
        ))}
      <button
        onClick={() => setOpen((o) => !o)}
        className="rounded p-1 hover:bg-[var(--muted)]"
        aria-label="More actions"
      >
        <MoreVerticalIcon />
      </button>
      {open && (
        <div className="absolute top-full right-0 z-50 mt-1 w-40 rounded-md border border-[var(--border)] bg-[var(--popover)] py-1 shadow-lg">
          {actions.map((action) => (
            <button
              key={action.key}
              className={`flex w-full items-center gap-2 px-3 py-1.5 text-sm hover:bg-[var(--accent)] ${
                action.destructive ? 'text-[var(--destructive)]' : ''
              }`}
              onClick={() => {
                action.onClick(row)
                setOpen(false)
              }}
            >
              {action.icon && <span className="h-4 w-4">{action.icon}</span>}
              {action.label}
            </button>
          ))}
        </div>
      )}
    </div>
  )
}

function MoreVerticalIcon() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M12 5v.01M12 12v.01M12 19v.01" />
    </svg>
  )
}
