import React from 'react';
import format from 'date-fns/format';
import { LineChart, XAxis, YAxis, Line, CartesianGrid } from 'recharts';
import { lighten } from 'polished';

import { Countries, CountryCases, Data } from '../types';
import { getCases } from '../utils/get-cases';
import { processCases } from '../utils/regression';

const margin = {
  top: 0,
  right: 0,
  bottom: 0,
  left: 0,
};

const dateTickFormatter = (date: Date): string => {
  return format(new Date(date), 'LLL do'); // 'Do MMM');
};

type Props = {
  countries: Countries;
};

const GraphCases: React.FC<Props> = ({ countries }) => {
  const [showCumulative, setCumulative] = React.useState<boolean>(true);

  const countryCases = React.useMemo<CountryCases>(
    () =>
      countries.map(({ country, rawData }) => ({
        country,
        dataSource: getCases(rawData),
      })),
    [countries],
  );

  const data = React.useMemo<Data>(() => processCases(countryCases, showCumulative), [
    countryCases,
    showCumulative,
  ]);

  if (!data.length) {
    return (
      <div>
        <h3>No data!</h3>
      </div>
    );
  }

  return (
    <div>
      <p>
        <input type="radio" onChange={(): void => setCumulative(true)} checked={showCumulative} />
        Cumulative
        <input type="radio" onChange={(): void => setCumulative(false)} checked={!showCumulative} />
        Daily
      </p>
      <LineChart width={640} height={480} data={data} margin={margin}>
        <XAxis
          dataKey="xValue"
          domain={['auto', 'auto']}
          tickFormatter={dateTickFormatter}
          type="number"
        />
        <YAxis tick yAxisId="left" domain={[50, 'auto']} />
        <CartesianGrid stroke="#f5f5f5" />
        {countries.map(({ country, color }) => (
          <Line
            key={`actual-${country}`}
            type="monotone"
            dataKey={`value.${country}`}
            stroke={color}
            yAxisId="left"
            dot={false}
            strokeWidth={2}
          />
        ))}
        {countries.map(({ country, color }) => (
          <Line
            key={`regression-${country}`}
            type="monotone"
            dataKey={`regression.${country}`}
            stroke={lighten(0.1)(color)}
            yAxisId="left"
            dot={false}
          />
        ))}
      </LineChart>
      <ul>
        {countries.map(({ country, color }, index) => (
          <li key={country} style={{ color }}>
            <h3>{country}</h3>
            <p style={{ color: 'black' }}>
              Source:{' '}
              <a href={countryCases[index].dataSource.source}>
                {countryCases[index].dataSource.source}
              </a>
            </p>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default GraphCases;
