import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'clsx';
import Image from 'next/image';
import { Inventory2Outlined, PlayArrowRounded } from '@mui/icons-material';
import ArrowDropDown from '@mui/icons-material/ArrowDropDown';

import { TABLE_HEADERS, TABS_CONFIG } from '../../constants';
import { SORT_DESC } from '@/modules/@common/constants/sort';
import { EDITORIAL_PAGE } from '@/modules/@common/router/constants';
import { PDF_EXPORT_HIDE_SCROLL } from '@/modules/analytics/common/constants';

import { abbreviateNumber } from '@/modules/@common/helpers/number';
import { getDuration } from '@/modules/@common/helpers/time';

import TextTooltip from './TextTooltip';
import {
  Button,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TableScroll,
  TableSortLabel,
  Typography,
} from '@/mui/components';

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

function VideoTable(props) {
  const handleClickRow = (id) => {
    props.setField({ selectedItemId: id });
    props.getItemMetrics(id);
  };

  return (
    <TableContainer elevation={0} className={styles.Wrapper}>
      <TableScroll inverseYScroll data-pdf-export={PDF_EXPORT_HIDE_SCROLL}>
        <Table stickyHeader aria-label="sticky table" size="small">
          <TableHead>
            <TableRow>
              {TABLE_HEADERS.map((header) => {
                const text = (
                  <Typography variant="captionSmall" whiteSpace="nowrap">
                    {header.getLabel(props.activeTabId)}
                  </Typography>
                );

                return (
                  <TableCell key={header.id} align={header.align} className={styles.TableCell}>
                    {header.sortable && (
                      <TableSortLabel
                        IconComponent={ArrowDropDown}
                        active={props.sortBy === header.id}
                        direction={props.sortBy === header.id ? props.sortOrder?.toLowerCase() : SORT_DESC}
                        onClick={() => {
                          const isDesc = props.sortBy === header.id && props.sortOrder === 'DESC';
                          props.setField({
                            sortBy: header.id,
                            sortOrder: isDesc ? 'ASC' : 'DESC',
                          });
                          props.handleSearchAndSorting();
                        }}
                      >
                        {text}
                      </TableSortLabel>
                    )}
                    {!header.sortable && text}
                  </TableCell>
                );
              })}
            </TableRow>
          </TableHead>
          <TableBody>
            {props.tableItems.map((video) => {
              const { uuid, name, thumbnail, thumbnails, numOfViews, attentionSpan, engScore, duration, status } =
                video;

              const smallThumbnail =
                props.activeTabId === TABS_CONFIG.VIDEOS.id ? thumbnails?.find((item) => item?.height === 48) : null;

              return (
                <TableRow
                  key={uuid}
                  className={classNames(styles.TableBodyRow, {
                    [styles.TableBodyRow___selected]: uuid === props.selectedItemId,
                  })}
                  onClick={() => handleClickRow(uuid)}
                >
                  <TableCell className={classNames(styles.TableCell, styles.TableCell___title)}>
                    <Stack spacing={2} direction="row" alignItems="center">
                      {props.activeTabId === TABS_CONFIG.VIDEOS.id && (
                        <div className={styles.ItemVideoThumb}>
                          <Image
                            src={smallThumbnail ? smallThumbnail.file : thumbnail}
                            alt="thumb"
                            className={styles.ItemVideoThumbImage}
                            fill
                            unoptimized
                            loading="eager"
                          />
                          <Typography
                            className={styles.ItemVideoThumbDuration}
                            variant="captionSmall"
                            fontWeight={500}
                            color="common.white"
                          >
                            {getDuration(duration)}
                          </Typography>
                          {status === 'DISABLED' && (
                            <Inventory2Outlined
                              fontSize="xSmall"
                              htmlColor="common.white"
                              className={styles.ItemVideoThumbStatus}
                            />
                          )}
                        </div>
                      )}

                      <Stack spacing={2} alignItems="center" direction="row" className={styles.ItemVideoName}>
                        <TextTooltip text={name} />

                        {props.activeTabId === TABS_CONFIG.VIDEOS.id && (
                          <Button
                            square
                            shape="circular"
                            size="xSmall"
                            className={classNames(styles.LinkIconWrapper, {
                              [styles.LinkIconWrapper___visible]: uuid === props.selectedItemId,
                            })}
                            disabled={uuid !== props.selectedItemId}
                            color="primary"
                            startIcon={<PlayArrowRounded />}
                            onClick={() => {
                              window.open(`${EDITORIAL_PAGE.path}?videoId=${props.selectedItemId}`, '_blank');
                            }}
                          />
                        )}
                      </Stack>
                    </Stack>
                  </TableCell>

                  <TableCell align="center" className={styles.TableCell}>
                    <Typography variant="captionSmall" color="text.primary" fontWeight={400}>
                      {abbreviateNumber(numOfViews, 2)}
                    </Typography>
                  </TableCell>

                  <TableCell align="center" className={styles.TableCell}>
                    <Typography variant="captionSmall" color="text.primary" fontWeight={400}>
                      {`${attentionSpan?.toFixed(1)}%`}
                    </Typography>
                  </TableCell>

                  <TableCell align="center" className={styles.TableCell}>
                    <Typography variant="captionSmall" color="text.primary" fontWeight={400}>
                      {engScore?.toFixed(1)}
                    </Typography>
                  </TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </TableScroll>
    </TableContainer>
  );
}

VideoTable.propTypes = {
  activeTabId: PropTypes.string,
  tableItems: PropTypes.arrayOf(
    PropTypes.shape({
      uuid: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired,
      thumbnail: PropTypes.string.isRequired,
      numOfViews: PropTypes.number.isRequired,
      attentionSpan: PropTypes.number.isRequired,
      engScore: PropTypes.number.isRequired,
    }),
  ).isRequired,
  sortBy: PropTypes.string.isRequired,
  sortOrder: PropTypes.string.isRequired,
  selectedItemId: PropTypes.string.isRequired,

  setField: PropTypes.func.isRequired,
  handleSearchAndSorting: PropTypes.func.isRequired,
  getItemMetrics: PropTypes.func.isRequired,
};

export default VideoTable;
