import type { FC } from 'react';
import React, { useRef } from 'react';
import { Pill, Tooltip, TruncatedText } from '@theorchard/suite-components';
import {
    createHref,
    formatDate,
    useIdentity,
} from '@theorchard/suite-frontend';
import { CountryFlag, GlyphIcon } from '@theorchard/suite-icons';
import { Link } from 'react-router-dom';
import {
    EMPTY_CHAR,
    ORDER_DATE_TIME_FORMAT,
    ROUTE_SONG,
    SONG_DATE_FORMAT,
} from 'src/constants';
import { formatNameVersion } from 'src/utils/formatter';
import { recordSRIdClick } from 'src/utils/segment/clickEvents';
import { isDateValid } from 'src/utils/utils';
import type { CellProps } from '../pages/catalogPage/types';
import type { OwnershipNrProduct } from 'src/data/queries/getOwnershipNrTracks';
import type {
    OwnershipNrParticipant,
    OwnershipNrTerritory,
} from 'src/data/types';

export const CountryCell: FC<
    CellProps<{ territory: OwnershipNrTerritory }>
> = ({ data }) => {
    const { countryName, territoryCodeA2 } = data.territory;
    return (
        <>
            <CountryFlag countryCode={territoryCodeA2} />
            <TruncatedText text={countryName || EMPTY_CHAR} maxWidth={200} />
        </>
    );
};

export const PercentageCell: FC<CellProps<object>> | undefined = ({
    value,
}) => (
    <TruncatedText
        text={value ? `${value as string}%` : EMPTY_CHAR}
        maxWidth={200}
    />
);

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

export const UpcCell: FC<CellProps<{ product: OwnershipNrProduct | null }>> = ({
    data: { product },
}) => <div className="UpcCell">{product?.upc ?? '-'}</div>;

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

export const ProductDateCell: FC<
    CellProps<{ product: OwnershipNrProduct | null }>
> = ({ data: { product } }) => (
    <div className="DateCell">
        {product
            ? formatDate(product.salesStartDate, SONG_DATE_FORMAT)
            : EMPTY_CHAR}
    </div>
);

export const SongNameLinkCell: FC<
    CellProps<{ srNameVersion: string; id: string }>
> = ({ data: { srNameVersion, id } }) => {
    const target = useRef(null);
    const { roles } = useIdentity();
    const isOwnershipUser = roles?.includes('manage_nr_ownership');
    const useLink = !!id && isOwnershipUser;
    return useLink ? (
        <Link
            to={createHref(ROUTE_SONG, { id })}
            ref={target}
            onClick={recordSRIdClick}
        >
            <TruncatedText text={srNameVersion} maxWidth={350} />
        </Link>
    ) : (
        <TruncatedText text={srNameVersion} maxWidth={350} />
    );
};

export const PrimaryArtistCell: FC<
    CellProps<{ primaryArtists: OwnershipNrParticipant[] }>
> = ({ data: { primaryArtists } }) => {
    const primaryArtistsString = primaryArtists
        .map(item => item.name)
        .join(', ');
    return <TruncatedText text={primaryArtistsString} maxWidth={200} />;
};

export const NameVersionCell: FC<
    CellProps<{
        title: string;
        version: string | null;
        isrc: string;
        reference: boolean;
    }>
> = ({ data: { title, version, isrc, reference } }) => (
    <div className="NameVersionCell">
        <div className="NameVersionCellTitle">
            <TruncatedText
                text={formatNameVersion(title, version)}
                maxWidth={250}
            />
            <div className="NameVersionCellIsrc">{isrc}</div>
        </div>
        {reference ? (
            <Tooltip
                id="tooltip-info"
                message={$t('ownershipRights.instances.titles.tooltip')}
            >
                <GlyphIcon name="info" size={16} />
            </Tooltip>
        ) : null}
    </div>
);

export const AccountNameCell: FC<
    CellProps<{ accountName: string; accountId: string; subaccountId: number }>
> = ({ data: { accountName, accountId, subaccountId } }) => {
    const accountNameWithSubaccountId =
        subaccountId !== 0
            ? `(${accountId}) - (${subaccountId})`
            : `(${accountId})`;
    return (
        <div className="AccountNameCell">
            <TruncatedText text={accountName} maxWidth={200} />
            <div className="AccountNameCellId">
                {accountNameWithSubaccountId}
            </div>
        </div>
    );
};

export const ProductInfoCell: FC<
    CellProps<{
        productInfo: string;
        productName: string;
    }>
> = ({ data: { productInfo, productName } }) => (
    <div className="ProductInfoNameCell">
        <TruncatedText text={productName} maxWidth={270} />
        <div className="ProductInfoCell">{productInfo}</div>
    </div>
);

export const DeliveryFileLinkCell: FC<
    CellProps<{ downloadFileUrl: string }>
> = ({ data: { downloadFileUrl } }) => {
    const { roles } = useIdentity();
    const isOwnershipUser = roles?.includes('manage_nr_ownership');
    const useLink = downloadFileUrl && isOwnershipUser;
    return useLink ? (
        <a className="DownloadFileCell" href={downloadFileUrl}>
            <GlyphIcon name="download" size={16} />
            {$t('ownershipRights.delivery.download')}
        </a>
    ) : (
        <TruncatedText text={EMPTY_CHAR} maxWidth={350} />
    );
};

export const DeliveryTypeCell: FC<
    CellProps<{ previousDeliveredOrderCreatedAt: string }>
> = ({ data: { previousDeliveredOrderCreatedAt } }) => {
    const type =
        !previousDeliveredOrderCreatedAt ||
        previousDeliveredOrderCreatedAt === 'Initial'
            ? $t('ownershipRights.delivery.initial')
            : $t('ownershipRights.delivery.update');
    return <TruncatedText text={type} maxWidth={350} />;
};

export const OrderDateCell: FC<CellProps<{ createdAt: GQLDate }>> = ({
    data,
}) => {
    return (
        <div className="DateCell">
            {data.createdAt
                ? formatDate(data.createdAt, ORDER_DATE_TIME_FORMAT)
                : EMPTY_CHAR}
        </div>
    );
};

export const RightsCountryCell: FC<
    CellProps<{
        rightsPerCountry: {
            contract: boolean;
            system: boolean;
            soundRecording: boolean;
        };
        startDate: GQLDate | null;
        endDate: GQLDate | null;
    }>
> = ({ data }) => {
    const { startDate, endDate, rightsPerCountry } = data;
    const { contract, system, soundRecording } = rightsPerCountry;
    const isRuleCurrent = isDateValid(startDate, endDate);
    const hasRights = contract && system && soundRecording && isRuleCurrent;
    const value = hasRights
        ? $t('ownershipRights.rights.titles.yes')
        : $t('ownershipRights.rights.titles.no');
    const optionsForPopover = {
        id: `rights-per-country-${Math.random()}`,
        content: (
            <div className="RightsTable-cell-rights-per-country-popover-content">
                <div className="RightsTable-cell-rights-per-country-popover-content-title">
                    <span>
                        {$t('ownershipRights.rights.titles.rightsByLevel')}
                    </span>
                </div>
                <div className="RightsTable-cell-rights-per-country-popover-wrapper">
                    <div className="RightsTable-cell-rights-per-country-popover-content-label">
                        <span>
                            {$t('ownershipRights.rights.titles.contract')}
                        </span>
                    </div>
                    <div className="RightsTable-cell-rights-per-country-popover-content-value">
                        <span>
                            {contract
                                ? $t('ownershipRights.rights.titles.yes')
                                : $t('ownershipRights.rights.titles.no')}
                        </span>
                    </div>
                </div>
                <div className="RightsTable-cell-rights-per-country-popover-wrapper">
                    <span className="RightsTable-cell-rights-per-country-popover-content-label">
                        {$t('ownershipRights.rights.titles.system')}
                    </span>
                    <span className="RightsTable-cell-rights-per-country-popover-content-value">
                        {system
                            ? $t('ownershipRights.rights.titles.yes')
                            : $t('ownershipRights.rights.titles.no')}
                    </span>
                </div>
                <div className="RightsTable-cell-rights-per-country-popover-wrapper">
                    <span className="RightsTable-cell-rights-per-country-popover-content-label">
                        {$t('ownershipRights.rights.titles.soundRecording')}
                    </span>
                    <span className="RightsTable-cell-rights-per-country-popover-content-value">
                        {soundRecording && isRuleCurrent
                            ? $t('ownershipRights.rights.titles.yes')
                            : $t('ownershipRights.rights.titles.no')}
                    </span>
                </div>
            </div>
        ),
    };
    const RightsPopOver = () => (
        <Pill
            text={value}
            className="RightsTable-cell-rights-per-country-popover"
            popoverOptions={optionsForPopover}
        ></Pill>
    );
    const NoRightsPopOver = () => (
        <Pill
            iconCategory="glyph"
            iconName="warning"
            text={value}
            className="RightsTable-cell-rights-per-country-popover"
            popoverOptions={optionsForPopover}
        ></Pill>
    );

    return (
        <div className="RightsTable-cell-rights-per-country-label">
            {hasRights ? <RightsPopOver /> : <NoRightsPopOver />}
        </div>
    );
};
