import { Dispatch, FC, SetStateAction } from 'react';
import { useNavigate } from 'react-router-dom';

import {
  IconCircleCheck,
  IconEdit,
  IconInfoCircle,
  IconPlaystationX,
  IconSmartHome,
} from '@material-hu/icons/tabler';
import CircularProgress from '@material-hu/mui/CircularProgress';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuMenuList from '@material-hu/components/composed-components/MenuList';
import HuAvatar from '@material-hu/components/design-system/Avatar';
import Button from '@material-hu/components/design-system/Buttons/Button';
import HuChips from '@material-hu/components/design-system/Chip';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';
import HuPills from '@material-hu/components/design-system/Pills';
import HuTable from '@material-hu/components/design-system/Table';
import HuTableBody from '@material-hu/components/design-system/Table/components/TableBody';
import HuTableCell from '@material-hu/components/design-system/Table/components/TableCell';
import HuTableContainer from '@material-hu/components/design-system/Table/components/TableContainer';
import HuTableRow from '@material-hu/components/design-system/Table/components/TableRow';
import HuTableToolbar from '@material-hu/components/design-system/Table/components/TableToolbar';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import { feedRoutes } from 'src/pages/dashboard/feed/routes';
import { groupsRoutes } from 'src/pages/dashboard/groups/routes';
import {
  DraftInProgressFilters,
  DraftRequest,
  DraftStatus,
} from 'src/types/posts';
import { extractTextFromHTML } from 'src/utils/feed';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName, getInitials } from 'src/utils/userUtils';

import useSidebarIcon from 'src/components/dashboard/sidebar/hooks/useSidebarIcon';
import { InfiniteList } from 'src/components/list';

import { draftsForReviewRoutes } from '../routes';

import EmptyState from './EmptyState';
import PostDraftHeader from './PostDraftHeader';

const getTypeFromState = (state: DraftStatus) => {
  switch (state) {
    case DraftStatus.PENDING:
      return 'info';
    case DraftStatus.OVERDUE:
      return 'warning';
    default:
      return 'info';
  }
};

export type PostDraftTableProps = {
  draftRequests: DraftRequest[];
  onDelete: ({ id }: { id: number }) => void;
  isLoadingGeneral: boolean;
  isLoadingFilter: boolean;
  draftStatus: DraftStatus;
  draftFilter: DraftStatus;
  setDraftFilter: Dispatch<SetStateAction<DraftStatus>>;
  fetchNextPage: any;
  hasNextPage: any;
  isFetchingNextPage: any;
  isFinalAuthorTab: boolean;
};

const PostDraftTable: FC<PostDraftTableProps> = props => {
  const {
    draftRequests,
    onDelete,
    isLoadingGeneral,
    isLoadingFilter,
    draftStatus,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    draftFilter,
    setDraftFilter,
    isFinalAuthorTab,
  } = props;

  const { t } = useLokaliseTranslation(['communication', 'post', 'drafts']);
  const navigate = useNavigate();
  const { Icon } = useSidebarIcon({
    defaultIcon: IconSmartHome,
    key: 'Feed',
  });

  const noResults = !draftRequests?.length;
  const isFilterStatus = [DraftStatus.PENDING, DraftStatus.OVERDUE].includes(
    draftFilter,
  );
  const isGeneralStatus = [
    DraftStatus.APPROVED,
    DraftStatus.IN_PROGRESS,
  ].includes(draftFilter);

  const showFilterEmptyState = isFilterStatus && noResults;
  const showGeneralEmptyState = isGeneralStatus && !isFilterStatus && noResults;

  const isApproved = draftStatus === DraftStatus.APPROVED;

  const handleRowClick = (postDraft: DraftRequest) => {
    if (postDraft.state === DraftStatus.APPROVED) {
      if (postDraft.post.group)
        navigate(groupsRoutes.detail(postDraft.post.group.id));
      else navigate(feedRoutes.feed());
    } else {
      navigate(draftsForReviewRoutes.detail(postDraft.id));
    }
  };

  const getEmptyStateDescription = () => {
    if (!isFinalAuthorTab)
      return t('communication:drafts_for_review.no_draft_description_drafter', {
        context: draftStatus,
      });
    if (isFinalAuthorTab)
      return t('communication:drafts_for_review.no_draft_description_author', {
        context: draftStatus,
      });
  };

  if (isLoadingGeneral) {
    return (
      <Stack sx={{ flex: 1, alignItems: 'center' }}>
        <CircularProgress />
      </Stack>
    );
  }

  return (
    <HuTableContainer
      sx={{
        width: '100%',
        overflow: showGeneralEmptyState ? 'hidden' : 'auto',
      }}
    >
      {!showGeneralEmptyState && (
        <>
          <HuTableToolbar sx={{ gap: 1 }}>
            <Stack
              sx={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 2,
              }}
            >
              <Typography
                variant="globalM"
                fontWeight="fontWeightSemiBold"
              >
                {t('communication:drafts_for_review.draft_status_general', {
                  context: draftStatus,
                })}
              </Typography>
              <HuTooltip
                description={t('communication:drafts_for_review.table_info', {
                  context: `${draftStatus}${isFinalAuthorTab ? '_AUTHOR' : ''}`,
                })}
                direction="right"
              >
                <IconInfoCircle />
              </HuTooltip>
            </Stack>
            {draftStatus === DraftStatus.IN_PROGRESS && (
              <Stack
                sx={{ flexDirection: 'row', gap: 1, alignItems: 'center' }}
              >
                <Typography
                  variant="globalS"
                  fontWeight="fontWeightSemiBold"
                  sx={{ mr: 1 }}
                >
                  {t('communication:drafts_for_review.filter_by_status')}
                </Typography>
                {Object.values(DraftInProgressFilters).map(filter => (
                  <HuChips
                    key={filter}
                    label={t(
                      'communication:drafts_for_review.draft_status_in_progress',
                      {
                        context: filter,
                      },
                    )}
                    isSelected={draftFilter === filter}
                    onClick={() => setDraftFilter(filter)}
                  />
                ))}
              </Stack>
            )}
          </HuTableToolbar>
          <InfiniteList
            isSuccess={!!draftRequests}
            fetchNextPage={fetchNextPage}
            hasNextPage={hasNextPage}
            isFetchingNextPage={isFetchingNextPage}
            renderSkeleton={
              <Stack sx={{ ml: 2 }}>
                <HuListItem loading />
                <HuListItem loading />
                <HuListItem loading />
              </Stack>
            }
            sx={{
              height: '100%',
              maxHeight: 'calc(100vh - 525px)',
              overflow: 'scroll',
            }}
          >
            <HuTable>
              <PostDraftHeader
                isFinalAuthor={isFinalAuthorTab}
                isApproved={isApproved}
              />
              {!isLoadingFilter && (
                <HuTableBody sx={{ cursor: 'pointer' }}>
                  {draftRequests?.map(request => {
                    const { plainText } = extractTextFromHTML(
                      request.post.bodyHtml,
                    );
                    const draftUser = isFinalAuthorTab
                      ? request.draftPermission.userFrom
                      : request.draftPermission.userTo;
                    return (
                      <HuTableRow
                        key={request.id}
                        onClick={() => handleRowClick(request)}
                      >
                        <HuTableCell>
                          <Typography
                            noWrap
                          >{`${plainText.slice(0, 25)}...`}</Typography>
                        </HuTableCell>
                        <HuTableCell>
                          <Stack
                            sx={{
                              flexDirection: 'row',
                              alignItems: 'center',
                              gap: 1,
                            }}
                          >
                            <HuAvatar
                              src={draftUser.profilePicture || undefined}
                              text={getInitials(getFullName(draftUser))}
                            />
                            <Typography noWrap>
                              {getFullName(draftUser)}
                            </Typography>
                          </Stack>
                        </HuTableCell>
                        <HuTableCell>
                          <Stack
                            sx={{
                              flexDirection: 'row',
                              alignItems: 'center',
                              gap: 1,
                            }}
                          >
                            {request.post.group?.icon && (
                              <HuAvatar
                                src={request.post.group?.icon || Icon}
                                size="small"
                              />
                            )}
                            {!request.post.group?.icon && (
                              <IconButton
                                variant="tertiary"
                                sx={{
                                  backgroundColor: theme =>
                                    theme.palette.new.background.elements.grey,
                                  cursor: 'auto',
                                }}
                              >
                                <Icon />
                              </IconButton>
                            )}
                            <Typography noWrap>
                              {request.post.group?.title || t('post:feed')}
                            </Typography>
                          </Stack>
                        </HuTableCell>
                        {!isApproved && (
                          <>
                            <HuTableCell sx={{ width: '100px' }}>
                              <HuPills
                                label={t(
                                  'communication:drafts_for_review.draft_status_in_progress',
                                  {
                                    context: request.state,
                                  },
                                )}
                                hasIcon={request.state === DraftStatus.OVERDUE}
                                size="small"
                                type={getTypeFromState(request.state)}
                              />
                            </HuTableCell>
                            <HuTableCell
                              align="center"
                              sx={{ px: 0 }}
                            >
                              {isFinalAuthorTab && (
                                <Button
                                  variant="secondary"
                                  onClick={() => handleRowClick(request)}
                                >
                                  {t('drafts:main.review')}
                                </Button>
                              )}
                            </HuTableCell>
                            <HuTableCell
                              variant="shortField"
                              align="right"
                              onClick={e => e.stopPropagation()}
                              sx={{ cursor: 'auto', width: '50px' }}
                            >
                              <HuMenuList
                                options={[
                                  {
                                    title: t(
                                      'communication:drafts_for_review.delete_draft_request',
                                    ),
                                    Icon: IconPlaystationX,
                                    onClick: () => onDelete({ id: request.id }),
                                  },
                                ]}
                              />
                            </HuTableCell>
                          </>
                        )}
                      </HuTableRow>
                    );
                  })}
                </HuTableBody>
              )}
            </HuTable>
            {isLoadingFilter && (
              <Stack sx={{ ml: 2 }}>
                <HuListItem loading />
                <HuListItem loading />
              </Stack>
            )}
            {!isLoadingFilter && showFilterEmptyState && (
              <EmptyState
                avatarProps={{
                  Icon: IconCircleCheck,
                  color: 'success',
                }}
                titleProps={{
                  title: '',
                  description: t(
                    draftFilter === DraftStatus.OVERDUE
                      ? 'drafts:main.no_overdue_drafts_yet'
                      : 'drafts:main.no_pending_approval_drafts_yet',
                  ),
                }}
                sx={{
                  p: 4,
                }}
              />
            )}
          </InfiniteList>
        </>
      )}
      {showGeneralEmptyState && !isLoadingFilter && (
        <EmptyState
          avatarProps={{
            Icon: IconEdit,
          }}
          titleProps={{
            title:
              noResults && draftStatus === DraftStatus.IN_PROGRESS
                ? t(
                    isFinalAuthorTab
                      ? 'drafts:main.no_drafts_other_title'
                      : 'communication:drafts_for_review.no_draft_title_drafter',
                  )
                : '',
            description: getEmptyStateDescription(),
          }}
          buttonProps={
            noResults &&
            !isFinalAuthorTab &&
            draftStatus === DraftStatus.IN_PROGRESS
              ? {
                  text: t('communication:drafts_for_review.new_draft'),
                  onClick: () => {
                    navigate(draftsForReviewRoutes.createPostDraft());
                  },
                }
              : undefined
          }
          sx={{
            height: '240px',
          }}
        />
      )}
    </HuTableContainer>
  );
};

export default PostDraftTable;
