import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import dayjs from 'dayjs';
import { useRouter } from 'next/router';
import { AddRounded, FilterAltRounded, SearchRounded } from '@mui/icons-material';

import { ACCOUNT_OPTIONS, ACCOUNT_TYPE_ALL, SEARCH_TEXT_MAX_LENGTH, TABLE_HEADERS } from '../constants';

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

import CommonList from '@/modules/@common/List';
import CommonTable from '@/modules/@common/Table';
import {
  Autocomplete,
  Button,
  Divider,
  IconButton,
  InputAdornment,
  Link,
  Stack,
  TableCell,
  TableRow,
  TextField,
  Tooltip,
  UserAvatar,
} from '@/mui/components';

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

const getLabelFromValue = (options, value) => options.find((option) => option.value === value)?.label;

const getAvatarPropsFromRows = ({ avatarUrl, name }) =>
  avatarUrl
    ? { src: avatarUrl }
    : {
        firstName: name.split(' ')[0],
        lastName: name.split(' ').pop(),
      };

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

  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 accountType = useSelector(selectors.accountTypeSelector);

  const shouldShowEmpty = false;

  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());
  };

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

  return (
    <CommonList
      title="Accounts"
      renderFilters={
        <Stack direction="row" alignItems="center" gap={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.Select}
            value={ACCOUNT_OPTIONS.find((s) => s.value === accountType) ?? ACCOUNT_TYPE_ALL}
            options={ACCOUNT_OPTIONS}
            size="small"
            onChange={(e, selected$) => handleFilter({ accountType: selected$?.value ?? ACCOUNT_TYPE_ALL, page: 1 })}
            renderInput={(params) => <TextField {...params} placeholder="Type" />}
          />
        </Stack>
      }
      renderActions={
        <Stack direction="row">
          <Tooltip title="Add Account">
            <Button
              size="small"
              variant="contained"
              color="primary"
              startIcon={<AddRounded />}
              onClick={() => router.push('/accounts/new')}
            >
              Account
            </Button>
          </Tooltip>
        </Stack>
      }
    >
      <CommonTable
        configHeaders={TABLE_HEADERS}
        configRenderRow={(row) => (
          <TableRow className={styles.Row} key={row.id} hover onClick={() => router.push(`/accounts/${row.id}`)}>
            <TableCell>
              <div className={styles.NoWrap}>{row.id}</div>
            </TableCell>
            <TableCell>
              <div className={styles.NoWrap}>
                <Stack direction="row" alignItems="center" gap={2}>
                  <UserAvatar variant="circular" size="small" {...getAvatarPropsFromRows(row)} />
                  {row.name}
                </Stack>
              </div>
            </TableCell>
            <TableCell>
              <div className={styles.NoWrap}>{row.salesforceId}</div>
            </TableCell>
            <TableCell>
              <div className={styles.NoWrap}>{getLabelFromValue(ACCOUNT_OPTIONS, row.type)}</div>
            </TableCell>
            <TableCell>
              <div className={styles.NoWrap}>
                <Link
                  href={`/hubs?accountId=${row.id}`}
                  target="_blank"
                  rel="noreferrer"
                  onClick={(e) => e.stopPropagation()}
                >
                  {row.sitesAmount}
                </Link>
              </div>
            </TableCell>
            <TableCell>
              <div className={styles.NoWrap}>{row.contentOwners?.length}</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>
          </TableRow>
        )}
        data={data || []}
        sortBy={sortBy}
        sortOrder={sortOrder}
        totalCount={totalCount}
        page={page}
        rowsPerPage={pageSize}
        onFilter={handleFilter}
      />
    </CommonList>
  );
}

export default List;
