import type { TableRowData } from "@/types/online-table";
import { DEFAULT_TABLE_COLUMNS } from "@/lib/online-table";

const pickCellValue = (cell: any) => {
  if (!cell) return undefined;
  if (cell.m != null) return cell.m;
  if (cell.v?.m != null) return cell.v.m;
  if (cell.v?.v != null) return cell.v.v;
  if (cell.v != null && typeof cell.v !== "object") return cell.v;
  if (cell.w != null) return cell.w;
  return undefined;
};

export const extractRowsForPreview = (
  luckysheetData: any,
  columns: Array<{ id: string }>,
): TableRowData[] => {
  const sheet = Array.isArray(luckysheetData) ? luckysheetData[0] : null;
  if (!sheet) {
    return [];
  }

  const columnIds =
    columns.length > 0 ? columns.map((item) => item.id) : Array.from({ length: DEFAULT_TABLE_COLUMNS }, (_, idx) => `col${idx + 1}`);

  const rows: TableRowData[] = [];
  const grid = Array.isArray(sheet.data) ? sheet.data : [];

  grid.forEach((row: any[], rowIndex: number) => {
    if (!Array.isArray(row)) return;
    const rowObj: TableRowData = {};
    let hasValue = false;
    columnIds.forEach((colId, colIndex) => {
      const value = pickCellValue(row[colIndex]);
      if (value !== undefined && value !== null && value !== "") {
        rowObj[colId] = value;
        hasValue = true;
      }
    });
    if (hasValue) {
      rows.push(rowObj);
    }
  });

  if (rows.length === 0 && Array.isArray(sheet.celldata)) {
    const map = new Map<number, TableRowData>();
    sheet.celldata.forEach((cell: { r: number; c: number; v: unknown }) => {
      const value = pickCellValue(cell?.v ?? cell);
      if (value === undefined || value === null || value === "") return;
      const existing = map.get(cell.r) ?? {};
      existing[columnIds[cell.c] ?? `col${cell.c + 1}`] = value;
      map.set(cell.r, existing);
    });
    Array.from(map.entries())
      .sort(([a], [b]) => a - b)
      .forEach(([, row]) => rows.push(row));
  }

  return rows;
};

