/**
 * 数据表格组件 - 显示结构化数据
 */

import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { format } from 'date-fns';
import type { ComponentPropsMap, RenderContext, TableColumn } from '../types';

interface DataTableProps {
  props: ComponentPropsMap['data_table'];
  context: RenderContext;
}

export function DataTable({ props, context }: DataTableProps) {
  const { title, columns = [], data = [], actions, pagination = false, pageSize = 10 } = props || {};
  const [page, setPage] = useState(0);

  // Handle rows prop (alternative to data)
  const rows = (props as any)?.rows || data || [];
  
  const displayData = pagination 
    ? rows.slice(page * pageSize, (page + 1) * pageSize)
    : rows;

  const totalPages = Math.ceil(rows.length / pageSize);
  const safeColumns = columns || [];

  const renderCell = (row: Record<string, any>, column: TableColumn) => {
    const value = row[column.key];

    switch (column.type) {
      case 'date':
        return value ? format(new Date(value), 'yyyy-MM-dd HH:mm') : '-';
      case 'status':
        const statusColors: Record<string, string> = {
          pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200',
          processing: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
          completed: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
          rejected: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200',
        };
        return (
          <Badge className={statusColors[value] || ''} variant="outline">
            {value}
          </Badge>
        );
      case 'number':
        return typeof value === 'number' ? value.toLocaleString() : value;
      case 'action':
        return (
          <div className="flex gap-2">
            {actions?.map(action => (
              <Button
                key={action.id}
                size="sm"
                variant={action.variant || 'outline'}
                disabled={action.disabled}
                onClick={() => context.onAction?.(action.action, { ...action.params, rowId: row.id })}
              >
                {action.label}
              </Button>
            ))}
          </div>
        );
      default:
        return value ?? '-';
    }
  };

  return (
    <Card className="border-border/60">
      {title && (
        <CardHeader className="pb-3">
          <CardTitle className="text-base">{title}</CardTitle>
        </CardHeader>
      )}
      <CardContent className={title ? 'pt-0' : ''}>
        <div className="rounded-lg border border-border/60 overflow-hidden">
          <Table>
            <TableHeader className="bg-muted/40">
              <TableRow className="hover:bg-transparent border-border/60">
                {safeColumns.map(column => (
                  <TableHead
                    key={column.key}
                    style={{ width: column.width }}
                    className="text-xs font-semibold text-muted-foreground uppercase tracking-wide h-10"
                  >
                    {column.label}
                  </TableHead>
                ))}
              </TableRow>
            </TableHeader>
            <TableBody>
              {displayData.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={safeColumns.length || 1} className="text-center text-muted-foreground py-10">
                    暂无数据
                  </TableCell>
                </TableRow>
              ) : (
                displayData.map((row: Record<string, any>, idx: number) => (
                  <TableRow key={row.id || idx} className="border-border/40 hover:bg-muted/30 transition-colors">
                    {safeColumns.map(column => (
                      <TableCell key={column.key} className="py-3">
                        {renderCell(row, column)}
                      </TableCell>
                    ))}
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
        
        {pagination && totalPages > 1 && (
          <div className="flex items-center justify-between mt-4">
            <span className="text-sm text-muted-foreground">
              共 {rows.length} 条，第 {page + 1}/{totalPages} 页
            </span>
            <div className="flex gap-2">
              <Button
                size="sm"
                variant="outline"
                disabled={page === 0}
                onClick={() => setPage(p => p - 1)}
              >
                上一页
              </Button>
              <Button
                size="sm"
                variant="outline"
                disabled={page >= totalPages - 1}
                onClick={() => setPage(p => p + 1)}
              >
                下一页
              </Button>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
