import type { FC } from 'react';
import React from 'react';
import { BsTooltip, BsOverlayTrigger } from '@theorchard/suite-components';
import { formatMessage } from '@theorchard/suite-frontend';
import { GlyphIcon } from '@theorchard/suite-icons';
import dayjs from 'dayjs';

export const CLASS_NAME = 'ProductTracksFocusTrackTooltip';
export const INTL_PREFIX = 'contentReview.productTracksFocusTrackTooltip';

const isDateInRange = (
    date: Date,
    rangeStartDate: string | GQLDate,
    rangeEndDate: string | GQLDate | null
) => {
    const startDate = new Date(rangeStartDate);
    let inBounds = date >= startDate;
    if (inBounds && rangeEndDate) {
        const endDate = new Date(rangeEndDate);
        inBounds = date <= endDate;
    }
    return inBounds;
};

export interface Props {
    startDate: GQLDate | null;
    endDate: GQLDate | null;
}

const ProductTracksFocusTrackTooltip: FC<Props> = ({ startDate, endDate }) => {
    let message;
    const today = new Date();
    const active =
        !startDate || isDateInRange(today, startDate, endDate) ? 'active' : '';

    if (startDate) {
        const startDateFormatted = dayjs(startDate).format('DD MMM YYYY');

        if (endDate) {
            const endDateFormatted = dayjs(endDate).format('DD MMM YYYY');
            message = formatMessage(`${INTL_PREFIX}.focusTrackTooltipRange`, {
                startDate: startDateFormatted,
                endDate: endDateFormatted,
            });
        } else {
            message = formatMessage(
                `${INTL_PREFIX}.focusTrackTooltipStartDate`,
                {
                    startDate: startDateFormatted,
                }
            );
        }
    } else {
        message = formatMessage(`${INTL_PREFIX}.focusTrackTooltipNoDates`);
    }

    return (
        <BsOverlayTrigger
            placement="top"
            trigger={['hover', 'focus']}
            overlay={<BsTooltip id="focus-track-tooltip">{message}</BsTooltip>}
        >
            {({ ref, ...triggerHandler }) => (
                <div
                    className={`${CLASS_NAME}-icon ${active}`}
                    ref={ref}
                    {...triggerHandler}
                >
                    <GlyphIcon
                        testId="StarGlyph"
                        name="starred"
                        size={24}
                        inverse
                    />
                </div>
            )}
        </BsOverlayTrigger>
    );
};

export default ProductTracksFocusTrackTooltip;
