import { useEffect, useMemo, useState } from 'react';
import { useParams } from 'react-router-dom';

import { once } from 'lodash-es';
import { useDebounce } from '@material-hu/hooks/useDebounce';
import { useServerPagination } from '@material-hu/hooks/useServerPagination';
import ArrowDownward from '@material-hu/icons/material/ArrowDownward';
import ArrowUpward from '@material-hu/icons/material/ArrowUpward';
import Clear from '@material-hu/icons/material/Clear';
import ExpandMore from '@material-hu/icons/material/ExpandMore';
import Search from '@material-hu/icons/material/Search';
import IconButton from '@material-hu/mui/IconButton';
import Paper from '@material-hu/mui/Paper';
import Stack from '@material-hu/mui/Stack';
import TextField from '@material-hu/mui/TextField';

import { PeopleExperience } from '@material-hu/components/composed-components/peopleExperience';
import Button from '@material-hu/components/design-system/Buttons/Button';

import { logEvent } from 'src/config/amplitude';
import useManagerParticipation from '../hooks/useManagerParticipation';
import { EventName } from 'src/types/amplitude';
import {
  type ParticipationListParams,
  type SegmentFilter,
  SegmentType,
  SortFilter,
} from '../types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { getBaseSegments } from '../constants';

import ParticipationList from './ParticipationList';
import SegmentSelect from './SegmentSelect';

const { ActionsMenu, ActionsMenuItem } = PeopleExperience;

const INITIAL_SORT_FILTER = SortFilter.ASC;

const ParticipationDashboard = () => {
  const urlParams = useParams();
  const { t } = useLokaliseTranslation('people_experience');
  const surveyId = Number(urlParams.id);
  const baseSegments = getBaseSegments(t);

  const [filters, setFilters] = useState({
    sortOrder: INITIAL_SORT_FILTER,
    segment: baseSegments[0],
    searchQuery: '',
  });

  const { sortOrder, segment, searchQuery } = filters;

  const debouncedSearchQuery = useDebounce(filters.searchQuery);

  const { pagination, paginationController } = useServerPagination({
    labelRowsPerPage: t('ROWS_PER_PAGE'),
  });

  const logEventOnce = useMemo(() => once(logEvent), []);

  useEffect(() => {
    logEventOnce(EventName.PARTICIPATION_VIEWED, {
      surveyID: Number(surveyId),
    });
  }, []);

  const initialParams: ParticipationListParams = {
    surveyId,
    depth: 0,
    parentId:
      segment?.type === SegmentType.SEGMENTATION_GROUPS
        ? (segment.id as number)
        : null,
    limit: pagination.limit,
    page: pagination.page + 1,
    dimension: segment?.type,
    order: sortOrder,
    q: searchQuery ? debouncedSearchQuery : searchQuery,
  };

  const { data } = useManagerParticipation(initialParams);

  const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setFilters(prev => ({ ...prev, searchQuery: event.target.value }));
  };

  const handleChangeSegment = (nextValue: SegmentFilter) => {
    setFilters({
      sortOrder: INITIAL_SORT_FILTER,
      segment: nextValue,
      searchQuery: '',
    });
  };

  const handleChangeOrder = (nextValue: SortFilter) => {
    setFilters(prev => ({ ...prev, sortOrder: nextValue }));
  };

  return (
    <Stack sx={{ gap: 'inherit' }}>
      <Stack
        sx={theme => ({
          backgroundColor: theme.palette.new.background.layout.default,
          padding: 2,
        })}
      >
        <SegmentSelect
          value={segment}
          onChange={handleChangeSegment}
        />
      </Stack>
      <Stack sx={{ gap: 1 }}>
        {![SegmentType.BOSSES, SegmentType.DIRECT_BOSS].includes(
          segment.type,
        ) && (
          <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 2 }}>
            <TextField
              fullWidth
              placeholder={t('SEARCH')}
              value={searchQuery}
              onChange={handleSearchChange}
              InputProps={{
                startAdornment: (
                  <Search
                    fontSize="small"
                    sx={theme => ({
                      color: theme.palette.new.icon.neutral.lighter,
                      mr: 1,
                    })}
                  />
                ),
                endAdornment: searchQuery && (
                  <IconButton
                    size="small"
                    onClick={() =>
                      setFilters(prev => ({ ...prev, searchQuery: '' }))
                    }
                    edge="end"
                    disableRipple
                  >
                    <Clear
                      fontSize="small"
                      sx={theme => ({
                        color: theme.palette.new.icon.neutral.lighter,
                      })}
                    />
                  </IconButton>
                ),
              }}
            />
            <ActionsMenu
              renderTrigger={({ ariaProps, handleOpen }) => (
                <Button
                  {...ariaProps}
                  onClick={handleOpen}
                  endIcon={<ExpandMore />}
                  variant="outlined"
                >
                  {t('SORT')}
                </Button>
              )}
              closeOnSelect
            >
              <ActionsMenuItem
                selected={sortOrder === SortFilter.ASC}
                onClick={() => handleChangeOrder(SortFilter.ASC)}
              >
                {t('general:ascending')}
                <ArrowUpward
                  fontSize="small"
                  sx={theme => ({
                    color: theme.palette.new.icon.neutral.lighter,
                    ml: 1,
                  })}
                />
              </ActionsMenuItem>
              <ActionsMenuItem
                selected={sortOrder === SortFilter.DESC}
                onClick={() => handleChangeOrder(SortFilter.DESC)}
              >
                {t('general:descending')}
                <ArrowDownward
                  fontSize="small"
                  sx={theme => ({
                    color: theme.palette.new.icon.neutral.lighter,
                    ml: 1,
                  })}
                />
              </ActionsMenuItem>
            </ActionsMenu>
          </Stack>
        )}
        <Paper
          sx={{
            borderRadius: theme =>
              `0px 0px ${theme.spacing(1)} ${theme.spacing(1)}`,
          }}
        >
          <ParticipationList {...initialParams} />
          {paginationController(data?.count ?? 0)}
        </Paper>
      </Stack>
    </Stack>
  );
};

export default ParticipationDashboard;
