import { DataTable, useWithRowSelection } from '@repo/rdx-ui/components';
import { useMemo } from 'react';
import { useFieldArray, useFormContext } from "react-hook-form";
import { useInvoiceContext } from '../../../context';
import { useInvoiceAutoRecalc } from '../../../hooks';
import { useTranslation } from '../../../i18n';
import { InvoiceFormData, defaultCustomerInvoiceItemFormData } from '../../../schemas';
import { debugIdCol } from './debug-id-col';
import { ItemRowEditor } from './item-row-editor';
import { useItemsColumns } from './use-items-columns';


const createEmptyItem = () => defaultCustomerInvoiceItemFormData;

export const ItemsEditor = () => {
    const { t } = useTranslation();
    const context = useInvoiceContext();
    const form = useFormContext<InvoiceFormData>();
    const { control, getValues } = form;

    useInvoiceAutoRecalc(form, context);

    const { fields, append, remove, move, insert, update } = useFieldArray({
        control,
        name: "items",
    });

    const baseColumns = useWithRowSelection(useItemsColumns(), true);
    const columns = useMemo(
        () => [...baseColumns, debugIdCol],
        [baseColumns]
    );

    return (
        <div className="space-y-0">
            <DataTable columns={columns as any} data={fields}
                meta={{
                    tableOps: {
                        onAdd: () => append({ ...createEmptyItem() }),
                        //appendItem: (item: any) => append(item),
                    },
                    rowOps: {
                        remove: (i: number) => remove(i),
                        move: (from: number, to: number) => move(from, to),
                        //insertItem: (index: number, item: any) => insert(index, item),
                        /*duplicateItems: (indexes: number[], table: Table<InvoiceFormData>) => {
                            const items = getValues("items") || [];
                            // duplicate in descending order to keep indexes stable
                            [...indexes].sort((a, b) => b - a).forEach(i => {
                                const curr = items[i] as any;
                                if (curr) {
                                    const { id, ...rest } = curr;
                                    append({ ...rest });
                                }
                            });
                        },*/
                        /*deleteItems: (indexes: number[]) => {
                            // remove in descending order to avoid shifting issues
                            [...indexes].sort((a, b) => b - a).forEach(i => remove(i));
                        },*/
                        //updateItem: (index: number, item: any) => update(index, item),
                    },
                    bulkOps: {
                        duplicateSelected: (indexes, table) => {
                            const originalData = indexes.map((i) => {
                                const { id, ...original } = table.getRowModel().rows[i].original;
                                return original;
                            });

                            insert(indexes[indexes.length - 1] + 1, originalData, { shouldFocus: true });
                            table.resetRowSelection();
                        },
                        removeSelected: (indexes) => indexes.sort((a, b) => b - a).forEach(remove),
                        moveSelectedUp: (indexes) => indexes.forEach((i) => move(i, i - 1)),
                        moveSelectedDown: (indexes) => [...indexes].reverse().forEach((i) => move(i, i + 1)),
                    }
                }}
                enableRowSelection
                enablePagination={false}
                pageSize={999}
                readOnly={false}
                EditorComponent={ItemRowEditor}
            />
        </div >
    );
}

