import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import NextLink from 'next/link';
import { AddRounded, DeleteRounded, FilterAltRounded } from '@mui/icons-material';

import { PCN_DELETE_LIVE_EVENTS, PCN_POST_LIVE_EVENTS } from '@/modules/@common/acl/constants';

import {
  liveEventsSelector,
  playersSelector,
  publishersSelector,
  queryParamsSelector,
  selectedEventsSelector,
} from '../../redux/selectors';
import {
  archiveLiveEventsAction,
  getLiveEventsAction,
  getPlayersAction,
  getPublishersAction,
} from '../../redux/slices';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';

import FilterSuggester from './FilterSuggester';
import Search from './Search';
import {
  Autocomplete,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  Stack,
  TextField,
  Typography,
} from '@/mui/components';

import styles from './styles.module.scss';

function LiveEventsHeader() {
  const dispatch = useDispatch();
  const selectedEvents = useSelector(selectedEventsSelector);
  const liveEvents = useSelector(liveEventsSelector);
  const players = useSelector(playersSelector);
  const publishers = useSelector(publishersSelector);
  const queryParams = useSelector(queryParamsSelector);
  const userPermissions = useSelector(getUserPermissionsSelector);
  const [isDialogOpen, setDialogOpen] = useState(false);

  const handleFilterChange = (filterType, filterValue) => {
    dispatch(
      getLiveEventsAction({
        ...queryParams,
        [filterType]: filterValue,
        page: 1,
      }),
    );
  };

  const handleArchiveClick = () => {
    setDialogOpen(true);
  };

  const handleDialogClose = () => {
    setDialogOpen(false);
  };

  const handleArchiveEventClick = () => {
    setDialogOpen(false);
    dispatch(
      archiveLiveEventsAction(
        selectedEvents.filter((id) => liveEvents.find((event) => event.id === id)?.status !== -1),
      ),
    );
  };

  const filters = [
    {
      type: 'eventFilter',
      placeholder: 'Period',
      options: [
        {
          label: 'Past',
          value: 'PAST',
        },
        {
          label: 'Current',
          value: 'CURRENT',
        },
        {
          label: 'Future',
          value: 'FUTURE',
        },
      ],
      value: queryParams.eventFilter,
      visibility: true,
    },
    {
      type: 'status',
      placeholder: 'Status',
      options: [
        {
          label: 'Active',
          value: 'active',
        },
        {
          label: 'Archived',
          value: 'archived',
        },
      ],
      disableClearable: true,
      value: queryParams.status,
      visibility: true,
    },
  ];

  const suggesters = [
    {
      type: 'publisherId',
      label: 'Hub',
      options: publishers,
      onSearch: (params) => dispatch(getPublishersAction(params)),
      value: queryParams.publisherId,
    },
    {
      type: 'playerId',
      label: 'Player',
      options: players,
      onSearch: (params) => dispatch(getPlayersAction(params)),
      value: queryParams.playerId,
    },
  ];

  return (
    <>
      <Stack className={styles.WrapperTitle} direction="row" alignItems="center">
        <Typography variant="h6" component="div" align="left">
          Live Events
        </Typography>
      </Stack>
      <Stack spacing={2} fullWidth alignItems="center" direction="row" className={styles.Filter}>
        <div>
          <Search />
        </div>
        <Stack spacing={1} direction="row" alignItems="center">
          <Divider orientation="vertical" flexItem />
          <FilterAltRounded color="shades.900" fontSize="medium" />
        </Stack>
        {filters
          .filter((f) => f.visibility)
          .map((filter) => (
            <Autocomplete
              key={filter.type}
              className={styles.StatusSelect}
              value={filter.options.find((s) => s.value === filter.value) ?? null}
              options={filter.options}
              disableClearable={filter.disableClearable}
              size="small"
              onChange={(e, selected$) => handleFilterChange(filter.type, selected$?.value ?? null)}
              renderInput={(params) => <TextField {...params} placeholder={filter.placeholder} />}
            />
          ))}
        {suggesters.map((filter) => (
          <div key={filter.type}>
            <FilterSuggester onChange={handleFilterChange} {...filter} />
          </div>
        ))}
        <Stack spacing={2} direction="row" alignItems="center" className={styles.AddButtonWrapper}>
          {hasPermission(PCN_DELETE_LIVE_EVENTS, userPermissions) &&
            selectedEvents.some((id) => liveEvents.find((event) => event.id === id)?.status !== -1) && (
              <Button
                onClick={handleArchiveClick}
                variant="outlined"
                color="error"
                size="small"
                title="Archive Selected Events"
                square
                startIcon={<DeleteRounded />}
              />
            )}

          {hasPermission(PCN_POST_LIVE_EVENTS, userPermissions) && (
            <Button href="/live/new" component={NextLink} size="small" data-id="add-button" startIcon={<AddRounded />}>
              Event
            </Button>
          )}
        </Stack>
      </Stack>

      {isDialogOpen && (
        <Dialog
          maxWidth="sm"
          open={isDialogOpen}
          onClose={handleDialogClose}
          aria-labelledby="alert-dialog-title"
          aria-describedby="alert-dialog-description"
        >
          <DialogTitle onClose={handleDialogClose}>Archive Event Confirmation</DialogTitle>
          <DialogContent>
            {selectedEvents.length > 1 ? 'Events ' : 'Event '}
            will be archived permanently from library. Are you sure you would like to archive?
          </DialogContent>
          <DialogActions>
            <Button size="small" onClick={handleDialogClose} variant="outlined">
              Cancel
            </Button>
            <Button size="small" onClick={handleArchiveEventClick} autoFocus>
              Archive
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </>
  );
}

export default LiveEventsHeader;
