import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import { Facebook, YouTube } from '@mui/icons-material';

import { PLATFORM_FACEBOOK, PLATFORM_YOUTUBE } from '../../constants';
import { SORT_ASC, SORT_DESC } from '@/modules/@common/constants/sort';

import { DestinationType } from '../../types';

import * as selectors from '../../redux/selectors';
import { clearFilterParamsAction, getDestinationsAction, setDestinationsAction } from '../../redux/slices';
import { capitalizeFirstLetter } from '@/modules/publishing/DestinationList/helpers';

import Header from './Header';
import { Table, TableBody, TableCell, TableContainer, TablePagination, TableRow, TableScroll } from '@/mui/components';

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

const platformIconStyle = {
  [PLATFORM_YOUTUBE]: {
    color: 'platform.youtube',
    icon: YouTube,
  },
  [PLATFORM_FACEBOOK]: {
    color: 'platform.facebook',
    icon: Facebook,
  },
};

function DestinationList() {
  const router = useRouter();
  const dispatch = useDispatch();

  const destinations = useSelector(selectors.destinationsSelector);
  const totalDestinations = useSelector(selectors.totalDestinationsSelector);
  const search = useSelector(selectors.searchSelector);
  const page = useSelector(selectors.pageSelector);
  const pageSize = useSelector(selectors.pageSizeSelector);
  const status = useSelector(selectors.statusSelector);
  const sortBy = useSelector(selectors.sortBySelector);
  const sortOrder = useSelector(selectors.sortOrderSelector);
  const platform = useSelector(selectors.platformSelector);
  const publisherId = useSelector(selectors.publisherIdSelector);

  const query = {
    search,
    page,
    pageSize,
    status,
    sortBy,
    sortOrder,
    platform,
    publisherId,
  };
  const handleGetDestination = (params = {}) => dispatch(getDestinationsAction({ ...query, ...params }));

  useEffect(() => {
    handleGetDestination({ page: 1 });

    return () => {
      dispatch(setDestinationsAction([]));
      dispatch(clearFilterParamsAction());
    };
  }, []);

  const handleRequestSort = (event: React.MouseEvent<HTMLButtonElement>, property: string) => {
    const isAsc = query.sortBy === property && query.sortOrder === 'ASC';
    handleGetDestination({
      page: 1,
      sortBy: property,
      sortOrder: isAsc ? 'DESC' : 'ASC',
    });
  };

  const handleChangePage = (event: React.MouseEvent<HTMLButtonElement, MouseEvent> | null, newPage: number) => {
    handleGetDestination({
      page: newPage,
    });
  };

  const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    handleGetDestination({
      page: 1,
      pageSize: +event.target.value,
    });
  };

  return (
    <div data-id="publishingList" className={styles.Wrapper}>
      <TableContainer>
        <TableScroll>
          <Table className={styles.Table} aria-labelledby="tableTitle" aria-label="enhanced table">
            <Header
              sortBy={query.sortBy}
              sortOrder={query.sortOrder as typeof SORT_ASC | typeof SORT_DESC}
              onRequestSort={handleRequestSort}
            />
            <TableBody>
              {destinations.map((row: DestinationType, index) => {
                const labelId = `enhanced-table-checkbox-${index}`;
                const Icon = platformIconStyle[row.type].icon;
                return (
                  <TableRow
                    hover
                    onClick={() => router.push(`/publishing/${row.type.toLowerCase()}/${row.id}`)}
                    className={styles.Row}
                    role="checkbox"
                    tabIndex={-1}
                    key={row.id}
                  >
                    <TableCell
                      component="th"
                      id={labelId}
                      scope="row"
                      data-id="cell-id"
                      classes={{
                        root: styles.Cell,
                      }}
                    >
                      {row.id}
                    </TableCell>
                    <TableCell
                      align="center"
                      data-id="cell-platform"
                      classes={{
                        root: styles.Cell,
                      }}
                    >
                      <Icon htmlColor={platformIconStyle[row.type].color} fontSize="x3Large" className={styles.Icon} />
                    </TableCell>
                    <TableCell
                      data-id="cell-name"
                      classes={{
                        root: styles.Cell,
                      }}
                    >
                      {row.name}
                    </TableCell>
                    <TableCell
                      data-id="cell-publisher"
                      classes={{
                        root: styles.Cell,
                      }}
                    >
                      {row.publisher?.name}
                    </TableCell>
                    <TableCell
                      data-id="cell-status"
                      classes={{
                        root: styles.Cell,
                      }}
                    >
                      {row.status ? capitalizeFirstLetter(row.status) : row.status}
                    </TableCell>
                    <TableCell
                      data-id="cell-visibility"
                      classes={{
                        root: styles.Cell,
                      }}
                    >
                      {row.visibility ? capitalizeFirstLetter(row.visibility) : row.visibility}
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </TableScroll>
        {!!destinations.length && (
          <TablePagination
            rowsPerPageOptions={[10, 15, 25]}
            count={totalDestinations}
            rowsPerPage={query.pageSize}
            page={query.page}
            onPageChange={handleChangePage}
            onRowsPerPageChange={handleChangeRowsPerPage}
            component="div"
          />
        )}
      </TableContainer>
    </div>
  );
}

export default DestinationList;
