'use client'

import { ReactNode } from 'react'
import clsx from 'clsx'

interface Column<T> {
  key: string
  header: string
  render?: (item: T, index: number) => ReactNode
  className?: string
  headerClassName?: string
  hideOnMobile?: boolean
}

interface DataTableProps<T> {
  data: T[]
  columns: Column<T>[]
  keyExtractor: (item: T) => string | number
  onRowClick?: (item: T) => void
  emptyState?: ReactNode
  loading?: boolean
  selectable?: boolean
  selectedIds?: (string | number)[]
  onSelectionChange?: (ids: (string | number)[]) => void
}

export function DataTable<T>({
  data,
  columns,
  keyExtractor,
  onRowClick,
  emptyState,
  loading,
  selectable,
  selectedIds = [],
  onSelectionChange,
}: DataTableProps<T>) {
  const toggleSelection = (id: string | number) => {
    if (!onSelectionChange) return
    if (selectedIds.includes(id)) {
      onSelectionChange(selectedIds.filter(i => i !== id))
    } else {
      onSelectionChange([...selectedIds, id])
    }
  }

  const toggleSelectAll = () => {
    if (!onSelectionChange) return
    if (selectedIds.length === data.length) {
      onSelectionChange([])
    } else {
      onSelectionChange(data.map(keyExtractor))
    }
  }

  if (loading) {
    return (
      <div className="relative overflow-hidden rounded-2xl border border-border/50 bg-gradient-to-b from-background-secondary/50 to-background-secondary/20">
        <div className="divide-y divide-border/30">
          {[...Array(5)].map((_, i) => (
            <div key={i} className="px-6 py-5 flex gap-4">
              <div className="h-5 w-32 bg-foreground/5 rounded-lg animate-pulse" />
              <div className="h-5 w-24 bg-foreground/5 rounded-lg animate-pulse" />
              <div className="h-5 w-20 bg-foreground/5 rounded-lg animate-pulse ml-auto" />
            </div>
          ))}
        </div>
      </div>
    )
  }

  if (data.length === 0) {
    return (
      <div className="relative overflow-hidden rounded-2xl border border-border/50 bg-gradient-to-b from-background-secondary/50 to-background-secondary/20">
        <div className="px-8 py-16 text-center">
          {emptyState || (
            <p className="text-foreground-muted">No data available</p>
          )}
        </div>
      </div>
    )
  }

  return (
    <div className="relative overflow-hidden rounded-2xl border border-border/50 bg-gradient-to-b from-background-secondary/50 to-background-secondary/20 shadow-[0_4px_24px_-4px_rgba(0,0,0,0.1)]">
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr className="border-b border-border/50">
              {selectable && (
                <th className="w-12 px-4 py-4">
                  <input
                    type="checkbox"
                    checked={selectedIds.length === data.length && data.length > 0}
                    onChange={toggleSelectAll}
                    className="w-4 h-4 rounded border-border/50 bg-background-secondary text-accent 
                               focus:ring-accent/20 focus:ring-offset-0 cursor-pointer"
                  />
                </th>
              )}
              {columns.map((col) => (
                <th
                  key={col.key}
                  className={clsx(
                    "text-left px-6 py-4 text-xs font-semibold text-foreground-subtle/80 uppercase tracking-wider",
                    col.hideOnMobile && "hidden md:table-cell",
                    col.headerClassName
                  )}
                >
                  {col.header}
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-border/30">
            {data.map((item, index) => {
              const key = keyExtractor(item)
              const isSelected = selectedIds.includes(key)
              
              return (
                <tr
                  key={key}
                  onClick={() => onRowClick?.(item)}
                  className={clsx(
                    "group transition-all duration-200",
                    onRowClick && "cursor-pointer",
                    isSelected 
                      ? "bg-accent/5" 
                      : "hover:bg-foreground/[0.02]"
                  )}
                >
                  {selectable && (
                    <td className="w-12 px-4 py-4" onClick={(e) => e.stopPropagation()}>
                      <input
                        type="checkbox"
                        checked={isSelected}
                        onChange={() => toggleSelection(key)}
                        className="w-4 h-4 rounded border-border/50 bg-background-secondary text-accent 
                                   focus:ring-accent/20 focus:ring-offset-0 cursor-pointer"
                      />
                    </td>
                  )}
                  {columns.map((col) => (
                    <td
                      key={col.key}
                      className={clsx(
                        "px-6 py-4 text-sm",
                        col.hideOnMobile && "hidden md:table-cell",
                        col.className
                      )}
                    >
                      {col.render 
                        ? col.render(item, index) 
                        : (item as Record<string, unknown>)[col.key] as ReactNode
                      }
                    </td>
                  ))}
                </tr>
              )
            })}
          </tbody>
        </table>
      </div>
    </div>
  )
}

// Status badge component for tables
export function StatusBadge({ 
  status, 
  variant = 'default' 
}: { 
  status: string
  variant?: 'success' | 'warning' | 'error' | 'default' | 'accent'
}) {
  return (
    <span className={clsx(
      "inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-lg",
      variant === 'success' && "bg-accent/10 text-accent border border-accent/20",
      variant === 'warning' && "bg-amber-500/10 text-amber-400 border border-amber-500/20",
      variant === 'error' && "bg-red-500/10 text-red-400 border border-red-500/20",
      variant === 'accent' && "bg-accent/10 text-accent border border-accent/20",
      variant === 'default' && "bg-foreground/5 text-foreground-muted border border-border/50"
    )}>
      {status}
    </span>
  )
}

// Action button for tables
export function TableAction({
  icon: Icon,
  onClick,
  variant = 'default',
  title,
  disabled,
}: {
  icon: React.ComponentType<{ className?: string }>
  onClick?: () => void
  variant?: 'default' | 'danger' | 'accent'
  title?: string
  disabled?: boolean
}) {
  return (
    <button
      onClick={(e) => {
        e.stopPropagation()
        onClick?.()
      }}
      disabled={disabled}
      title={title}
      className={clsx(
        "p-2 rounded-lg transition-all duration-200",
        "disabled:opacity-30 disabled:cursor-not-allowed",
        variant === 'danger' && "bg-red-500/10 text-red-400 hover:bg-red-500/20 border border-red-500/20",
        variant === 'accent' && "bg-accent/10 text-accent hover:bg-accent/20 border border-accent/20",
        variant === 'default' && "bg-foreground/5 text-foreground-muted hover:text-foreground hover:bg-foreground/10 border border-border/50"
      )}
    >
      <Icon className="w-4 h-4" />
    </button>
  )
}

