import { ContractTermException } from 'src/types/contract-term';
import React from 'react';

const formatExceptionText = (exception: ContractTermException): string => {
    const { country, service, labelShare } = exception;

    const isAllServices = service.length === 1 && service[0] === 'All';
    const isAllCountries = country.length === 1 && country[0] === 'All';

    const displayedServices = !isAllServices
        ? service.slice(0, 3).join(', ')
        : '';
    const additionalServicesCount =
        !isAllServices && service.length > 3
            ? ` + ${service.length - 3} additional services`
            : '';

    const displayedCountries = !isAllCountries
        ? country.slice(0, 3).join(', ')
        : '';
    const additionalCountriesCount =
        !isAllCountries && country.length > 3
            ? ` + ${country.length - 3} additional countries`
            : '';

    let exceptionText = `Except ${labelShare}% Label’s Share`;

    if (displayedServices && displayedCountries) {
        exceptionText += ` for ${displayedServices}${additionalServicesCount} in ${displayedCountries}${additionalCountriesCount}`;
    } else if (displayedServices) {
        exceptionText += ` for ${displayedServices}${additionalServicesCount}`;
    } else if (displayedCountries) {
        exceptionText += ` in ${displayedCountries}${additionalCountriesCount}`;
    }

    return exceptionText;
};

export const RenderExceptions: React.FC<{
    exceptions: ContractTermException[];
    showExceptions: boolean;
}> = ({ exceptions, showExceptions }) => {
    if (!showExceptions || exceptions.length === 0) return null;

    const filteredExceptions = exceptions.filter(
        exception =>
            !(
                exception.country.length === 1 &&
                exception.country[0] === 'All' &&
                exception.service.length === 1 &&
                exception.service[0] === 'All'
            )
    );

    if (filteredExceptions.length === 0) return null;

    return (
        <div
            className="d-flex flex-column suite-text-medium"
            style={{ color: 'var(--text-label)', gap: '4px' }}
            data-testid="ContractTermDetailsExceptions"
        >
            {filteredExceptions.map((exception, index) => (
                <div key={index}>{formatExceptionText(exception)}</div>
            ))}
        </div>
    );
};
