import { scrollWidth } from '../../@styles/theme-provider';
import type { DataGridProps } from '../types/DataGridProps';
import type { GridColDef } from '../types/GridColDef';
import type { GridRowDef } from '../types/GridRowDef';
import { GRID_COLUMN_HEADER_HEIGHT, GRID_ROW_HEIGHT } from '../utils';
import { DataGridInner } from './DataGridInner';
import { TreeStructure } from './TreeStructure';

export const calculateDataGridInnerHeight = (innerTableRows: unknown[]) => {
  return GRID_COLUMN_HEADER_HEIGHT + GRID_ROW_HEIGHT * innerTableRows.length;
};

export const getDetailPanelContent: NonNullable<
  DataGridProps['getDetailPanelContent']
> = params => {
  const { detailPanelField, detailPanelProps } = params.columns[0] as GridColDef;
  if (!detailPanelField || !detailPanelProps) {
    console.warn(
      `Cannot render master detail panel without "detailPanelField" and "detailPanelProps" passed to DataGrid.`
    );
    return null;
  }

  const { tableConfig: innerTableConfig, ...dataGridInnerProps } = detailPanelProps;

  const innerTableRows = (params.row[detailPanelField] || []) as GridRowDef[];
  const innerTableData: DataGridProps['tableData'] = {
    page: 1,
    totalPages: 1,
    totalRecords: innerTableRows.length,
    data: innerTableRows
  };

  // add to inner table height the scrollbar width
  const height = calculateDataGridInnerHeight(innerTableRows) + scrollWidth;

  return innerTableRows.length ? (
    <div className="detailPanelContent" style={{ height }}>
      <TreeStructure innerTableRows={innerTableRows} />
      <DataGridInner
        disableColumnHover
        disableStickyHeader
        disableStickyPagination
        initialState={{
          pinnedColumns: {
            left: [innerTableConfig[0].field],
            right: ['actions']
          }
        }}
        {...dataGridInnerProps}
        tableConfig={innerTableConfig}
        tableData={innerTableData}
      />
    </div>
  ) : null;
};
