import React from 'react';
import { Box } from '@wix/design-system';
import { KeyedItem } from '@wix/bex-core';
import { TableColumn } from '../../model';

function isFirstColumnMobileConfig<T>(
  col: TableColumn<KeyedItem<T>>,
): col is TableColumn<KeyedItem<T>> & {
  mobile: { column: 'first'; order?: number };
} {
  return col.mobile?.column === 'first';
}

export function buildMobileColumns<T>(columns: TableColumn<KeyedItem<T>>[]) {
  const hasMobileConfig = columns.some((col) => (col as any).mobile?.column);

  if (!hasMobileConfig) {
    return [
      {
        id: 'tableColumn',
        title: '',
        render: (params: any, index: number) => (
          <Box direction="vertical" gap="SP1">
            {columns[0] && <div>{columns[0].render?.(params, index)}</div>}
            {columns[1] && <div>{columns[1].render?.(params, index)}</div>}
          </Box>
        ),
      },
    ];
  }

  const firstColumns = columns
    .filter(isFirstColumnMobileConfig)
    .sort((a, b) => {
      const orderA = a.mobile?.order ?? Infinity;
      const orderB = b.mobile?.order ?? Infinity;
      return orderA - orderB;
    });

  const secondColumn = columns.find((col) => col.mobile?.column === 'second');

  const result = [];

  if (firstColumns.length > 0) {
    result.push({
      id: 'mobile-first-column',
      title: '',
      render: (params: any, index: number) => (
        <Box direction="vertical" gap="SP1">
          {firstColumns.map((col, colIndex) => (
            <div key={`first-col-${colIndex}`}>
              {col.render?.(params, index)}
            </div>
          ))}
        </Box>
      ),
    } as any);
  }

  if (secondColumn) {
    result.push({
      id: 'mobile-second-column',
      title: '',
      render: (params: any, index: number) =>
        secondColumn.render?.(params, index),
    } as any);
  }

  return result;
}
