import * as React from 'react';
import Link from 'next/link';
import { withRouter } from 'next/router';

import Hiperlink from './Link.styled';
import { Forward, Backward, ArrowPlus, Download, Plus } from './LinksIcon';

export interface IProps {
  href?: string;
  children?: React.ReactNode;
  target?: string;
  isType?: string;
  query?: any;
  className?: string;
  css?: string|Object;
  title?: string;
  alt?: string;
  prefetch?: boolean;
  onClick?: (any?: any) => any;
  router: {
    pathname: string;
  };
  isActiveRoute?: boolean;
  routerProvider?: any;
  route?: string;
  params?: any;
}

const renderChildAndTypeIcon = (type?: string, children?: any) => {
  const mapIconLinks = new Map();
  mapIconLinks
    .set('forward', Forward(children))
    .set('backward', Backward(children))
    .set('download', Download(children))
    .set('arrow-plus', ArrowPlus(children))
    .set('plus', Plus(children));

  return mapIconLinks.get(type) || children;
};

export default withRouter(({ href, children, query, isType, router, prefetch, routerProvider, route, params, ...props }: IProps) => {
  const isActiveRoute: boolean = router.pathname === href || router.pathname === `/${href}`;
  const linkProps = { href, ...query && query, prefetch, route, ...params && params };
  const restProps = { isType, isActiveRoute, ...props};
  const LinkComponent = routerProvider || Link;

  return (
    <LinkComponent {...linkProps} passHref>
      <Hiperlink {...restProps}>
        {renderChildAndTypeIcon(isType, children)}
      </Hiperlink>
    </LinkComponent>
  );
});
