import React from 'react';
import { createIntl, createIntlCache } from 'react-intl';
import { entitiesReducer } from '../../store/index';
import {
    cellWidth,
    info
} from '@patternfly/react-table/dist/esm/components/Table/index';
import messages from '../../Messages';
import StatusLabel from '../StatusLabel/StatusLabel';
import { Tooltip } from '@patternfly/react-core/dist/esm/components/Tooltip/Tooltip';
import { Link } from 'react-router-dom';
import { DateFormat } from '@redhat-cloud-services/frontend-components/DateFormat';

const cache = createIntlCache();
const locale = navigator.language.slice(0, 2);

export const intl = createIntl({
    locale
}, cache);

export const intlSettings = { locale };

export const defaultOnLoad =
  (columns, getRegistry) =>
      ({ INVENTORY_ACTION_TYPES, mergeWithEntities }) =>
          getRegistry().register({
              ...mergeWithEntities(entitiesReducer(INVENTORY_ACTION_TYPES, columns),
                  {
                      page: 1,
                      perPage: 10,
                      sortBy: {
                          key: 'lastScanDate',
                          direction: 'desc'
                      }
                  })
          });

export const columns = [
    {
        title: intl.formatMessage(messages.name),
        transforms: [cellWidth(45)],
        key: 'displayName',
        sortBy: ['DISPLAY_NAME'],
        renderFunc: (displayName) => <Link to={`/systems/${displayName}`}>{displayName}</Link>
    },
    {
        title: 'Tags',
        key: 'tags',
        props: { width: 10, isStatic: true }
    },
    {
        title: 'OS',
        key: 'osVersion',
        sortBy: ['OS_VERSION'],
        renderFunc: (osVersion) => `RHEL ${osVersion}`
    },
    {
        title: intl.formatMessage(messages.lastStatus),
        transforms: [cellWidth(10)],
        key: 'hasMatch',
        sortBy: ['HAS_MATCH'],
        renderFunc: (hasMatch, _, { isDisabled }) => <StatusLabel isDisabled={isDisabled} hasMatch={hasMatch} displayMatch />
    },
    {
        title: intl.formatMessage(messages.lastMatched),
        transforms: [cellWidth(10)],
        key: 'lastMatchDate',
        sortBy: ['LAST_MATCH_DATE'],
        renderFunc: (lastMatchDate) =>
            lastMatchDate ?
                <Tooltip content={<DateFormat date={new Date(lastMatchDate)} type='exact' />}>
                    <span><DateFormat date={new Date(lastMatchDate)} /></span>
                </Tooltip>
                : <Tooltip content={intl.formatMessage(messages.noHostHas)}>
                    <span>{intl.formatMessage(messages.never)}</span>
                </Tooltip>
    },
    {
        title: intl.formatMessage(messages.totalMatches),
        transforms: [
            cellWidth(15),
            info({
                tooltip: intl.formatMessage(messages.totalMatchesNote)
            })
        ],
        key: 'totalMatches',
        sortBy: ['TOTAL_MATCHES'],
        renderFunc: (totalMatches, _, { displayName }) => <Link to={`/systems/${displayName}`}>{totalMatches?.toLocaleString()}</Link>
    },
    {
        title: intl.formatMessage(messages.lastScan),
        transforms: [cellWidth(10)],
        key: 'lastScanDate',
        sortBy: ['LAST_SCAN_DATE'],
        renderFunc: (lastScanDate) =>
            <Tooltip content={<DateFormat date={new Date(lastScanDate)} type='exact' />}>
                <span><DateFormat date={new Date(lastScanDate)} /></span>
            </Tooltip>

    }
];

export const mergedColumns = (defaultColumns) =>
    columns.map((column) => {
        const isStringCol = typeof column === 'string';
        const key = isStringCol ? column : column.key;
        const defaultColumn = defaultColumns.find(
            (defaultCol) => defaultCol.key === key
        );
        return {
            ...defaultColumn,
            ...(isStringCol ? { key: column } : column),
            props: {
                ...defaultColumn?.props,
                ...column?.props
            }
        };
    });

export const appendDirection = (attributes, direction) =>
    attributes?.map((attribute) => `${attribute}_${direction}`);

export const findColumnByKey = (key) =>
    (columns || []).find((column) => column.key === key);