"use client";

/**
 * 增强表格组件
 * 
 * 提供以下功能：
 * - 行级配置管理（显示/隐藏、排序）
 * - 虚拟化渲染（大数据集优化）
 * - 动画效果支持
 * - 配置预览模式
 * - 性能优化和错误处理
 * 
 * @author Financial Analysis Platform Team
 * @version 1.0.0
 */

import React, { useMemo, useCallback, useState } from "react";
import { cn } from "@/lib/utils";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { RowSettingsButton } from "@/components/ui/row-settings";
import { TableRowConfig } from "@/components/ui/row-settings";
import { DraggableRow } from "./draggable-row";
import { AddRowMenu } from "./add-row-menu";

// ============================================================================
// 类型定义
// ============================================================================

/**
 * 表格行数据接口
 */
export interface TableRowData {
  /** 行唯一标识符 */
  id: string;
  /** 显示文本 */
  displayText: string;
  /** 各年份/列的值 */
  values: Record<string, string | number | null>;
  /** 指标分组 */
  group?: string;
  /** API接口名 */
  api?: string;
  /** Tushare参数名 */
  tushareParam?: string;
  /** 是否为用户添加的自定义行 */
  isCustomRow?: boolean;
  /** 自定义行类型 */
  customRowType?: 'empty' | 'separator' | 'note';
}

/**
 * 增强表格组件属性
 */
export interface EnhancedTableProps {
  /** 表格数据 */
  data: TableRowData[];
  /** 列标题数组 */
  columns: string[];
  /** 行配置对象 */
  rowConfigs: Record<string, TableRowConfig>;
  /** 当前选中的行ID */
  selectedRowId?: string;
  /** 行点击回调 */
  onRowClick?: (rowId: string) => void;
  /** 配置变更回调 */
  onRowConfigChange: (configs: Record<string, TableRowConfig>) => void;
  /** 打开设置面板回调 */
  onOpenSettings: () => void;
  /** 添加新行回调 */
  onAddCustomRow?: (rowType: 'separator') => void;
  /** 删除自定义行回调 */
  onDeleteCustomRow?: (rowId: string) => void;
  /** 行顺序变更回调 */
  onRowOrderChange?: (newOrder: string[]) => void;
  /** 自定义CSS类名 */
  className?: string;
  /** 是否启用动画效果 */
  enableAnimations?: boolean;
  /** 动画持续时间（毫秒） */
  animationDuration?: number;
  /** 是否启用虚拟化渲染 */
  enableVirtualization?: boolean;
  /** 虚拟化最大可见行数 */
  maxVisibleRows?: number;
  /** 是否启用行拖拽排序 */
  enableRowDragging?: boolean;
}

// ============================================================================
// 子组件类型定义
// ============================================================================

/**
 * 虚拟化行组件属性
 */
interface VirtualizedRowProps {
  /** 行数据 */
  rowData: TableRowData;
  /** 列数组 */
  columns: string[];
  /** 是否可见 */
  isVisible: boolean;
  /** 是否选中 */
  isSelected: boolean;
  /** 点击回调 */
  onClick: () => void;
  /** 动画持续时间 */
  animationDuration: number;
}

/**
 * 虚拟化行组件
 * 
 * 使用React.memo优化性能，避免不必要的重渲染
 */
const VirtualizedRow = React.memo<VirtualizedRowProps>(({
  rowData,
  columns,
  isVisible,
  isSelected,
  onClick,
  animationDuration
}) => {
  return (
    <TableRow
      isVisible={isVisible}
      animationDuration={animationDuration}
      className={cn(
        "cursor-pointer transition-all duration-200",
        isSelected && "bg-indigo-50 border-indigo-200",
        "hover:bg-muted/70"
      )}
      onClick={onClick}
    >
      <TableCell className="font-medium">
        <div className="flex items-center gap-2">
          <span>{rowData.displayText}</span>
        </div>
      </TableCell>
      {columns.map((column) => (
        <TableCell key={column} className="text-right">
          {rowData.values[column] ?? "-"}
        </TableCell>
      ))}
    </TableRow>
  );
});

VirtualizedRow.displayName = "VirtualizedRow";

// ============================================================================
// 主组件
// ============================================================================

/**
 * 增强表格组件
 * 
 * 提供行级配置、虚拟化渲染、动画效果等高级功能
 * 
 * @param props - 组件属性
 * @returns JSX元素
 */
export function EnhancedTable({
  data,
  columns,
  rowConfigs,
  selectedRowId,
  onRowClick,
  onRowConfigChange,
  onOpenSettings,
  onAddCustomRow,
  onDeleteCustomRow,
  onRowOrderChange,
  className,
  enableAnimations = true,
  animationDuration = 300,
  enableVirtualization = false,
  maxVisibleRows = 50,
  enableRowDragging = true
}: EnhancedTableProps) {
  const [isConfigPreviewMode, setIsConfigPreviewMode] = useState(false);
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
  const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);

  // 过滤和排序可见行
  const visibleRows = useMemo(() => {
    try {
      const filtered = data.filter(row => {
        const config = rowConfigs[row.id];
        return config?.isVisible !== false;
      });

      // 确保至少有一行可见
      if (filtered.length === 0 && data.length > 0) {
        console.warn('No visible rows found, showing first row as fallback');
        return [data[0]];
      }

      return filtered.sort((a, b) => {
        const aOrder = rowConfigs[a.id]?.displayOrder ?? 0;
        const bOrder = rowConfigs[b.id]?.displayOrder ?? 0;
        return aOrder - bOrder;
      });
    } catch (error) {
      console.error('Error filtering visible rows:', error);
      // 发生错误时返回所有数据作为后备
      return data;
    }
  }, [data, rowConfigs]);

  // 虚拟化处理（仅在启用时）
  const displayRows = useMemo(() => {
    if (!enableVirtualization || visibleRows.length <= maxVisibleRows) {
      return visibleRows;
    }
    // 简单的虚拟化：只显示前N行
    return visibleRows.slice(0, maxVisibleRows);
  }, [visibleRows, enableVirtualization, maxVisibleRows]);

  // 行点击处理
  const handleRowClick = useCallback((rowId: string) => {
    if (onRowClick && !isConfigPreviewMode) {
      onRowClick(rowId);
    }
  }, [onRowClick, isConfigPreviewMode]);

  // 配置预览切换
  const toggleConfigPreview = useCallback(() => {
    setIsConfigPreviewMode(prev => !prev);
  }, []);

  // 快速显示/隐藏行
  const quickToggleRow = useCallback((rowId: string, event: React.MouseEvent) => {
    event.stopPropagation();
    
    try {
      const currentConfig = rowConfigs[rowId] || { rowId, isVisible: true, displayOrder: 0 };
      
      // 如果要隐藏行，检查是否会导致所有行都被隐藏
      if (currentConfig.isVisible) {
        const visibleCount = Object.values(rowConfigs).filter(config => config.isVisible).length;
        if (visibleCount <= 1) {
          console.warn('Cannot hide the last visible row');
          return;
        }
      }
      
      const newConfigs = {
        ...rowConfigs,
        [rowId]: {
          ...currentConfig,
          rowId,
          isVisible: !currentConfig.isVisible
        }
      };
      onRowConfigChange(newConfigs);
    } catch (error) {
      console.error('Error toggling row visibility:', error);
    }
  }, [rowConfigs, onRowConfigChange]);

  // 拖拽排序处理
  const handleDragStart = useCallback((index: number) => {
    if (!enableRowDragging) return;
    setDraggedIndex(index);
  }, [enableRowDragging]);

  const handleDragEnd = useCallback(() => {
    setDraggedIndex(null);
    setDragOverIndex(null);
  }, []);

  const handleDragEnter = useCallback((index: number) => {
    setDragOverIndex(index);
  }, []);

  const handleDragLeave = useCallback(() => {
    setDragOverIndex(null);
  }, []);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
  }, []);

  const handleDrop = useCallback((e: React.DragEvent, dropIndex: number) => {
    e.preventDefault();
    
    if (draggedIndex === null || draggedIndex === dropIndex || !enableRowDragging) {
      return;
    }

    try {
      // 重新排序可见行
      const newVisibleRows = [...displayRows];
      const [draggedRow] = newVisibleRows.splice(draggedIndex, 1);
      newVisibleRows.splice(dropIndex, 0, draggedRow);

      // 更新配置中的显示顺序
      const newConfigs = { ...rowConfigs };
      newVisibleRows.forEach((row, index) => {
        if (newConfigs[row.id]) {
          newConfigs[row.id] = { ...newConfigs[row.id], displayOrder: index };
        }
      });

      onRowConfigChange(newConfigs);
      
      if (onRowOrderChange) {
        const newOrder = newVisibleRows.map(row => row.id);
        onRowOrderChange(newOrder);
      }
    } catch (error) {
      console.error('Error reordering rows:', error);
    }
  }, [draggedIndex, displayRows, rowConfigs, onRowConfigChange, onRowOrderChange, enableRowDragging]);

  // 添加自定义行处理
  const handleAddCustomRow = useCallback((rowType: 'separator') => {
    if (onAddCustomRow) {
      onAddCustomRow(rowType);
    }
  }, [onAddCustomRow]);

  // 删除自定义行处理
  const handleDeleteCustomRow = useCallback((rowId: string) => {
    if (onDeleteCustomRow) {
      onDeleteCustomRow(rowId);
    }
  }, [onDeleteCustomRow]);

  // 性能统计
  const stats = useMemo(() => {
    const total = data.length;
    const visible = visibleRows.length;
    const hidden = total - visible;
    return { total, visible, hidden };
  }, [data.length, visibleRows.length]);

  return (
    <div className={cn("w-full space-y-2", className)}>
      {/* 表格控制栏 */}
      <div className="flex items-center justify-between text-sm text-muted-foreground">
        <div className="flex items-center gap-4">
          <span>
            显示 {stats.visible} / {stats.total} 行
            {stats.hidden > 0 && (
              <span className="text-orange-600 ml-1">
                ({stats.hidden} 行已隐藏)
              </span>
            )}
          </span>
          {enableVirtualization && displayRows.length < visibleRows.length && (
            <span className="text-blue-600">
              虚拟化显示前 {displayRows.length} 行
            </span>
          )}
        </div>
        <div className="flex items-center gap-2">
          {onAddCustomRow && (
            <AddRowMenu
              onAddRow={handleAddCustomRow}
              disabled={isConfigPreviewMode}
            />
          )}
          {isConfigPreviewMode && (
            <span className="text-blue-600 text-xs">配置预览模式</span>
          )}
          <button
            onClick={toggleConfigPreview}
            className={cn(
              "px-2 py-1 text-xs rounded transition-colors",
              isConfigPreviewMode 
                ? "bg-blue-100 text-blue-700 hover:bg-blue-200" 
                : "bg-gray-100 text-gray-600 hover:bg-gray-200"
            )}
          >
            {isConfigPreviewMode ? "退出预览" : "配置预览"}
          </button>
        </div>
      </div>

      {/* 表格 */}
      <div className="w-full overflow-x-auto">
        {displayRows.length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            <div className="text-sm">暂无可显示的数据行</div>
            <div className="text-xs mt-1">请检查行配置设置</div>
          </div>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-56">
                  <div className="flex items-center justify-between">
                    <span>指标</span>
                    <div className="flex items-center gap-1">
                      {enableRowDragging && (
                        <span className="text-xs text-gray-400" title="支持拖拽排序">
                          <svg className="h-3 w-3" fill="currentColor" viewBox="0 0 20 20">
                            <path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
                          </svg>
                        </span>
                      )}
                      <RowSettingsButton onClick={onOpenSettings} />
                    </div>
                  </div>
                </TableHead>
                {columns.map((column) => (
                  <TableHead key={column} className="text-right">
                    {column}
                  </TableHead>
                ))}
              </TableRow>
            </TableHeader>
            <TableBody>
              {displayRows.map((row, index) => {
                try {
                  const isSelected = selectedRowId === row.id;
                  const isVisible = rowConfigs[row.id]?.isVisible !== false;
                  const canHide = Object.values(rowConfigs).filter(config => config.isVisible).length > 1;
                  
                  return (
                    <React.Fragment key={row.id}>
                      {isConfigPreviewMode ? (
                        // 配置预览模式：显示快速切换按钮
                        <TableRow
                          isVisible={isVisible}
                          animationDuration={enableAnimations ? animationDuration : 0}
                          className={cn(
                            "transition-all duration-200",
                            isSelected && "bg-indigo-50 border-indigo-200",
                            !isVisible && "opacity-50 bg-gray-50"
                          )}
                        >
                          <TableCell className="font-medium">
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-2">
                                <span>{row.displayText}</span>
                                {(row.group === "income" || 
                                  row.group === "balancesheet" || 
                                  row.group === "cashflow" || 
                                  row.tushareParam === "total_mv") && (
                                  <span className="text-xs text-muted-foreground">（亿元）</span>
                                )}
                              </div>
                              <button
                                onClick={(e) => quickToggleRow(row.id, e)}
                                disabled={isVisible && !canHide}
                                className={cn(
                                  "px-2 py-1 text-xs rounded transition-colors",
                                  isVisible && canHide && "bg-green-100 text-green-700 hover:bg-green-200",
                                  !isVisible && "bg-red-100 text-red-700 hover:bg-red-200",
                                  isVisible && !canHide && "bg-gray-100 text-gray-400 cursor-not-allowed"
                                )}
                                title={isVisible && !canHide ? "至少需要保留一行可见" : undefined}
                              >
                                {isVisible ? "隐藏" : "显示"}
                              </button>
                            </div>
                          </TableCell>
                          {columns.map((column) => (
                            <TableCell key={column} className="text-right">
                              {row.values[column] ?? "-"}
                            </TableCell>
                          ))}
                        </TableRow>
                      ) : (
                        // 正常模式：可拖拽排序的行
                        <DraggableRow
                          rowData={row}
                          columns={columns}
                          index={index}
                          isVisible={isVisible}
                          isSelected={isSelected}
                          isDraggable={enableRowDragging}
                          isDragging={draggedIndex === index}
                          isDragOver={dragOverIndex === index}
                          animationDuration={enableAnimations ? animationDuration : 0}
                          onClick={() => handleRowClick(row.id)}
                          onDragStart={handleDragStart}
                          onDragEnd={handleDragEnd}
                          onDragEnter={handleDragEnter}
                          onDragLeave={handleDragLeave}
                          onDragOver={handleDragOver}
                          onDrop={(e) => handleDrop(e, index)}
                          onDeleteCustomRow={handleDeleteCustomRow}
                        />
                      )}
                    </React.Fragment>
                  );
                } catch (error) {
                  console.error('Error rendering table row:', error);
                  return (
                    <TableRow key={`error-${row.id}`}>
                      <TableCell colSpan={columns.length + 1} className="text-center text-red-500 text-sm">
                        渲染行数据时出错: {row.displayText}
                      </TableCell>
                    </TableRow>
                  );
                }
              })}
            </TableBody>
          </Table>
        )}
      </div>

      {/* 性能提示 */}
      {data.length > 100 && (
        <div className="text-xs text-muted-foreground text-center py-2">
          <span>
            大量数据已优化渲染性能
            {enableVirtualization && ` (虚拟化已启用)`}
          </span>
        </div>
      )}
    </div>
  );
}

// Types are already exported with their interface declarations