import * as React from 'react';
import { FormattedMessage } from 'react-intl';

import { ChannelDetails } from 'mweb/common/reducers/data/channels';
import { ChannelThumbnailListItemCard } from 'mweb/common/components/channelThumbnailCard';
import { THUMBNAIL_ASPECT_RATIO } from 'mweb/common/utils/imageUtils';
import { List } from 'mweb/common/components/list';
import {
  estimateImageCountForViewport,
  ImageType,
} from 'mweb/common/utils/estimateImageCountForViewport';
import { extendInteractionMedium } from 'mweb/common/tracking/extendInteractionMedium';

if (process.env.BROWSER) {
  require('./channelList.sass');
}

export interface ChannelListProps {
  channels: ChannelDetails[];
  gameDisplayName: string | undefined;
  getNextPage: () => void;
}

const INITIAL_PAGE_SIZE = 6;
const CHANNEL_THUMBNAIL_METADATA_HEIGHT = 67;
const INTERACTION_MEDIUM = 'channel_list';
const CHANNEL_THUMBNAIL_SIZES = [
  {
    size: '96vw',
    mediaCondition: '(max-width: 540px) and (orientation: portrait)',
  },
  {
    size: '32.33vw',
    mediaCondition: '(min-width: 768px) and (orientation: landscape)',
  },
  { size: '48.5vw' },
];

export class ChannelListBase extends React.Component<ChannelListProps, {}> {
  totalLatencyCount: number = 0;

  constructor(props: ChannelListProps) {
    super(props);

    if (process.env.BROWSER) {
      this.totalLatencyCount = Math.min(
        INITIAL_PAGE_SIZE,
        estimateImageCountForViewport(
          THUMBNAIL_ASPECT_RATIO,
          CHANNEL_THUMBNAIL_METADATA_HEIGHT,
          ImageType.Channel,
        ),
      );
    }
  }

  itemRenderer = (index: number, key: string): JSX.Element => {
    const channel = this.props.channels[index];
    return (
      <ChannelThumbnailListItemCard
        imageTemplate={channel.preview}
        logoURL={channel.logoURL}
        key={key}
        name={channel.name}
        displayName={channel.displayName}
        title={channel.status}
        gameName={channel.game}
        viewCount={channel.viewerCount}
        isLatencyCritical={index < this.totalLatencyCount}
        position={index}
        srcSetSizes={CHANNEL_THUMBNAIL_SIZES}
      />
    );
  };

  emptyList(): JSX.Element {
    return (
      <h4 className="channel-list-empty">
        <FormattedMessage
          id="channel-list--empty"
          defaultMessage={`There are no channels currently live for {game}.`}
          values={{ game: this.props.gameDisplayName || 'Twitch' }}
        />
      </h4>
    );
  }

  render(): JSX.Element {
    if (this.props.channels.length === 0) {
      return this.emptyList();
    }

    return (
      <List
        itemRenderer={this.itemRenderer}
        length={this.props.channels.length}
        getNextPage={this.props.getNextPage}
        className="channel-list"
        initialPageSize={INITIAL_PAGE_SIZE}
      />
    );
  }
}

export const ChannelList = extendInteractionMedium(
  ChannelListBase,
  INTERACTION_MEDIUM,
);
