import type { FC } from 'react';
import React from 'react';
import {
    TruncatedText,
    GlyphButton,
    Status,
} from '@theorchard/suite-components';
import {
    createHref,
    formatDate,
    formatNumber,
} from '@theorchard/suite-frontend';
import { GlyphIcon } from '@theorchard/suite-icons';
import { Link } from 'react-router-dom';
import {
    EMPTY_CHAR,
    ROUTE_MONITOR_OWNERSHIP,
    TIME_DATE_FORMAT,
} from 'src/constants';
import {
    OwnershipNrDeliveryJobStatus,
    OwnershipNrDeliveryOrderStatus,
} from 'src/data/globalTypes';
import type {
    OwnershipDeliveryOrder,
    OrderSummary,
    CmmTerritory,
    OwnershipNrDeliveryJob,
} from 'src/data/queries';
import type { CellProps } from 'src/types';

export const TRANSLATION_MONITOR_PAGE = 'ownershipRights.monitorOwnershipPage';

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

const capitalize = (s: string) => {
    const string = s.toLowerCase();
    return String(string[0]).toUpperCase() + String(string).slice(1);
};

export const ProductTypeCell: FC<CellProps<object>> | undefined = ({
    value,
}) => (
    <TruncatedText
        text={value ? capitalize(value.toString()) : EMPTY_CHAR}
        maxWidth={220}
    />
);

export const CreatedByCell: FC<CellProps<object>> | undefined = ({
    value,
    data,
}) => {
    const { createdBy } = data as unknown as OwnershipDeliveryOrder;
    const name = `${createdBy?.firstName} ${createdBy?.lastName}`;
    return (
        <TruncatedText
            text={
                value && createdBy?.firstName && createdBy?.lastName
                    ? name
                    : EMPTY_CHAR
            }
            maxWidth={220}
        />
    );
};

export const StoreTerritoryCell: FC<CellProps<object>> | undefined = ({
    value,
    data,
}) => {
    const {
        territory,
        cmm: { ownershipServices },
    } = data as unknown as OwnershipDeliveryOrder;

    let matchedCountry: CmmTerritory | null = null;

    if (ownershipServices!.length > 1 && territory) {
        matchedCountry =
            ownershipServices?.find(
                ({ territory: { territoryCodeA2 } }) =>
                    territoryCodeA2 === territory
            ) ?? null;
    }

    const countryName = matchedCountry?.territory.countryName ?? null;

    if (countryName) {
        return (
            <>
                {value ? value : EMPTY_CHAR}{' '}
                <span className="Cmm-Country-Cell">{`${countryName}`}</span>
            </>
        );
    }

    return (
        <TruncatedText
            text={value ? (`${value}` as string) : EMPTY_CHAR}
            maxWidth={220}
        />
    );
};

export const ServiceNameCell: FC<CellProps<object>> | undefined = ({
    data,
}) => {
    const {
        order: {
            cmm: { name },
        },
    } = data as unknown as OwnershipNrDeliveryJob;
    return (
        <TruncatedText
            text={name ? (`${name}` as string) : EMPTY_CHAR}
            maxWidth={220}
        />
    );
};

export const EntityNameCell: FC<CellProps<object>> | undefined = ({ data }) => {
    const { entityName } = data as unknown as OwnershipNrDeliveryJob;
    return (
        <TruncatedText
            text={entityName ? entityName.toString().toUpperCase() : EMPTY_CHAR}
            maxWidth={220}
        />
    );
};

export const DeliveryFileStatusCell: FC<
    CellProps<{
        status: OwnershipNrDeliveryOrderStatus;
        summary: OrderSummary;
    }>
> = ({ data: { status, summary } }) => {
    if (status === OwnershipNrDeliveryOrderStatus.PENDING)
        return (
            <span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                <GlyphIcon name="inProgress" size={16} className="blue" />
                {$t(`${TRANSLATION_MONITOR_PAGE}.generating`)}
            </span>
        );
    if (status === OwnershipNrDeliveryOrderStatus.ERROR)
        return (
            <span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                <GlyphIcon name="warning" size={16} className="red" />
                {$t(`${TRANSLATION_MONITOR_PAGE}.errorFiles`)}
            </span>
        );
    if (
        (status === OwnershipNrDeliveryOrderStatus.READY ||
            status === OwnershipNrDeliveryOrderStatus.DELIVERED) &&
        summary.soundRecordingsProcessed
    )
        return (
            <span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                {$t(`${TRANSLATION_MONITOR_PAGE}.downloadReady`)}
            </span>
        );
    return <div className="EmptyCell">{EMPTY_CHAR}</div>;
};

export const DeliveryJobStatusCell: FC<
    CellProps<{
        status: OwnershipNrDeliveryJobStatus;
    }>
> = ({ data: { status } }) => {
    if (status === OwnershipNrDeliveryJobStatus.READY)
        return (
            <Status
                variant="info"
                text={$t(`${TRANSLATION_MONITOR_PAGE}.readyForDelivery`)}
                filled
            />
        );
    if (status === OwnershipNrDeliveryJobStatus.CANCELLED)
        return (
            <Status
                variant="neutral"
                text={$t(`${TRANSLATION_MONITOR_PAGE}.cancelled`)}
                filled
            />
        );
    if (status === OwnershipNrDeliveryJobStatus.DELIVERED)
        return (
            <Status
                variant="success"
                text={$t(`${TRANSLATION_MONITOR_PAGE}.completed`)}
                filled
            />
        );
    return (
        <TruncatedText text={$t(`${TRANSLATION_MONITOR_PAGE}.notAvailable`)} />
    );
};

export const DownloadFileButtonCell: FC<
    CellProps<{
        status: OwnershipNrDeliveryOrderStatus;
        downloadFileUrl: string;
        summary: OrderSummary;
    }>
> = ({ data: { status, downloadFileUrl, summary } }) => {
    if (
        (status === OwnershipNrDeliveryOrderStatus.READY ||
            status === OwnershipNrDeliveryOrderStatus.DELIVERED) &&
        summary.soundRecordingsProcessed &&
        !!downloadFileUrl
    )
        return (
            <a className="DownloadFileCell" href={downloadFileUrl}>
                <GlyphButton
                    variant="secondary"
                    name="download"
                    tooltip={$t(`${TRANSLATION_MONITOR_PAGE}.downloadFile`)}
                />
            </a>
        );
    return <div className="EmptyCell">{EMPTY_CHAR}</div>;
};

export const DownloadJobFileCell: FC<
    CellProps<{
        jobFileUrl: string;
    }>
> = ({ data: { jobFileUrl } }) => {
    if (jobFileUrl)
        return (
            <a className="DownloadFileCell" href={jobFileUrl}>
                <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<{
        id: string;
        jobCount: number;
        status: OwnershipNrDeliveryOrderStatus;
        downloadFileUrl: string;
    }>
> = ({ data: { id, jobCount, status, downloadFileUrl } }) => {
    if (status === OwnershipNrDeliveryOrderStatus.ERROR) return <div></div>;
    if (status === OwnershipNrDeliveryOrderStatus.PENDING)
        return <GlyphIcon name="inProgress" size={16} className="blue" />;
    if (
        (status === OwnershipNrDeliveryOrderStatus.READY && jobCount === 0) ||
        !downloadFileUrl
    )
        return <div>{jobCount}</div>;
    if (
        status === OwnershipNrDeliveryOrderStatus.READY &&
        !!downloadFileUrl &&
        jobCount !== 0
    )
        return (
            <Link
                to={createHref(ROUTE_MONITOR_OWNERSHIP, {
                    showBy: 'jobs',
                    orderId: id,
                    tab: 'ownership',
                })}
            >
                {formatNumber(jobCount, {
                    digitGrouping: true,
                    fractionalDigits: 0,
                })}
            </Link>
        );

    return <div className="EmptyCell">{EMPTY_CHAR}</div>;
};

export const JobUpdatedAtCell:
    | FC<CellProps<OwnershipNrDeliveryJob>>
    | undefined = ({ data, value }) => {
    if (
        data.status === OwnershipNrDeliveryJobStatus.CANCELLED ||
        data.status === OwnershipNrDeliveryJobStatus.DELIVERED
    )
        return <>{value ? formatDate(value, TIME_DATE_FORMAT) : EMPTY_CHAR}</>;
    return <div className="EmptyCell">{EMPTY_CHAR}</div>;
};

export const JobUpdatedByCell:
    | FC<CellProps<OwnershipNrDeliveryJob>>
    | undefined = ({ data, value }) => {
    if (
        data.status === OwnershipNrDeliveryJobStatus.CANCELLED ||
        data.status === OwnershipNrDeliveryJobStatus.DELIVERED
    )
        return (
            <TruncatedText
                text={value?.toString() ?? EMPTY_CHAR}
                maxWidth={200}
            />
        );
    return <div className="EmptyCell">{EMPTY_CHAR}</div>;
};

export const InstanceCountCell: FC<
    CellProps<{
        instanceCount: number;
    }>
> = ({ data: { instanceCount } }) => {
    return (
        <div>
            {formatNumber(instanceCount, {
                digitGrouping: true,
                fractionalDigits: 0,
            })}
        </div>
    );
};
