import { CheckedState, useRowSelection } from '@repo/rdx-ui/hooks';
import { Checkbox, Table, TableBody, TableCell, TableFooter, TableHead, TableHeader, TableRow } from "@repo/shadcn-ui/components";
import { useCallback } from 'react';
import { useFormContext } from "react-hook-form";
import { useInvoiceContext } from '../../../context';
import { useInvoiceAutoRecalc, useItemsTableNavigation } from '../../../hooks';
import { useTranslation } from '../../../i18n';
import { InvoiceFormData, InvoiceItemFormData, defaultCustomerInvoiceItemFormData } from '../../../schemas';
import { ItemRow } from './item-row';
import { ItemsEditorToolbar } from './items-editor-toolbar';

interface ItemsEditorProps {
    onChange?: (items: InvoiceItemFormData[]) => void;
    readOnly?: boolean;
}

const createEmptyItem = () => defaultCustomerInvoiceItemFormData;

export const ItemsEditor = ({ readOnly = false }: ItemsEditorProps) => {
    const { t } = useTranslation();
    const context = useInvoiceContext();
    const form = useFormContext<InvoiceFormData>();
    const { control } = form;

    // Navegación y operaciones sobre las filas
    const tableNav = useItemsTableNavigation(form, {
        name: "items",
        createEmpty: createEmptyItem,
        firstEditableField: "description",
    });

    const { fieldArray: { fields } } = tableNav;

    const {
        selectedRows,
        selectedIndexes,
        selectAllState,
        toggleRow,
        setSelectAll,
        clearSelection,
    } = useRowSelection(fields.length);

    useInvoiceAutoRecalc(form, context);

    const handleAddSelection = useCallback(() => {
        if (readOnly) return;
        tableNav.addEmpty(true);
    }, [readOnly, tableNav]);

    const handleDuplicateSelection = useCallback(() => {
        if (readOnly || selectedIndexes.length === 0) return;
        // duplicar en orden ascendente no rompe índices
        selectedIndexes.forEach((i) => tableNav.duplicate(i));
    }, [readOnly, selectedIndexes, tableNav]);

    const handleMoveUpSelection = useCallback(() => {
        if (readOnly || selectedIndexes.length === 0) return;
        // mover de menor a mayor para mantener índices válidos
        selectedIndexes.forEach((i) => tableNav.moveUp(i));
    }, [readOnly, selectedIndexes, tableNav]);

    const handleMoveDownSelection = useCallback(() => {
        if (readOnly || selectedIndexes.length === 0) return;
        // mover de mayor a menor evita desplazar objetivos
        [...selectedIndexes].reverse().forEach((i) => tableNav.moveDown(i));
    }, [readOnly, selectedIndexes, tableNav]);

    const handleRemoveSelection = useCallback(() => {
        if (readOnly || selectedIndexes.length === 0) return;
        // borrar de mayor a menor para no invalidar índices siguientes
        [...selectedIndexes].reverse().forEach((i) => tableNav.remove(i));
        clearSelection();
    }, [readOnly, selectedIndexes, tableNav, clearSelection]);

    return (
        <div className="space-y-0">
            {/* Toolbar selección múltiple */}
            <ItemsEditorToolbar
                readOnly={readOnly}
                selectedIndexes={selectedIndexes}
                onAdd={handleAddSelection}
                onDuplicate={handleDuplicateSelection}
                onMoveUp={handleMoveUpSelection}
                onMoveDown={handleMoveDownSelection}
                onRemove={handleRemoveSelection} />
            <div className="bg-background">
                <Table className="w-full border-collapse text-sm">
                    <TableHeader className="text-sm bg-muted backdrop-blur supports-[backdrop-filter]:bg-muted/60 ">
                        <TableRow>
                            <TableHead className='w-[1%] h-5'>
                                <Checkbox
                                    aria-label={t("common.select_all")}
                                    checked={selectAllState}
                                    disabled={readOnly}
                                    onCheckedChange={(checked: CheckedState) => setSelectAll(checked)}
                                />
                            </TableHead>
                            <TableHead className='w-[1%]' aria-hidden="true">#</TableHead>
                            <TableHead className='w-[40%]'>{t("form_fields.item.description.label")}</TableHead>
                            <TableHead className="w-[4%] text-right">{t("form_fields.item.quantity.label")}</TableHead>
                            <TableHead className="w-[10%] text-right">{t("form_fields.item.unit_amount.label")}</TableHead>
                            <TableHead className="w-[4%] text-right">{t("form_fields.item.discount_percentage.label")}</TableHead>
                            <TableHead className="w-[16%] text-right">{t("form_fields.item.tax_codes.label")}</TableHead>
                            <TableHead className="w-[8%] text-right">{t("form_fields.item.total_amount.label")}</TableHead>
                            <TableHead className='w-[1%]' aria-hidden="true" />
                        </TableRow>
                    </TableHeader>
                    <TableBody className='text-sm'>

                        {fields.map((f, rowIndex: number) => (
                            <ItemRow
                                key={f.id}
                                control={control}
                                rowIndex={rowIndex}
                                isSelected={selectedRows.has(rowIndex)}
                                isFirst={rowIndex === 0}
                                isLast={rowIndex === fields.length - 1}
                                readOnly={readOnly}
                                onToggleSelect={() => toggleRow(rowIndex)}
                                onDuplicate={() => tableNav.duplicate(rowIndex)}
                                onMoveUp={() => tableNav.moveUp(rowIndex)}
                                onMoveDown={() => tableNav.moveDown(rowIndex)}
                                onRemove={() => tableNav.remove(rowIndex)}
                            />
                        ))}

                    </TableBody>
                    <TableFooter>
                        <TableRow>
                            <TableCell colSpan={9} className='p-0 m-0'>
                                <ItemsEditorToolbar
                                    readOnly={readOnly}
                                    selectedIndexes={selectedIndexes}
                                    onAdd={() => tableNav.addEmpty(true)}
                                />
                            </TableCell>
                        </TableRow>
                    </TableFooter>
                </Table>
            </div>

        </div >
    );
}

