import { IRecommendation, sendTrackingData } from '@rh-support/api';
import isEmpty from 'lodash/isEmpty';
import map from 'lodash/map';
import React, { useRef } from 'react';
import CaseUtils from '../../utils/caseUtils';
import MoreOrLess from '../shared/MoreOrLess';

interface IProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement> {
    doc: IRecommendation;
    index: number;
    guid: string;
}
const defaultProps: Partial<IProps> = {
    className: ''
};

export default function ResultRow(props: IProps) {
    const { doc, index, className, ...divProps } = props;

    const tagRef: React.MutableRefObject<any> = useRef(null);
    const sendTracking = (title: string, link: string) => () => {
        sendTrackingData('url_visited', [title, link], props.guid);
    };

    const computeMarkDownNonIssue = (item) => {
        const abstract = (!isEmpty(item.publishedAbstract)) ? item.publishedAbstract : item.abstract;
        return { __html: computeMarkDown(abstract)};
    };

    const computeMarkDownIssue = (issue) => {
        // when we have array of issues with array length
        // greater than zero we should remove '-' form start
        // of the issue otherwise we will have double list
        issue = issue.replace(/^- /, '');
        return { __html: computeMarkDown(issue) };
    };

    const computeMarkDown = (str: string) => {
        // remove leading space form code block
        str = str.replace(/~~~ /g, '~~~');

        // add new line before and after ~~~ in order to be compiled as code block
        str = str.replace(/~~~/g, '\n~~~\n');

        // add new line before '-' in order to be compiled as ordered list
        str = str.replace(/- /g, '\n- ');

        // handle h tags at the beginning of abstract
        if (str.substring(0, 12) === '### Overview') {
            str = str.replace('### Overview', '');
        } else if (str.substring(0, 3) === '###') {
            str = str.replace('###', '');
        } else if (str.substring(0, 2) === '##') {
            str = str.replace('##', '');
        } else if (str.substring(0, 1) === '#') {
            str = str.replace('#', '');
        }

        return (CaseUtils.markdownToHTML(str, {
            openLinksInNewTab: true,
            jsMarkdownExtra: true
        }));
    };

    const computeFormattedDate = (date) => {
        date = new Date(date);
        const monthIndex = date.getMonth();
        const dd = date.getDate();
        const yyyy = date.getFullYear();
        const monthNames = [
            'January', 'February', 'March',
            'April', 'May', 'June', 'July',
            'August', 'September', 'October',
            'November', 'December'
        ];
        const formattedDate = `${monthNames[monthIndex]}  ${dd}, ${yyyy}`;

        return formattedDate;
    };

    return (
        <div className={`result ${className}`} {...divProps}>
            <header className="result-header">
                <a href={`${doc.view_uri}?band=se`}
                    className="se-recommended ts-result"
                    target="_blank"
                    onClick={sendTracking(CaseUtils.getRecommendationTitle(doc), doc.view_uri)}>
                        {CaseUtils.getRecommendationTitle(doc)}
                </a>
                <div className="header-meta">
                    {doc.kcsState === 'verified' && (<>
                        <span className="status-verified">verified</span>
                        <span className="list-separator">&ndash;</span>
                    </>)}
                    <span className="meta">{doc.documentKind}</span>
                    <span className="list-separator">&ndash;</span>
                    <time className="moment_date meta" title={doc.lastModifiedDate.toString()}>
                        {computeFormattedDate(doc.lastModifiedDate)}
                    </time>
                </div>
            </header>
            {doc.issue && doc.issue.length !== 1 && (<div className="issue-wrap" ref={tagRef}>
                <ul className="list-flushleft">
                    {map(doc.issue, (issueItem, i) => (
                        <li className="result-issue"
                            key={`${doc.id}-${i}-issue`}
                            dangerouslySetInnerHTML={computeMarkDownIssue(issueItem)} />
                    ))}
                </ul>
            </div>
            )}
            {doc.issue && doc.issue.length === 1 && (
                <div ref={tagRef} className="issue-wrap" dangerouslySetInnerHTML={computeMarkDownIssue(doc.issue[0])} />
             )}
            {doc.documentKind !== 'Solution' &&
                <div ref={tagRef} className="issue-wrap"><div dangerouslySetInnerHTML={computeMarkDownNonIssue(doc)} /></div>
            }
            <MoreOrLess tagRef={tagRef}/>
        </div>
    );
}
ResultRow.defaultProps = defaultProps;
