import type { FC } from 'react';
import React from 'react';
import { Status } from '@theorchard/suite-components';
import { formatDate, Segment } from '@theorchard/suite-frontend';
import { GlyphIcon } from '@theorchard/suite-icons';
import { OSR_CATEGORY } from 'src/constants';
import { AckStatus } from 'src/data/globalTypes';
import type { CellProps } from './types';
import type { StatusProps } from '@theorchard/suite-components';
import type { FormattedDeliveryHistory } from 'src/data/queries/orchardSoundRecording/selector';

const DATE_FORMAT = 'hh:mma, D MMM YYYY';
const TIKTOK_SERVICE_NAME = 'TikTok (Audio Fingerprinting)';
const NEUTRAL_VARIANT = 'neutral';
export const UNAVAILABLE_LABEL = 'Unavailable';
export const ackStatusToLabelMap: Record<
    AckStatus,
    { label: string; variant: StatusProps['variant'] }
> = {
    [AckStatus.SUCCESS]: {
        label: 'Complete',
        variant: 'success',
    },
    [AckStatus.ERROR]: {
        label: 'Error',
        variant: 'error',
    },
    [AckStatus.AWAITED]: {
        label: 'In Progress',
        variant: 'info',
    },
    [AckStatus.MISSING]: {
        label: UNAVAILABLE_LABEL,
        variant: NEUTRAL_VARIANT,
    },
};

export const DownloadDeliveryFileCell: FC<CellProps<object>> = ({ value }) => (
    <div className="DownloadDeliveryFileCell">
        {value && (
            <div>
                <a
                    onClick={() => {
                        Segment.trackEvent(
                            'Click',
                            { category: OSR_CATEGORY, value: Date.now() },
                            'Download Version'
                        ).catch(console.error);
                    }}
                    href={`${value}`}
                    download
                >
                    <GlyphIcon name="download" size={16} />
                </a>
            </div>
        )}
    </div>
);

export const DateCell: FC<CellProps<object>> = ({ value }) => (
    <div>{formatDate(value, DATE_FORMAT)}</div>
);

export const TypeCell: FC<CellProps<object>> = ({ value }) => (
    <div>
        {value ? (value as string).replaceAll('_', ' ').toLowerCase() : ''}
    </div>
);

const statusVariant = (
    value: string
): React.ComponentProps<typeof Status>['variant'] => {
    const v = value.toLowerCase();
    if (v.includes('success')) return 'success';
    if (v.includes('fail') || v.includes('error')) return 'error';
    if (v.includes('pending') || v.includes('progress')) return 'warning';
    return 'neutral';
};

export const LegacyStatusCell: FC<CellProps<object>> = ({ value }) => {
    if (!value) return <div />;
    const text = (value as string)
        .replaceAll('_', ' ')
        .toLowerCase()
        .replace(/\b\w/g, char => char.toUpperCase());
    return (
        <Status variant={statusVariant(value as string)} filled text={text} />
    );
};

export const IngestionStatusCell: FC<CellProps<FormattedDeliveryHistory>> = ({
    data,
}) => {
    const ack = data.ack;
    const service = data.service;
    if (service !== TIKTOK_SERVICE_NAME) return null;

    const statusLabel = !ack
        ? UNAVAILABLE_LABEL
        : ackStatusToLabelMap[ack].label;
    const statusVariant: StatusProps['variant'] = !ack
        ? NEUTRAL_VARIANT
        : ackStatusToLabelMap[ack].variant;

    return (
        <div>
            <Status text={statusLabel} filled variant={statusVariant} />
        </div>
    );
};
