import { SpainTaxCatalogProvider } from '@erp/core';
import { MultiSelect } from "@repo/rdx-ui/components";
import { cn } from "@repo/shadcn-ui/lib/utils";
import { useCallback, useMemo } from 'react';
import { useTranslation } from "../i18n";


interface CustomerInvoiceTaxesMultiSelect {
  value?: string[];
  onChange: (selectedValues: string[]) => void;
  className?: string;
  inputId?: string;
  [key: string]: any; // Allow other props to be passed
}

export const CustomerInvoiceTaxesMultiSelect = (props: CustomerInvoiceTaxesMultiSelect) => {
  const { value, onChange, className, inputId, ...otherProps } = props;
  const { t } = useTranslation();

  const taxCatalog = useMemo(() => SpainTaxCatalogProvider(), []);
  const catalogLookup = useMemo(() => SpainTaxCatalogProvider().toOptionLookup(), []);

  /**
   * Filtra para mantener solo un elemento por grupo.
   * Si hay duplicados dentro del mismo grupo, se queda con el último.
   */
  const filterSelectedByGroup = useCallback((selectedValues: string[]) => {
    const groupMap = new Map<string | undefined, string>();

    selectedValues.forEach((code) => {
      const item = taxCatalog.findByCode(code).getOrUndefined();
      const group = item?.group ?? "ungrouped";
      groupMap.set(group, code); // Sobrescribe el anterior del mismo grupo
    });

    return Array.from(groupMap.values());
  }, [taxCatalog]);

  return (
    <div className={cn("w-full", "max-w-md")}>
      <MultiSelect
        id={inputId}
        options={catalogLookup}
        onValueChange={onChange}
        defaultValue={value}
        placeholder={t("components.customer_invoice_taxes_multi_select.placeholder")}
        variant='secondary'
        animation={0}
        maxCount={3}
        autoFilter={true}
        filterSelected={filterSelectedByGroup}
        className={cn(
          "flex w-full -mt-0.5 px-1 py-0.5 rounded-md border min-h-8 h-auto items-center justify-between bg-background hover:bg-inherit [&_svg]:pointer-events-auto",
          "hover:border-ring hover:ring-ring/50 hover:ring-[2px]",
          className
        )}

        {...otherProps}
      />
    </div>
  );
};
