import type { FC } from 'react';
import React, { useCallback } from 'react';
import { formatDate, Segment } from '@theorchard/suite-frontend';
import { Decimal } from 'decimal.js';
import { Link } from 'react-router-dom';
import { SONG_DATE_FORMAT } from 'src/constants';
import SongWritersList from 'src/pages/songListPage/components/songWritersList';
import { getSum } from 'src/utils/helpers';
import { songUrl } from 'src/utils/urls';
import type { Composition } from 'src/data/queries/compositions/types';
import type { CellProps } from 'src/pages/songListPage/types';

export const TitleCell: FC<CellProps<Composition>> = ({ data }) => {
    const onClickSong = useCallback(() => {
        void Segment.trackEvent('Click - Edit Song', { category: 'Songs' });
    }, []);

    return (
        <Link to={songUrl(data.id)} onClick={onClickSong}>
            {data.title}
        </Link>
    );
};

export const SongWritersCall: FC<CellProps<Composition>> = ({ data }) => (
    <SongWritersList agreements={data.agreements} />
);

export const AssociatedSoundRecordingCell: FC<CellProps<Composition>> = ({
    data,
}) => (
    <div>
        {data.associatedGlobalSoundRecordings.length +
            data.associatedLabelSoundRecordings.length ===
        0 ? (
            <div className="none">{$t('common.none')}</div>
        ) : (
            data.associatedGlobalSoundRecordings.length +
            data.associatedLabelSoundRecordings.length
        )}
    </div>
);

export const OwnershipCell: FC<CellProps<Composition>> = ({ data }) => {
    const ownership = getSum(
        data.agreements.map(agreement => new Decimal(agreement.split || 0))
    ).toString();

    if (ownership === '0')
        return <div className="none">{$t('common.noOwnership')}</div>;
    return (
        <div className="ownership">{`${ownership}% ${$t(
            'common.ownership'
        )}`}</div>
    );
};

export const DateCell: FC<CellProps<Composition>> = ({ data }) => (
    <div>
        {formatDate(
            data.draft
                ? data.modifiedAt || data.createdAt
                : data.submittedAt ?? '',
            SONG_DATE_FORMAT
        )}
    </div>
);
