import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import dayjs from 'dayjs';
import timezonePlugin from 'dayjs/plugin/timezone';
import utcPlugin from 'dayjs/plugin/utc';
import Image from 'next/image';
import { useRouter } from 'next/router';
import {
  AddRounded,
  ContentCopyRounded,
  FilterAltRounded,
  Inventory2Rounded,
  SearchRounded,
} from '@mui/icons-material';

import { SEARCH_TEXT_MAX_LENGTH, STATUSES_ALL, STATUSES_OPTIONS } from '../constants';

import { getConfigHeaders } from '../helpers';
import * as computedState from '../helpers/computedState';
import * as selectors from '../redux/selectors';
import { archiveAction, getDataAction, getHubOptionsAction, setAction, setTableAction } from '../redux/slices';
import { omitUndefinedProps } from '@/mui/helpers';

import CommonList from '@/modules/@common/List';
import CommonTable, { TableCellActions } from '@/modules/@common/Table';
import Empty from './Empty/Empty';
import {
  Autocomplete,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  IconButton,
  InputAdornment,
  Stack,
  TableCell,
  TableRow,
  TextField,
  Tooltip,
} from '@/mui/components';

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

dayjs.extend(utcPlugin);
dayjs.extend(timezonePlugin);

function List() {
  const router = useRouter();
  const dispatch = useDispatch();
  const [archive, setArchive] = useState(null);

  const data = useSelector(selectors.dataSelector);
  const page = useSelector(selectors.pageSelector);
  const pageSize = useSelector(selectors.pageSizeSelector);
  const totalCount = useSelector(selectors.totalCountSelector);
  const sortBy = useSelector(selectors.sortBySelector);
  const sortOrder = useSelector(selectors.sortOrderSelector);

  const search = useSelector(selectors.searchSelector);
  const status = useSelector(selectors.statusSelector);
  const hub = useSelector(selectors.hubSelector);
  const hubOptions = useSelector(selectors.hubOptionsSelector);

  const shouldShowEmpty = useSelector(computedState.shouldShowEmpty);

  const handleFilter = (filter) => {
    const { sortBy: sortBy$, sortOrder: sortOrder$, page: page$, pageSize: pageSize$, ...mainState } = filter;

    dispatch(
      setTableAction(
        omitUndefinedProps({
          sortBy: sortBy$,
          sortOrder: sortOrder$,
          page: page$,
          pageSize: pageSize$,
        }),
      ),
    );

    dispatch(
      setAction({
        ...mainState,
      }),
    );
    dispatch(getDataAction());
  };

  const handleArchive = () => {
    dispatch(archiveAction(archive));
    setArchive(null);
  };

  useEffect(() => {
    dispatch(getDataAction());
  }, []);

  return (
    <>
      <CommonList
        title="X-Ray Creatives"
        renderFilters={
          <Stack direction="row" alignItems="center" spacing={2}>
            <div>
              <TextField
                className={styles.SearchField}
                size="small"
                placeholder="Search"
                value={search}
                onChange={({ target }) => handleFilter({ search: target.value, page: 1 })}
                inputProps={{
                  autoComplete: 'off',
                  maxLength: SEARCH_TEXT_MAX_LENGTH,
                }}
                InputProps={{
                  endAdornment: (
                    <InputAdornment position="end">
                      <IconButton onClick={() => null}>
                        <SearchRounded />
                      </IconButton>
                    </InputAdornment>
                  ),
                }}
                variant="outlined"
                disabled={shouldShowEmpty}
              />
            </div>
            <Stack spacing={1} direction="row" alignItems="center">
              <Divider orientation="vertical" flexItem />
              <FilterAltRounded color="shades.900" fontSize="medium" />
            </Stack>
            <Autocomplete
              className={styles.StatusSelect}
              value={STATUSES_OPTIONS.find((s) => s.value === status) ?? STATUSES_ALL}
              options={STATUSES_OPTIONS}
              size="small"
              onChange={(e, selected$) => handleFilter({ status: selected$?.value ?? STATUSES_ALL, page: 1 })}
              renderInput={(params) => <TextField {...params} placeholder="Status" />}
            />
            <Autocomplete
              className={styles.HubSelect}
              value={hub}
              options={hubOptions || []}
              optionLabelKey="name"
              optionValueKey="id"
              loading={!hubOptions}
              size="small"
              onOpen={() => dispatch(getHubOptionsAction(''))}
              onChange={(e, selectedHub) => handleFilter({ hub: selectedHub, page: 1 })}
              onInputChange={(e, searchText) => dispatch(getHubOptionsAction(searchText))}
              renderInput={(params) => <TextField {...params} placeholder="Hub" />}
            />
          </Stack>
        }
        renderActions={
          <Tooltip title="Add X-Ray Creative">
            <Button
              size="small"
              variant="contained"
              color="primary"
              startIcon={<AddRounded />}
              onClick={() => router.push('/x-ray/creatives/new')}
            >
              X-Ray Creative
            </Button>
          </Tooltip>
        }
      >
        {shouldShowEmpty ? (
          <Empty />
        ) : (
          <CommonTable
            configHeaders={getConfigHeaders()}
            configRenderRow={(row) => (
              <TableRow
                className={styles.Row}
                key={row.id}
                hover
                role="checkbox"
                onClick={() => router.push(`/x-ray/creatives/${row.id}`)}
              >
                <TableCell>
                  <div className={styles.NoWrap}>{row.id}</div>
                </TableCell>
                <TableCell>
                  <div className={styles.Image}>
                    <Image src={row.image} width={32} height={32} alt="empty-logo" />
                  </div>
                </TableCell>
                <TableCell>
                  <div className={styles.NoWrap}>{row.name}</div>
                </TableCell>
                <TableCell>
                  <div className={styles.NoWrap}>{row.title}</div>
                </TableCell>
                <TableCell>
                  <div className={styles.NoWrap}>{row.publisherName}</div>
                </TableCell>
                <TableCell>
                  <div className={styles.NoWrap}>{row.updatedBy}</div>
                </TableCell>
                <TableCell>
                  <div className={styles.NoWrap}>{dayjs(row.updatedAt).format('MMM D, YYYY hh:mm A')}</div>
                </TableCell>
                <TableCellActions>
                  <Tooltip title="Duplicate" disableInteractive>
                    <IconButton
                      size="small"
                      onClick={(e) => {
                        e.stopPropagation();
                        router.push(`/x-ray/creatives/${row.id}/duplicate`);
                      }}
                    >
                      <ContentCopyRounded />
                    </IconButton>
                  </Tooltip>
                  <Tooltip title="Archive" disableInteractive>
                    {row.status === 1 && (
                      <IconButton
                        size="small"
                        onClick={(e) => {
                          e.stopPropagation();
                          setArchive(row.id);
                        }}
                      >
                        <Inventory2Rounded />
                      </IconButton>
                    )}
                  </Tooltip>
                </TableCellActions>
              </TableRow>
            )}
            data={data || []}
            sortBy={sortBy}
            sortOrder={sortOrder}
            totalCount={totalCount}
            page={page}
            rowsPerPage={pageSize}
            onFilter={handleFilter}
          />
        )}
      </CommonList>
      {archive && (
        <Dialog open={!!archive} onClose={() => setArchive(null)} maxWidth="sm">
          <DialogTitle onClose={() => setArchive(null)}>Archive</DialogTitle>
          <DialogContent>Are you sure you want to archive the X-Ray Creative?</DialogContent>
          <DialogActions>
            <Button variant="outlined" color="primary" onClick={() => setArchive(null)}>
              Cancel
            </Button>
            <Button variant="contained" color="primary" onClick={handleArchive}>
              Archive
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </>
  );
}

export default List;
