'use client';

import React from 'react';
import type { ColumnsType, ColumnType, TableProps } from 'antd/es/table';
import { ListingMobileSelectionMenuColumnTitle } from '@/components/listings/ListingMobileSelectionMenuColumnTitle';
import type { ListingMobileSelectionMenuColumnTitleProps } from '@/components/listings/ListingMobileSelectionMenuColumnTitle';
import { parseListingRowSelection } from '@/components/listings/listingRowSelectionTypes';

/** Chaves canónicas da coluna de opções por linha (ModalOpcoes / ⋮). */
const LISTING_MENU_COLUMN_KEYS = ['menu', 'row_actions', 'acoes', 'actions', 'opcoes'] as const;

function isEmptyColumnTitle(title: ColumnType<unknown>['title']): boolean {
    return title === '' || title === undefined || title === null;
}

function findListingMenuColumnIndex<T>(columns: ColumnsType<T>): number {
    for (const key of LISTING_MENU_COLUMN_KEYS) {
        const idx = columns.findIndex((col) => col.key === key);
        if (idx >= 0) {
            return idx;
        }
    }

    return columns.findIndex((col) => {
        if (col.fixed !== 'left') {
            return false;
        }
        if (!isEmptyColumnTitle(col.title as ColumnType<unknown>['title'])) {
            return false;
        }
        const width = col.width;
        return width === undefined || (typeof width === 'number' && width <= 72);
    });
}

/**
 * Injecta o ícone de selecção múltipla no `th` da coluna de menu (listagem padrão Waygest, mobile).
 */
export function patchListingColumnsForMobileSelection<T>(
    columns: ColumnsType<T>,
    mobileMenuHeader: ListingMobileSelectionMenuColumnTitleProps | null,
): ColumnsType<T> {
    if (!mobileMenuHeader) {
        return columns;
    }

    const menuIndex = findListingMenuColumnIndex(columns);
    if (menuIndex < 0) {
        return columns;
    }

    return columns.map((col, index) => {
        if (index !== menuIndex) {
            return col;
        }

        return {
            ...col,
            title: () =>
                React.createElement(ListingMobileSelectionMenuColumnTitle, mobileMenuHeader),
        };
    });
}

/**
 * Prepara colunas + `rowSelection` para `DataTable` / `Table` com toggle mobile na coluna menu.
 */
export function prepareListingTableRowSelectionAndColumns<T>(
    columns: ColumnsType<T>,
    rowSelection: TableProps<T>['rowSelection'],
): {
    columns: ColumnsType<T>;
    rowSelection: TableProps<T>['rowSelection'];
} {
    const { tableRowSelection, mobileMenuHeader } = parseListingRowSelection(rowSelection);
    return {
        columns: patchListingColumnsForMobileSelection(columns, mobileMenuHeader),
        rowSelection: tableRowSelection,
    };
}
