import Button, { ButtonProps } from '@/components/Button';
import { getFilledFormikValuesCount } from '@/lib/formik-helper';
import { cn } from '@/lib/helper';
import { Icon } from '@iconify/react';
import { FormikValues } from 'formik';
import { useMemo } from 'react';

export type ButtonFilterProps = ButtonProps & {
  values: FormikValues;
  onClick: () => void;
  excludeFields?: string[];
  fieldGroups?: string[][];
};

// 'bg-gradient-to-t from-blue-50 to-blue-100 border-blue-500 text-blue-600 hover:from-blue-100 hover:to-blue-200

const ButtonFilter = ({
  values,
  onClick,
  excludeFields = [],
  fieldGroups = [],
  ...props
}: ButtonFilterProps) => {
  const activeCount = useMemo(() => {
    const filteredValues: FormikValues = {};
    Object.keys(values).forEach((key) => {
      if (!excludeFields.includes(key)) {
        filteredValues[key] = values[key];
      }
    });

    let count = getFilledFormikValuesCount(filteredValues);

    fieldGroups.forEach((group) => {
      const groupFields = group.filter(
        (field) => !excludeFields.includes(field)
      );
      const filledGroupFields = groupFields.filter(
        (field) => filteredValues[field]
      );
      if (
        filledGroupFields.length === groupFields.length &&
        groupFields.length > 1
      ) {
        count -= groupFields.length - 1;
      }
    });

    return count;
  }, [values, excludeFields, fieldGroups]);
  return (
    <Button
      {...props}
      onClick={onClick}
      variant='outline'
      color='none'
      className={cn(
        'rounded-lg max-h-10 font-semibold text-sm gap-1.5',
        'text-sm text-base-content/50 border border-base-content/10 shadow-button-soft',
        activeCount > 0
          ? 'border-primary-gradient text-primary rounded-lg!'
          : 'rounded-lg',
        props.className
      )}
    >
      <Icon
        icon='heroicons:funnel'
        width={20}
        height={20}
        className={activeCount > 0 ? 'text-blue-600' : ''}
      />
      Filter
      {activeCount > 0 && (
        <span className='w-5 h-5 text-white bg-[#FF3535] rounded-lg border border-base-300 flex items-center justify-center text-xs'>
          {activeCount}
        </span>
      )}
    </Button>
  );
};

export default ButtonFilter;
