import type { Key, ReactElement, ReactNode } from 'react';

import type { DataGridProps } from './DataGrid';

export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

export type Maybe<T> = T | undefined | null;

export type StateSetter<S> = React.Dispatch<React.SetStateAction<S>>;

export interface Column<TRow, TSummaryRow = unknown> {
  /** The name of the column. Displayed in the header cell by default */
  readonly name: string | ReactElement;
  /** A unique key to distinguish each column */
  readonly key: string;
  /**
   * Column width. If not specified, it will be determined automatically based on grid width and specified widths of other columns
   * @default 'auto'
   */
  readonly width?: Maybe<number | string>;
  /**
   * Minimum column width in pixels
   * @default 50
   */
  readonly minWidth?: Maybe<number>;
  /** Maximum column width in pixels */
  readonly maxWidth?: Maybe<number>;
  /** Class name(s) for cells */
  readonly cellClass?: Maybe<string | ((row: TRow) => Maybe<string>)>;
  /** Class name(s) for the header cell */
  readonly headerCellClass?: Maybe<string>;
  /** Class name(s) for summary cells */
  readonly summaryCellClass?: Maybe<string | ((row: TSummaryRow) => Maybe<string>)>;
  /** Render function to render the content of cells */
  readonly renderCell?: Maybe<(props: RenderCellContentProps<TRow, TSummaryRow>) => ReactNode>;
  /** Render function to render the content of the header cell */
  readonly renderHeaderCell?: Maybe<
    (props: RenderHeaderCellContentProps<TRow, TSummaryRow>) => ReactNode
  >;
  /** Render function to render the content of summary cells */
  readonly renderSummaryCell?: Maybe<
    (props: RenderSummaryCellContentProps<TSummaryRow, TRow>) => ReactNode
  >;
  /** Render function to render the content of group cells */
  readonly renderGroupCell?: Maybe<
    (props: RenderGroupCellContentProps<TRow, TSummaryRow>) => ReactNode
  >;
  /** Render function to render the content of edit cells. When set, the column is automatically set to be editable */
  readonly renderEditCell?: Maybe<
    (props: RenderEditCellContentProps<TRow, TSummaryRow>) => ReactNode
  >;
  /** Control whether cells can be edited with `renderEditCell` */
  readonly editable?: Maybe<boolean | ((row: TRow) => boolean)>;
  /**
   * Returns the number of columns that the cell spans, or `undefined` for no spanning.
   * The span is clamped to the start-frozen, unfrozen, or end-frozen columns, whichever the column is part of.
   */
  readonly colSpan?: Maybe<(args: ColSpanArgs<TRow, TSummaryRow>) => Maybe<number>>;
  /** Determines whether the column is frozen, and on which edge.
   *  `true` is an alias for `'start'` for backward compatibility. */
  readonly frozen?: Maybe<ColumnFrozen | true>;
  /** Enable resizing of the column */
  readonly resizable?: Maybe<boolean>;
  /** Enable sorting of the column */
  readonly sortable?: Maybe<boolean>;
  /** Enable dragging of the column */
  readonly draggable?: Maybe<boolean>;
  /** Sets the column sort order to be descending instead of ascending the first time the column is sorted */
  readonly sortDescendingFirst?: Maybe<boolean>;
  /** Options for cell editing */
  readonly editorOptions?: Maybe<{
    /**
     * Render the cell content in addition to the edit cell content.
     * Enable this option when the editor is rendered outside the grid, like a modal for example.
     * By default, the cell content is not rendered when the edit cell is open.
     * @default false
     */
    readonly displayCellContent?: Maybe<boolean>;
    /**
     * Commit changes when clicking outside the cell
     * @default true
     */
    readonly commitOnOutsideClick?: Maybe<boolean>;
    /**
     * Close the editor when the row value changes externally
     * @default true
     */
    readonly closeOnExternalRowChange?: Maybe<boolean>;
  }>;
}

export interface CalculatedColumn<TRow, TSummaryRow = unknown> extends Column<TRow, TSummaryRow> {
  /** The column group that contains the column, or `undefined` if the column is not in a group */
  readonly parent: CalculatedColumnParent<TRow, TSummaryRow> | undefined;
  /** The index of the column in the grid. Column groups are flattened and frozen columns are moved to their edge, so it can differ from the column's index in `columns` */
  readonly idx: number;
  /** Header row level, counted from the bottom header row: always `0` for columns, and negative for column groups */
  readonly level: number;
  readonly width: number | string;
  readonly minWidth: number;
  readonly maxWidth: number | undefined;
  readonly resizable: boolean;
  readonly sortable: boolean;
  readonly draggable: boolean;
  readonly frozen: ColumnFrozen;
  readonly renderCell: (props: RenderCellContentProps<TRow, TSummaryRow>) => ReactNode;
  readonly renderHeaderCell: (props: RenderHeaderCellContentProps<TRow, TSummaryRow>) => ReactNode;
  /** Returns the number of columns that the cell spans: the clamped value returned by `colSpan`, or `1` */
  readonly getColSpan: (args: ColSpanArgs<TRow, TSummaryRow> | undefined) => number;
  // Always set, `undefined` when not set on the column
  readonly cellClass: Column<TRow, TSummaryRow>['cellClass'];
  readonly headerCellClass: Column<TRow, TSummaryRow>['headerCellClass'];
  readonly summaryCellClass: Column<TRow, TSummaryRow>['summaryCellClass'];
  readonly renderSummaryCell: Column<TRow, TSummaryRow>['renderSummaryCell'];
  readonly renderGroupCell: Column<TRow, TSummaryRow>['renderGroupCell'];
  readonly renderEditCell: Column<TRow, TSummaryRow>['renderEditCell'];
  readonly editable: Column<TRow, TSummaryRow>['editable'];
  readonly colSpan: Column<TRow, TSummaryRow>['colSpan'];
  readonly sortDescendingFirst: Column<TRow, TSummaryRow>['sortDescendingFirst'];
  readonly editorOptions: Column<TRow, TSummaryRow>['editorOptions'];
}

export interface ColumnGroup<R, SR = unknown> {
  /** The name of the column group. It will be displayed in the header cell */
  readonly name: string | ReactElement;
  readonly headerCellClass?: Maybe<string>;
  readonly children: readonly ColumnOrColumnGroup<R, SR>[];
}

export interface CalculatedColumnParent<R, SR> {
  readonly name: string | ReactElement;
  readonly parent: CalculatedColumnParent<R, SR> | undefined;
  readonly idx: number;
  readonly colSpan: number;
  readonly level: number;
  readonly headerCellClass?: Maybe<string>;
}

export type ColumnOrColumnGroup<R, SR = unknown> = Column<R, SR> | ColumnGroup<R, SR>;

export type CalculatedColumnOrColumnGroup<R, SR> =
  | CalculatedColumnParent<R, SR>
  | CalculatedColumn<R, SR>;

export interface Position {
  /** Column index, or `-1` for the whole row in `TreeDataGrid` */
  readonly idx: number;
  /** Row index: `0` is the first row, header rows and top summary rows have negative indexes, and bottom summary rows come after the last row */
  readonly rowIdx: number;
}

export interface RenderCellContentProps<TRow, TSummaryRow = unknown> {
  column: CalculatedColumn<TRow, TSummaryRow>;
  row: TRow;
  rowIdx: number;
  isCellEditable: boolean;
  tabIndex: number;
  onRowChange: (row: TRow) => void;
}

export interface RenderSummaryCellContentProps<TSummaryRow, TRow = unknown> {
  column: CalculatedColumn<TRow, TSummaryRow>;
  row: TSummaryRow;
  tabIndex: number;
}

export interface RenderGroupCellContentProps<TRow, TSummaryRow = unknown> {
  column: CalculatedColumn<TRow, TSummaryRow>;
  /** The group row: its key, rows, expanded state, level, and ID */
  row: GroupRow<TRow>;
  tabIndex: number;
  /** Expands or collapses the group */
  toggleGroup: () => void;
}

export interface RenderEditCellContentProps<TRow, TSummaryRow = unknown> {
  column: CalculatedColumn<TRow, TSummaryRow>;
  row: TRow;
  rowIdx: number;
  onRowChange: (row: TRow, commitChanges?: boolean) => void;
  onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void;
}

export interface RenderHeaderCellContentProps<TRow, TSummaryRow = unknown> {
  column: CalculatedColumn<TRow, TSummaryRow>;
  sortDirection: SortDirection | undefined;
  priority: number | undefined;
  tabIndex: number;
}

interface BaseRenderCellProps<TRow, TSummaryRow = unknown>
  extends
    Omit<React.ComponentProps<'div'>, 'children'>,
    Pick<
      DataGridProps<TRow, TSummaryRow>,
      'onCellMouseDown' | 'onCellClick' | 'onCellDoubleClick' | 'onCellContextMenu'
    > {
  rowIdx: number;
  setActivePosition: (position: Position, options?: SetActivePositionOptions) => void;
}

export interface RenderCellProps<TRow, TSummaryRow> extends BaseRenderCellProps<TRow, TSummaryRow> {
  column: CalculatedColumn<TRow, TSummaryRow>;
  row: TRow;
  colSpan: number;
  isDraggedOver: boolean;
  isCellActive: boolean;
  onRowChange: (column: CalculatedColumn<TRow, TSummaryRow>, rowIdx: number, newRow: TRow) => void;
}

export interface EditCellProps<R, SR> extends Pick<
  RenderCellProps<R, SR>,
  'column' | 'row' | 'rowIdx'
> {
  onRowChange: (row: R, commitChanges: boolean, shouldFocus: boolean) => void;
  closeEditor: (shouldFocus: boolean) => void;
  navigate: (event: React.KeyboardEvent<HTMLDivElement>) => void;
  onKeyDown: Maybe<(args: EditCellKeyDownArgs<R, SR>, event: CellKeyboardEvent) => void>;
}

export type CellEvent<E extends React.SyntheticEvent<HTMLDivElement>> = E & {
  /** Prevents the default grid behavior for this event */
  preventGridDefault: () => void;
  /** Returns whether `preventGridDefault` was called */
  isGridDefaultPrevented: () => boolean;
};

export type CellMouseEvent = CellEvent<React.MouseEvent<HTMLDivElement>>;

export type CellKeyboardEvent = CellEvent<React.KeyboardEvent<HTMLDivElement>>;

export type CellClipboardEvent = React.ClipboardEvent<HTMLDivElement>;

export interface CellMouseArgs<TRow, TSummaryRow = unknown> {
  /** The column object of the cell. */
  column: CalculatedColumn<TRow, TSummaryRow>;
  /** The row object of the cell. */
  row: TRow;
  /** The row index of the cell. */
  rowIdx: number;
  /** Sets the active position to the cell. Pass `{ enableEditor: true }` to open its editor, or `{ shouldFocus: true }` to also focus it. */
  setActivePosition: (options?: SetActivePositionOptions) => void;
}

interface ActiveCellKeyDownArgs<TRow, TSummaryRow = unknown, TActiveRow = TRow> {
  mode: 'ACTIVE';
  /**
   * column object of the active position,
   * undefined if the active position is a row instead of a cell
   */
  column: CalculatedColumn<TRow, TSummaryRow> | undefined;
  /** The active row. In `TreeDataGrid`, it can be a `GroupRow`, see `isGroupRow` */
  row: TActiveRow;
  rowIdx: number;
  setActivePosition: (position: Position, options?: SetActivePositionOptions) => void;
}

interface EditCellKeyDownArgs<TRow, TSummaryRow = unknown> {
  mode: 'EDIT';
  column: CalculatedColumn<TRow, TSummaryRow>;
  row: TRow;
  rowIdx: number;
  navigate: () => void;
  onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void;
}

/**
 * @typeParam TActiveRow - The type of the active row in `ACTIVE` mode, `TRow | GroupRow<TRow>` in `TreeDataGrid`
 */
export type CellKeyDownArgs<TRow, TSummaryRow = unknown, TActiveRow = TRow> =
  | ActiveCellKeyDownArgs<TRow, TSummaryRow, TActiveRow>
  | EditCellKeyDownArgs<TRow, TSummaryRow>;

/**
 * @typeParam TActiveRow - The type of the active row, `TRow | GroupRow<TRow>` in `TreeDataGrid`
 */
export interface PositionChangeArgs<TRow, TSummaryRow = unknown, TActiveRow = TRow> {
  /** row index of the active position */
  rowIdx: number;
  /**
   * row object of the active position,
   * undefined if the active position is on a header or summary row.
   * In `TreeDataGrid`, it can be a `GroupRow`, see `isGroupRow`
   */
  row: TActiveRow | undefined;
  /**
   * column object of the active position,
   * undefined if the active position is a row instead of a cell
   */
  column: CalculatedColumn<TRow, TSummaryRow> | undefined;
}

/** The arguments of `TreeDataGrid`'s `onCellKeyDown`, whose active row can be a `GroupRow` */
export type TreeCellKeyDownArgs<TRow, TSummaryRow = unknown> = CellKeyDownArgs<
  TRow,
  TSummaryRow,
  TRow | GroupRow<TRow>
>;

/** The arguments of `TreeDataGrid`'s `onActivePositionChange`, whose row can be a `GroupRow` */
export type TreePositionChangeArgs<TRow, TSummaryRow = unknown> = PositionChangeArgs<
  TRow,
  TSummaryRow,
  TRow | GroupRow<TRow>
>;

export type CellMouseEventHandler<R, SR> = Maybe<
  (args: CellMouseArgs<NoInfer<R>, NoInfer<SR>>, event: CellMouseEvent) => void
>;

export type MapViewportColumns<TRow, TSummaryRow> = <T>(
  activeIdx: number | undefined,
  colSpanArgs: ColSpanArgs<TRow, TSummaryRow> | undefined,
  callback: (
    column: CalculatedColumn<TRow, TSummaryRow>,
    isCellActive: boolean,
    colSpan: number,
    index: number
  ) => T
) => T[];

export interface BaseRenderRowProps<TRow, TSummaryRow = unknown> extends BaseRenderCellProps<
  TRow,
  TSummaryRow
> {
  /**
   * Calls `callback` for each cell to render in the row, and returns the results.
   * `activeIdx` is the column index of the row's active cell, if any: that cell is rendered even when it is scrolled out of view.
   * If virtualization would leave out the active row, it is rendered with only its active cell, if any.
   * `colSpanArgs` is passed to `column.colSpan`, and the columns that a cell spans are skipped, even the active one.
   * The callback receives the cell's column, whether the cell is active, its `colSpan`, and its index in the results.
   */
  mapViewportColumns: MapViewportColumns<TRow, TSummaryRow>;
  rowIdx: number;
  activeCellIdx: number | undefined;
  isRowSelectionDisabled: boolean;
  isRowSelected: boolean;
  gridRowStart: number;
}

export interface RenderRowProps<TRow, TSummaryRow = unknown> extends BaseRenderRowProps<
  TRow,
  TSummaryRow
> {
  row: TRow;
  draggedOverCellIdx: number | undefined;
  activeCellEditor: ReactElement<EditCellProps<TRow, TSummaryRow>> | undefined;
  onRowChange: (column: CalculatedColumn<TRow, TSummaryRow>, rowIdx: number, newRow: TRow) => void;
  rowClass: Maybe<(row: TRow, rowIdx: number) => Maybe<string>>;
  isTreeGrid: boolean;
}

export interface RowsChangeData<R, SR = unknown> {
  /** Indexes of the rows that changed */
  indexes: number[];
  /** The column of the cells that changed */
  column: CalculatedColumn<R, SR>;
}

export interface SelectRowEvent<TRow> {
  row: TRow;
  checked: boolean;
  isShiftClick: boolean;
}

export interface SelectHeaderRowEvent {
  checked: boolean;
}

export interface FillEvent<TRow> {
  columnKey: string;
  sourceRow: TRow;
  targetRow: TRow;
}

interface CellCopyPasteArgs<TRow, TSummaryRow = unknown> {
  column: CalculatedColumn<TRow, TSummaryRow>;
  row: TRow;
}

export type CellCopyArgs<TRow, TSummaryRow = unknown> = CellCopyPasteArgs<TRow, TSummaryRow>;
export type CellPasteArgs<TRow, TSummaryRow = unknown> = CellCopyPasteArgs<TRow, TSummaryRow>;

export interface GroupRow<TRow> {
  /** The rows of the group, including the rows of its subgroups */
  readonly childRows: readonly TRow[];
  /** The group's ID, returned by `getGroupId` */
  readonly id: string;
  /** The ID of the parent group, or `undefined` on the first level */
  readonly parentId: string | undefined;
  /** The group's key, returned by `getRowGroupKey` */
  readonly groupKey: string;
  /** Whether the group is expanded, i.e., its ID is in `expandedGroupIds` */
  readonly isExpanded: boolean;
  /** The nesting level, `0` for the first level */
  readonly level: number;
  /** The position of the group among its sibling groups, `0` for the first one */
  readonly posInSet: number;
  /** The number of sibling groups, including this one */
  readonly setSize: number;
  /** The index of the group row among all the rows, counting every group as expanded */
  readonly startRowIndex: number;
}

export interface SortColumn {
  readonly columnKey: string;
  readonly direction: SortDirection;
}

export type CellNavigationMode = 'NONE' | 'CHANGE_ROW';
export type ColumnFrozen = false | 'start' | 'end';
export type SortDirection = 'ASC' | 'DESC';

export type ColSpanArgs<TRow, TSummaryRow> =
  | { readonly type: 'HEADER' }
  | { readonly type: 'ROW'; readonly row: TRow }
  | { readonly type: 'SUMMARY'; readonly row: TSummaryRow };

export type RowHeightArgs<TRow> =
  | { type: 'ROW'; row: TRow }
  | { type: 'GROUP'; row: GroupRow<TRow> };

export interface RenderSortIconProps {
  /** The sort direction of the column, or `undefined` if it is not sorted */
  sortDirection: SortDirection | undefined;
}

export interface RenderSortPriorityProps {
  /** The column's position in `sortColumns`, starting at 1, when sorting by multiple columns, or `undefined` otherwise */
  priority: number | undefined;
}

export interface RenderSortStatusProps extends RenderSortIconProps, RenderSortPriorityProps {}

export interface RenderCheckboxProps {
  /** Whether the checkbox is checked */
  checked?: boolean | undefined;
  /** Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected */
  indeterminate?: boolean | undefined;
  /** Whether the checkbox is disabled */
  disabled?: boolean | undefined;
  /** Called when the checkbox is toggled. `shift` is `true` if the Shift key was held, to select a range of rows */
  onChange: (checked: boolean, shift: boolean) => void;
  /** `0` when the checkbox's cell is active and `-1` otherwise, so the grid can move focus from the cell to the checkbox */
  tabIndex?: number | undefined;
  /** Accessible label for the checkbox */
  'aria-label'?: string | undefined;
  /** ID of the element that labels the checkbox */
  'aria-labelledby'?: string | undefined;
}

export interface Renderers<TRow, TSummaryRow> {
  readonly renderCell?: Maybe<(key: Key, props: RenderCellProps<TRow, TSummaryRow>) => ReactNode>;
  readonly renderCheckbox?: Maybe<(props: RenderCheckboxProps) => ReactNode>;
  readonly renderRow?: Maybe<(key: Key, props: RenderRowProps<TRow, TSummaryRow>) => ReactNode>;
  readonly renderSortStatus?: Maybe<(props: RenderSortStatusProps) => ReactNode>;
  readonly noRowsFallback?: Maybe<ReactNode>;
}

export interface SetActivePositionOptions {
  enableEditor?: Maybe<boolean>;
  shouldFocus?: Maybe<boolean>;
}

export interface ColumnWidth {
  /** `'resized'` if the user resized the column, or `'measured'` if the grid measured it */
  readonly type: 'resized' | 'measured';
  /** The width in pixels */
  readonly width: number;
}

export type ColumnWidths = ReadonlyMap<string, ColumnWidth>;

export type Direction = 'ltr' | 'rtl';

export type ResizedWidth = number | 'max-content';
