import { TrashIcon } from '@heroicons/react/24/outline';

import { PlusCircleIcon } from '@heroicons/react/24/solid';
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { __ } from '@wordpress/i18n';
import Button from '../../../../../../components/Button';
import LoadingSpinner from '../../../../../../components/LoadingSpinner';
import {
  addCondition,
  deleteCondition,
  deleteConditionGroup,
  updateConditionGroup,
  updateConditionValues,
} from '../../../../../../features/filters/filtersSlice';
import Condition from './Condition';
import SelectFilterDropdown from './FilterDropdown';
import OperatorRadio from './OperatorRadio';

const Conditions = ({ allFilters, isLoading }) => {
  const { conditions: conditionsGroup } = useSelector((state) => state.filters);
  const dispatch = useDispatch();

  const handleAddCondition = (conditionGroup) => {
    dispatch(addCondition(conditionGroup.id));
  };

  const handleChangeGroupOperator = (operator, conditionGroup) => {
    dispatch(
      updateConditionGroup({
        operator,
        id: conditionGroup.id,
      }),
    );
  };

  const handleOperatorChange = (operator, filter, group) => {
    dispatch(
      updateConditionValues({
        values: { ...filter, operator },
        group_id: group.id,
      }),
    );
  };

  const handleConditionGroupDelete = (conditionsGroup) => {
    dispatch(deleteConditionGroup(conditionsGroup.id));
  };

  const handleConditionDelete = (filter, conditionGroup) => {
    dispatch(
      deleteCondition({
        condition_id: filter.id,
        group_id: conditionGroup.id,
      }),
    );
  };

  useEffect(() => {
    window.scroll({
      top: window.document.body.scrollHeight,
    });
  }, [conditionsGroup.length]);

  if (isLoading || !allFilters) {
    return (
      <div className='wmx-mt-5 wmx-flex wmx-items-center wmx-gap-2'>
        <LoadingSpinner className='wmx-size-6' />
        <p className='wmx-text-base wmx-mt-0.5'>Conditions Loading</p>
      </div>
    );
  }

  return (
    <div>
      {conditionsGroup.map((conditionGroup, index) => {
        return (
          <div
            key={conditionGroup.id}
            className='wmx-relative wmx-p-4 wmx-border wmx-rounded-lg wmx-bg-white first:wmx-mt-5 wmx-mt-12'
          >
            <button
              onClick={() => handleConditionGroupDelete(conditionGroup)}
              className='wmx-absolute -wmx-bottom-2 -wmx-right-1 wmx-text-xs wmx-transition-colors wmx-text-white  wmx-px-1 wmx-py-0.5 wmx-bg-red-500 hover:wmx-bg-red-600 wmx-rounded-sm'
            >
              Delete Group
            </button>
            <div className='wmx-flex wmx-justify-center'>
              {index !== 0 && (
                <div className='wmx-relative -wmx-mt-14'>
                  <OperatorRadio
                    fontSize='wmx-text-[11px]'
                    value={conditionGroup.base_operator}
                    onChange={(operator) => handleChangeGroupOperator(operator, conditionGroup)}
                  />
                </div>
              )}
            </div>
            {conditionGroup.base_filters.map((filter, index) => (
              <div key={filter.id}>
                {index !== 0 && (
                  <div className='wmx-my-2'>
                    <OperatorRadio
                      fontSize='wmx-text-[10px]'
                      value={filter.operator}
                      onChange={(operator) => handleOperatorChange(operator, filter, conditionGroup)}
                    />
                  </div>
                )}

                <div className='wmx-flex wmx-gap-3 wmx-px-0'>
                  <div>
                    <SelectFilterDropdown
                      allFilters={allFilters?.values ?? []}
                      conditionGroup={conditionGroup}
                      condition={filter}
                    />
                  </div>
                  <div className='wmx-w-full wmx-flex wmx-gap-3 wmx-justify-between wmx-items-center'>
                    <Condition
                      condition={filter}
                      conditionGroup={conditionGroup}
                      allFilters={allFilters?.values ?? []}
                    />

                    <button
                      onClick={() => handleConditionDelete(filter, conditionGroup)}
                      className='wmx-flex-shrink-0 wmx-bg-red-100 wmx-p-1.5 wmx-rounded-md wmx-text-red-500 wmx-transition-colors hover:wmx-text-red-600 wmx-border wmx-border-red-100'
                    >
                      <TrashIcon className='wmx-h-5 wmx-w-5 ' />
                    </button>
                  </div>
                </div>
              </div>
            ))}
            <div className='wmx-mt-3'>
              <Button
                testId='add-another-condition'
                onClick={() => handleAddCondition(conditionGroup)}
                type={'transparent'}
                className='!wmx-px-2 !wmx-py-1.5 !wmx-text-sm !wmx-font-regular'
              >
                <PlusCircleIcon className='wmx-h-5 wmx-w-5 wmx-text-white' />
                {__('Add Another Condition', 'wmx')}
              </Button>
            </div>
          </div>
        );
      })}
    </div>
  );
};
export default Conditions;
