import React from 'react';
import { cn } from '@/lib/utils';

/**
 * 控制台数据表格容器组件
 * 提供统一的表格布局和样式基础
 */

interface DataTableShellProps {
  /** 表格标题 */
  title?: string;
  /** 标题右侧的操作区 */
  titleAction?: React.ReactNode;
  /** 表格内容 */
  children: React.ReactNode;
  /** 空状态内容 */
  empty?: React.ReactNode;
  /** 是否为空 */
  isEmpty?: boolean;
  /** 额外的 className */
  className?: string;
  /** 表格容器的 className */
  tableClassName?: string;
}

/**
 * 数据表格容器组件
 * 用于控制台中统一展示表格数据
 */
export function DataTableShell({
  title,
  titleAction,
  children,
  empty,
  isEmpty = false,
  className,
  tableClassName,
}: DataTableShellProps) {
  return (
    <div className={cn('w-full', className)}>
      {/* 标题行 */}
      {(title || titleAction) && (
        <div className="flex items-center justify-between mb-2">
          {title && (
            <h3 className="text-sm font-medium text-console-text-primary">
              {title}
            </h3>
          )}
          {titleAction && (
            <div className="flex items-center gap-2">
              {titleAction}
            </div>
          )}
        </div>
      )}

      {/* 表格容器 */}
      {isEmpty ? (
        empty || (
          <div className="py-8 text-center text-xs text-console-text-muted">
            暂无数据
          </div>
        )
      ) : (
        <div className={cn(
          'overflow-auto border border-console-border rounded-console-md',
          tableClassName
        )}>
          <table className="w-full text-xs">
            {children}
          </table>
        </div>
      )}
    </div>
  );
}

/**
 * 表格头部组件
 */
interface DataTableHeadProps {
  children: React.ReactNode;
  className?: string;
}

export function DataTableHead({ children, className }: DataTableHeadProps) {
  return (
    <thead className={cn('bg-console-surface-raised', className)}>
      {children}
    </thead>
  );
}

/**
 * 表格行组件
 */
interface DataTableRowProps {
  children: React.ReactNode;
  className?: string;
  onClick?: () => void;
}

export function DataTableRow({ children, className, onClick }: DataTableRowProps) {
  return (
    <tr
      className={cn(
        'border-b border-console-border last:border-0',
        onClick && 'cursor-pointer hover:bg-console-surface-raised',
        className
      )}
      onClick={onClick}
      role={onClick ? 'button' : undefined}
      tabIndex={onClick ? 0 : undefined}
    >
      {children}
    </tr>
  );
}

/**
 * 表格单元格组件
 */
interface DataTableCellProps {
  children: React.ReactNode;
  className?: string;
  header?: boolean;
}

export function DataTableCell({ children, className, header }: DataTableCellProps) {
  const Tag = header ? 'th' : 'td';
  return (
    <Tag
      className={cn(
        'px-3 py-2 text-left',
        header && 'font-medium text-console-text-secondary bg-console-surface-raised',
        !header && 'text-console-text-primary',
        className
      )}
    >
      {children}
    </Tag>
  );
}
