import React, { type FC } from 'react';
import { TruncatedText } from '@theorchard/suite-components';
import {
    createHref,
    ENV_PROD,
    formatDate,
    useAppConfig,
} from '@theorchard/suite-frontend';
import { GlyphIcon } from '@theorchard/suite-icons';
import { Link } from 'react-router-dom';
import {
    EMPTY_CHAR,
    ROUTE_MONITOR_PERFORMANCE,
    SONG_DATE_FORMAT,
    TIME_DATE_FORMAT,
} from 'src/constants';
import {
    NrContributorDeliveryStoreStatus,
    NrDeliveryJobStatus,
    NrDeliveryOrderStatus,
} from './data/globalTypes';
import { type DeliveryJobs } from './data/queries';
import { type CellProps } from './types';
import {
    recordDownloadFileClicked,
    recordNumberOfJobsClicked,
} from './utils/segment/clickEvents';

export const TRANSLATION_MONITOR_PAGE = 'neighbouringRights.monitorPage';

export const LoadingCommonCell = () => (
    <div className="loading" data-testid="LoadingCommonCell">
        <div className="loading-common-bar" />
    </div>
);

export const DateCell: FC<CellProps<object>> = ({ value }) => (
    <div className="DateCell">
        {value ? formatDate(value, SONG_DATE_FORMAT) : EMPTY_CHAR}
    </div>
);

export const TimeDateCell: FC<CellProps<object>> = ({ value }) => (
    <div className="DateCell">
        {value ? formatDate(value, TIME_DATE_FORMAT) : EMPTY_CHAR}
    </div>
);

export const TextCell: FC<CellProps<object>> | undefined = ({ value }) => (
    <TruncatedText
        text={value ? (value as string) : EMPTY_CHAR}
        maxWidth={220}
    />
);

export const StatusCell: FC<CellProps<object>> | undefined = ({ value }) => {
    const formatted = value ? (value as string) : EMPTY_CHAR;
    return (
        <TruncatedText
            text={
                formatted ===
                NrContributorDeliveryStoreStatus.REGISTRATION_CONFIRMED
                    ? NrContributorDeliveryStoreStatus.REGISTERED
                    : formatted
            }
            maxWidth={200}
        />
    );
};

export const DownloadFileCell: FC<
    CellProps<{ status: NrDeliveryOrderStatus; outputFile: string }>
> = ({ data: { status, outputFile } }) => {
    if (
        status === NrDeliveryOrderStatus.PROCESSING_JOBS ||
        status === NrDeliveryOrderStatus.STARTED ||
        status === NrDeliveryOrderStatus.QUEUED
    )
        return <span>{$t(`${TRANSLATION_MONITOR_PAGE}.generating`)}</span>;
    if (status === NrDeliveryOrderStatus.ERROR)
        return (
            <span className="error">
                <GlyphIcon name="warning" size={12} />{' '}
                {$t(`${TRANSLATION_MONITOR_PAGE}.generationError`)}
            </span>
        );
    if (status === NrDeliveryOrderStatus.SUCCESS && !!outputFile)
        return (
            <a
                className="DownloadFileCell"
                href={outputFile}
                onClick={recordDownloadFileClicked}
            >
                <span className="DownloadFileCell">
                    <GlyphIcon name="download" size={16} />
                    {$t(`${TRANSLATION_MONITOR_PAGE}.downloadReady`)}
                </span>
            </a>
        );
    return <div className="EmptyCell">{EMPTY_CHAR}</div>;
};

export const OrderIdLinkCell: FC<
    CellProps<{
        orderId: string;
        numberOfJobs: number;
        status: NrDeliveryOrderStatus;
        outputFile: string;
    }>
> = ({ data: { orderId, numberOfJobs, status, outputFile } }) => {
    if (status === NrDeliveryOrderStatus.ERROR) return <div>N/A</div>;
    if (
        status === NrDeliveryOrderStatus.PROCESSING_JOBS ||
        status === NrDeliveryOrderStatus.STARTED ||
        !outputFile
    )
        return <div>{numberOfJobs}</div>;
    if (status === NrDeliveryOrderStatus.SUCCESS && !!outputFile)
        return (
            <Link
                to={createHref(ROUTE_MONITOR_PERFORMANCE, {
                    showBy: 'jobs',
                    orderId,
                })}
                onClick={recordNumberOfJobsClicked}
            >
                <TruncatedText text={numberOfJobs.toString()} maxWidth={200} />
            </Link>
        );

    return <div>{EMPTY_CHAR}</div>;
};

export const JobStatusCell: FC<CellProps<{ status: NrDeliveryJobStatus }>> = ({
    data: { status },
}) => {
    if (status === NrDeliveryJobStatus.STARTED)
        return (
            <span>{$t(`${TRANSLATION_MONITOR_PAGE}.generatingFile`)}...</span>
        );
    if (status === NrDeliveryJobStatus.SUCCESS)
        return (
            <span className="JobStatus-ready">
                {$t(`${TRANSLATION_MONITOR_PAGE}.readyForDelivery`)}
            </span>
        );
    if (status === NrDeliveryJobStatus.COMPLETE)
        return (
            <span className="JobStatus-complete">
                {$t(`${TRANSLATION_MONITOR_PAGE}.complete`)}
            </span>
        );
    if (status === NrDeliveryJobStatus.CANCELLED)
        return (
            <span className="JobStatus-cancelled">
                {$t(`${TRANSLATION_MONITOR_PAGE}.cancelled`)}
            </span>
        );
    if (status === NrDeliveryJobStatus.ERROR)
        return (
            <span className="JobStatus-error">
                {$t(`${TRANSLATION_MONITOR_PAGE}.error`)}
            </span>
        );
    return <div className="EmptyCell">{EMPTY_CHAR}</div>;
};

export const JobUpdatedAtCell: FC<CellProps<DeliveryJobs>> | undefined = ({
    data,
    value,
}) => {
    if (
        data.status === NrDeliveryJobStatus.CANCELLED ||
        data.status === NrDeliveryJobStatus.COMPLETE
    )
        return <>{value ? formatDate(value, SONG_DATE_FORMAT) : EMPTY_CHAR}</>;
    return <div>{EMPTY_CHAR}</div>;
};

export const JobUpdatedByCell: FC<CellProps<DeliveryJobs>> | undefined = ({
    data,
    value,
}) => {
    if (
        data.status === NrDeliveryJobStatus.CANCELLED ||
        data.status === NrDeliveryJobStatus.COMPLETE
    )
        return (
            <TruncatedText
                text={value?.toString() ?? EMPTY_CHAR}
                maxWidth={200}
            />
        );
    return <div>{EMPTY_CHAR}</div>;
};

export const SoundRecordingLinkCell: FC<
    CellProps<{ soundRecordingTitle: string; soundRecordingId: string }>
> = ({ data: { soundRecordingTitle, soundRecordingId } }) => {
    const { environment } = useAppConfig();
    let contentUrl = `https://content.qaorch.com/catalog/sr-performance/${soundRecordingId}/`;
    if (environment === ENV_PROD)
        contentUrl = `https://content.theorchard.com/catalog/sr-performance/${soundRecordingId}/`;

    return (
        <Link to={{ pathname: contentUrl }} target="_blank">
            <TruncatedText text={soundRecordingTitle} maxWidth={200} />
        </Link>
    );
};
