import { useEffect, useMemo, useState } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';

import { type Theme } from '@material-hu/mui/index';
import Stack from '@material-hu/mui/Stack/Stack';

import CollapsibleAutocompleteSelector from '@material-hu/components/composed-components/CollapsibleAutocompleteSelector';
import DatePickerWithOptions from '@material-hu/components/composed-components/DatePickerWithOptions';
import Accordion from '@material-hu/components/design-system/Accordion';
import Drawer from '@material-hu/components/design-system/Drawer';

import UserCollapsibleAutocompleteSelector from 'src/pages/dashboard/serviceManagement/general/UserCollapsibleAutocompleteSelector';
import {
  ServiceItemTypes,
  type State,
} from 'src/pages/dashboard/serviceManagement/types';
import {
  getCreationDateFilterDescription,
  getStateName,
} from 'src/pages/dashboard/serviceManagement/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import useInfiniteServiceItems from '../../../hooks/useInfiniteServiceItems';
import useInfiniteUsersAndAgents from '../../../hooks/useInfiniteUsersAndAgents';
import useTaskStates from '../../../hooks/useTaskStates';
import { createStaticOptionsQuery } from '../../../utils';
import { subtasksFilters } from '../../form/form';
import { type SubtasksFormValues } from '../../Subtasks';

type Props = {
  open: boolean;
  onClose: () => void;
  onApply: () => void;
  onReset: () => void;
};

const SubtasksFiltersDrawer = ({ open, onClose, onApply, onReset }: Props) => {
  const { t, i18n } = useLokaliseTranslation(['service_management', 'general']);

  const { control, clearErrors, setValue } =
    useFormContext<SubtasksFormValues>();

  const { data: taskStates = [] } = useTaskStates(ServiceItemTypes.SUBTASK);

  const [
    dateRangeSelected,
    lastSevenDays,
    lastFourteenDays,
    lastThirtyDays,
    createdAtFrom,
    createdAtTo,
  ] = useWatch({
    control,
    name: [
      subtasksFilters.dateOptions.dateRange(),
      subtasksFilters.dateOptions.lastSevenDays(),
      subtasksFilters.dateOptions.lastFourteenDays(),
      subtasksFilters.dateOptions.lastThirtyDays(),
      subtasksFilters.createdAtFrom(),
      subtasksFilters.createdAtTo(),
    ],
  });

  const [expanded, setExpanded] = useState<Record<string, boolean>>({
    [subtasksFilters.parentTaskInitiatorsIn()]: false,
    [subtasksFilters.parentTaskCatalogItemsIn()]: false,
    [subtasksFilters.statesIn()]: false,
  });

  const handleExpand = (field: string, newExpanded: boolean) => {
    setExpanded(prev => ({ ...prev, [field]: newExpanded }));
  };

  const autocompleteLabelProps = useMemo(() => {
    return {
      selectAllLabel: t('select_all'),
      noResultsLabel: t('empty_results'),
      lackingOptionsMessage: t('empty_results'),
      formatAndMore: (count: number) => t('and_n_items_more', { count }),
      virtualized: true,
      maxHeight: 300,
    };
  }, [t]);

  const taskStaticQueryOptions = useMemo(
    () =>
      createStaticOptionsQuery(taskStates, {
        getSearchText: item => t(getStateName(item.name)),
      }),
    [taskStates, t],
  );

  useEffect(() => {
    if (!dateRangeSelected) {
      clearErrors([
        subtasksFilters.createdAtFrom(),
        subtasksFilters.createdAtTo(),
      ]);
      setValue(subtasksFilters.createdAtFrom(), null);
      setValue(subtasksFilters.createdAtTo(), null);
    }
  }, [dateRangeSelected, clearErrors, setValue]);

  return (
    <Drawer
      title={t('filter')}
      open={open}
      onClose={onClose}
      primaryButtonProps={{
        children: t('apply'),
        onClick: onApply,
        fullWidth: true,
      }}
      secondaryButtonProps={{
        children: t('reset'),
        onClick: onReset,
        fullWidth: true,
      }}
    >
      <Stack sx={{ gap: 2 }}>
        <CollapsibleAutocompleteSelector<State>
          fieldName={subtasksFilters.statesIn()}
          sectionTitle={t('statuses')}
          customMapper={item => ({
            value: item.id,
            name: t(getStateName(item.name)),
          })}
          infiniteQuery={taskStaticQueryOptions}
          isExpanded={expanded[subtasksFilters.statesIn()]}
          setExpanded={newExpanded =>
            handleExpand(subtasksFilters.statesIn(), newExpanded)
          }
          {...autocompleteLabelProps}
        />
        <CollapsibleAutocompleteSelector
          sectionTitle={t('associated_services')}
          fieldName={subtasksFilters.parentTaskCatalogItemsIn()}
          infiniteQuery={useInfiniteServiceItems}
          isExpanded={expanded[subtasksFilters.parentTaskCatalogItemsIn()]}
          setExpanded={newExpanded =>
            handleExpand(
              subtasksFilters.parentTaskCatalogItemsIn(),
              newExpanded,
            )
          }
          {...autocompleteLabelProps}
        />
        <UserCollapsibleAutocompleteSelector
          fieldName={subtasksFilters.parentTaskInitiatorsIn()}
          sectionTitle={t('requesters')}
          infiniteQuery={useInfiniteUsersAndAgents}
          isExpanded={expanded[subtasksFilters.parentTaskInitiatorsIn()]}
          setExpanded={newExpanded =>
            handleExpand(subtasksFilters.parentTaskInitiatorsIn(), newExpanded)
          }
          {...autocompleteLabelProps}
        />
        <Accordion
          title={t('creation_date')}
          description={getCreationDateFilterDescription({
            dateRangeValueSelected: Boolean(dateRangeSelected),
            lastSevenDays: Boolean(lastSevenDays),
            lastFourteenDays: Boolean(lastFourteenDays),
            lastThirtyDays: Boolean(lastThirtyDays),
            fromDate: createdAtFrom,
            toDate: createdAtTo,
            language: i18n.language || 'en',
            t,
          })}
          customDetail={
            <DatePickerWithOptions
              showDatePickers
              options={[
                {
                  name: subtasksFilters.dateOptions.lastSevenDays(),
                  label: t('last_n_days', { days: 7 }),
                },
                {
                  name: subtasksFilters.dateOptions.lastFourteenDays(),
                  label: t('last_n_days', { days: 14 }),
                },
                {
                  name: subtasksFilters.dateOptions.lastThirtyDays(),
                  label: t('last_n_days', { days: 30 }),
                },
                {
                  name: subtasksFilters.dateOptions.dateRange(),
                  label: t('choose_date_range'),
                },
              ]}
              startDatePicker={{
                name: subtasksFilters.createdAtFrom(),
                label: t('from'),
                disabled: !dateRangeSelected,
                inputProps: { disableFuture: true },
              }}
              endDatePicker={{
                name: subtasksFilters.createdAtTo(),
                label: t('general:until'),
                disabled: !dateRangeSelected,
                inputProps: { disableFuture: true },
              }}
            />
          }
          elevation={0}
          sx={{
            mb: 2,
            borderRadius: ({ spacing }: Theme) => spacing(1),
            backgroundColor: ({ palette }: Theme) =>
              palette.new.background.elements.grey,
            '&:before': { backgroundColor: 'transparent' },
          }}
          disableGutters
        />
      </Stack>
    </Drawer>
  );
};

export default SubtasksFiltersDrawer;
