import { type FC, useState } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';

import { fromPairs } from 'lodash-es';
import { IconSearch } from '@material-hu/icons/tabler';
import Box from '@material-hu/mui/Box';
import Stack from '@material-hu/mui/Stack';

import HuCheckbox from '@material-hu/components/design-system/Checkbox/Checkbox';
import HuFormCheckbox from '@material-hu/components/design-system/Checkbox/Checkbox/form';
import HuInputClassic from '@material-hu/components/design-system/Inputs/Classic';
import FormSwitcher from '@material-hu/components/design-system/Switcher/form';

import { useLokaliseTranslation } from 'src/utils/i18n';

import AdvancedFilterAccordion from 'src/components/AdvancedFilter/Accordion';
import { type AutocompleteField } from 'src/components/AdvancedFilter/types';

type Props = {
  enableFieldName: string;
  fieldName: string;
  optionsList: AutocompleteField[];
  sectionTitle: string;
  sectionDescription?: string;
};

const HourTypesFieldsSelector: FC<Props> = props => {
  const {
    enableFieldName,
    fieldName,
    optionsList,
    sectionDescription = '',
    sectionTitle,
  } = props;
  const { t } = useLokaliseTranslation('time_tracker');
  const { setValue, control } = useFormContext();
  const [searchQuery, setSearchQuery] = useState('');

  const [enabledField, formItems] = useWatch({
    name: [enableFieldName, fieldName],
    control,
  });

  const filteredOptions = optionsList.filter(item =>
    item.label.toLowerCase().includes(searchQuery.toLowerCase()),
  );

  const selectedItems = optionsList.filter(item => formItems?.[item.value]);

  const itemsSelected = () => {
    const totalItems = optionsList.length;
    return {
      all: selectedItems.length === totalItems,
      some: selectedItems.length > 0 && selectedItems.length < totalItems,
    };
  };

  const handleSelectAll = () => {
    const availableOptions = optionsList.map(o => o.value);
    setValue(fieldName, {
      ...formItems,
      ...fromPairs(availableOptions.map(o => [o, !itemsSelected().all])),
    });
  };

  return (
    <AdvancedFilterAccordion
      label={
        <FormSwitcher
          name={enableFieldName}
          switcherProps={{
            sx: { width: 'unset', minWidth: '100%' },
            title: sectionTitle,
            description: sectionDescription,
          }}
        />
      }
      accordionProps={{
        expanded: enabledField,
        sx: {
          backgroundColor: ({ palette }) =>
            palette.new.background.layout.default,
          '&:before': {
            display: 'none',
          },
          '& .MuiAccordionSummary-expandIconWrapper': {
            display: 'none',
          },
        },
      }}
      withDivider={false}
    >
      <Stack sx={{ width: '100%', pt: 1, gap: 2 }}>
        <HuInputClassic
          placeholder={t('general:search')}
          value={searchQuery}
          hasCounter={false}
          onChange={value => setSearchQuery(value)}
          startAdornment={<IconSearch size={20} />}
          sx={{
            backgroundColor: ({ palette }) =>
              palette.new.background.layout.tertiary,
          }}
        />
        <Box
          sx={{
            backgroundColor: ({ palette }) =>
              palette.new.background.layout.tertiary,
            borderRadius: 2,
            p: 2,
            maxHeight: 200,
            overflow: 'auto',
          }}
        >
          <Stack sx={{ gap: 3 }}>
            {optionsList.length > 1 && !searchQuery && (
              <HuCheckbox
                label={t('select_all')}
                onChange={handleSelectAll}
                checked={itemsSelected().all}
                indeterminate={itemsSelected().some}
              />
            )}
            {filteredOptions.map(item => (
              <HuFormCheckbox
                key={item.value}
                name={`${String(fieldName)}.${item.value}`}
                checkBoxProps={{
                  label: item.label,
                }}
              />
            ))}
          </Stack>
        </Box>
      </Stack>
    </AdvancedFilterAccordion>
  );
};

export default HourTypesFieldsSelector;
