import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import PodcastCard from './podcast-card';

function debounce(func, timeout = 50) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, timeout);
  };
}

function useWindowWidth() {
  const [windowWidth, setWindowWidth] = useState(undefined);
  useEffect(() => {
    function handleResize() {
      setWindowWidth(window.innerWidth);
    }
    const processResize = debounce(() => handleResize());
    window.addEventListener('resize', processResize);
    handleResize();

    return () => window.removeEventListener('resize', handleResize);
  }, []);
  return windowWidth;
}

const podcastIdentBaseUrl =
  'https://cdn.design-system.economist.com/assets/latest/common/static/images/podcast-idents/';

const podcastTypes = [
  {
    headline: 'The World in Brief',
    topic: 'Current Affairs',
    description:
      'Understand what’s on the global agenda with this daily news briefing.',
    cadence: 'Weekly',
    imageProps: { src: `${podcastIdentBaseUrl}the-world-in-brief.png` },
  },
  {
    headline: 'Babbage',
    topic: 'Science and Technology',
    description:
      'Learn about the latest innovations and discoveries in science and technology. ',
    cadence: 'Weekly',
    imageProps: { src: `${podcastIdentBaseUrl}babbage.png` },
  },
  {
    headline: 'Drum Tower',
    topic: 'China',
    description:
      'Dig into the stories and issues at the heart of China with our correspondents.',
    cadence: 'Weekly',
    imageProps: { src: `${podcastIdentBaseUrl}drum-tower.png` },
  },
  {
    headline: 'Money Talks',
    topic: 'Business and Economics',
    description:
      'Make sense of the biggest stories in economics, business and markets.',
    cadence: 'Weekly',
    imageProps: { src: `${podcastIdentBaseUrl}money-talks.png` },
  },
  {
    headline: 'Checks and Balance',
    topic: 'US Politics',
    description:
      'Stay ahead on American politics with an in-depth discussions from our correspondents.',
    cadence: 'Weekly',
    imageProps: { src: `${podcastIdentBaseUrl}checks-and-balance.png` },
  },
];

export default {
  title: 'common/Podcast Card',
  component: PodcastCard,
  parameters: {
    controls: { expanded: true },
  },
  args: {
    url: '/podcast-url',
    imageProps: {
      src: `${podcastIdentBaseUrl}babbage.png`,
    },
    ctaText: 'Follow',
    cadence: 'Weekly',
    // eslint-disable-next-line no-console
    ctaFunction: () => console.log('Podcast card clicked'),
  },
};

const PodcastGrid = ({ overrides }) => {
  const width = useWindowWidth();

  let columns = 4;
  if (width > 960) {
    columns = 4;
  } else if (width > 600) {
    columns = 3;
  } else if (width > 360) {
    columns = 2;
  }
  return (
    <div
      style={{
        display: 'grid',
        gridGap: 'var(--ds-grid-gutter)',
        gridTemplateColumns: `repeat(${columns}, 1fr)`,
      }}
    >
      {podcastTypes.map((podcast, index) => (
        <PodcastCard
          {...podcast}
          {...overrides}
          key={podcast.headline}
          imageProps={{
            ...podcast.imageProps,
            alt: index % 2 === 0 ? '' : `Ident for ${podcast.headline}`,
          }}
        />
      ))}
    </div>
  );
};

PodcastGrid.propTypes = {
  overrides: PropTypes.shape({
    headline: PropTypes.string,
    topic: PropTypes.string,
    description: PropTypes.string,
    cadence: PropTypes.string,
    url: PropTypes.string.isRequired,
    imageProps: PropTypes.shape({
      src: PropTypes.string.isRequired,
      alt: PropTypes.string,
      srcset: PropTypes.string,
      sizes: PropTypes.string,
    }),
    ctaText: PropTypes.string,
    ctaFunction: PropTypes.func,
  }).isRequired,
};

export const podcastCard = args => {
  const podcast = podcastTypes[0];

  return (
    <div style={{ maxWidth: '400px' }}>
      <PodcastCard
        {...podcast}
        {...args}
        key={podcast.headline}
        imageProps={{ ...args.imageProps, alt: podcast.headline }}
      />
    </div>
  );
};

export const podcastCardInGrid = args => (
  <PodcastGrid overrides={{ ...args }} />
);
