import { useState } from 'react';
import { Row } from '@umami/react-zen';
import thenby from 'thenby';
import { percentFilter } from '@/lib/filters';
import { ListTable } from '@/components/metrics/ListTable';
import { useMessages, useWebsite } from '@/components/hooks';
import { FilterButtons } from '@/components/input/FilterButtons';

const FILTER_REFERRERS = 'filter-referrers';
const FILTER_PAGES = 'filter-pages';

export function RealtimeUrls({ data }: { data: any }) {
  const website = useWebsite();
  const { formatMessage, labels } = useMessages();
  const { referrers, urls } = data || {};
  const [filter, setFilter] = useState(FILTER_REFERRERS);
  const limit = 15;

  const buttons = [
    {
      id: FILTER_REFERRERS,
      label: formatMessage(labels.referrers),
    },
    {
      id: FILTER_PAGES,
      label: formatMessage(labels.pages),
    },
  ];

  const renderLink = ({ label: x }) => {
    const domain = x.startsWith('/') ? website?.domain : '';
    return (
      <a href={`//${domain}${x}`} target="_blank" rel="noreferrer noopener">
        {x}
      </a>
    );
  };

  const domains = percentFilter(
    Object.keys(referrers)
      .map(key => {
        return {
          x: key,
          y: referrers[key],
        };
      })
      .sort(thenby.firstBy('y', -1))
      .slice(0, limit),
  );

  const pages = percentFilter(
    Object.keys(urls)
      .map(key => {
        return {
          x: key,
          y: urls[key],
        };
      })
      .sort(thenby.firstBy('y', -1))
      .slice(0, limit),
  );

  return (
    <>
      <Row justifyContent="center">
        <FilterButtons items={buttons} value={filter} onChange={setFilter} />
      </Row>
      {filter === FILTER_REFERRERS && (
        <ListTable
          title={formatMessage(labels.referrers)}
          metric={formatMessage(labels.views)}
          renderLabel={renderLink}
          data={domains.map(({ x, y, z }: { x: string; y: number; z: number }) => ({
            label: x,
            count: y,
            percent: z,
          }))}
        />
      )}
      {filter === FILTER_PAGES && (
        <ListTable
          title={formatMessage(labels.pages)}
          metric={formatMessage(labels.views)}
          renderLabel={renderLink}
          data={pages.map(({ x, y, z }: { x: string; y: number; z: number }) => ({
            label: x,
            count: y,
            percent: z,
          }))}
        />
      )}
    </>
  );
}
