import React from 'react';
import cx from 'classnames';
import { upperFirst } from '../../utils';
import { CDN_MANIFEST, CdnAsset } from '../cdnAsset';
import type { CdnAssetProps, Manifest, VariantType } from '../cdnAsset';

export type CompanyIcons = Manifest['brands'];

/**
 * @deprecated Use `CompanyIcons` instead. `BrandIcons` will be removed in the next major version.
 */
export type BrandIcons = CompanyIcons;

type SizeNumber<S> = S extends '16' ? 16 : S extends '24' ? 24 : S extends '48' ? 48 : never;

export interface CompanyIconProps<
    Name extends keyof CompanyIcons,
    Size extends keyof CompanyIcons[Name],
    Variant extends VariantType<CompanyIcons[Name][Size]>,
> extends Omit<CdnAssetProps<'brands', Name, Size, Variant>, 'category' | 'size' | 'name'> {
    size?: Size | SizeNumber<Size>;
    name?: Name | string;
    /**
     * @deprecated Use `name` instead. `brand` will be removed in the next major version.
     */
    brand?: Name | string;
}

/**
 * @deprecated Use `CompanyIconProps` instead. `BrandIconProps` will be removed in the next major version.
 */
export type BrandIconProps<
    Name extends keyof CompanyIcons,
    Size extends keyof CompanyIcons[Name],
    Variant extends VariantType<CompanyIcons[Name][Size]>,
> = CompanyIconProps<Name, Size, Variant>;

export const COMPANY_ICONS_BY_SIZE = Object.entries(CDN_MANIFEST.brands).reduce(
    (stores, [store, sizes]) => ({
        ...stores,
        [store]: Object.keys(sizes)
            .map((size) => parseInt(size, 10))
            .filter((size) => !isNaN(size)),
    }),
    {} as Record<string, number[]>
);

/**
 * @deprecated Use `COMPANY_ICONS_BY_SIZE` instead. `BRAND_ICONS_BY_SIZE` will be removed in the next major version.
 */
export const BRAND_ICONS_BY_SIZE = COMPANY_ICONS_BY_SIZE;

/**
 * Company icons are company logos, formerly referred to as brand icons. They are provided by the business units we support.
 *
 * @type atom
 * @status live
 * @tags visuals
 */
export function CompanyIcon<
    Name extends keyof CompanyIcons,
    Size extends keyof CompanyIcons[Name],
    Variant extends VariantType<CompanyIcons[Name][Size]>,
>({ size, name, brand, testId, className, ...rest }: CompanyIconProps<Name, Size, Variant>) {
    const company = name ?? brand;
    if (!company || !CDN_MANIFEST.brands[company as Name]) return null;

    const iconClass = upperFirst(`${company}BrandIcon`);

    return (
        <CdnAsset
            {...rest}
            name={company as Name}
            className={cx('BrandIcon', iconClass, className)}
            testId={testId ?? iconClass}
            size={size as Size}
            category="brands"
        />
    );
}
