import type { FC } from 'react';
import React, { useState, useMemo } from 'react';
import {
    GridTable,
    InfoMessage,
    Section,
    TagCloud,
} from '@theorchard/suite-components';
import { GlyphIcon } from '@theorchard/suite-icons';
import { values } from 'lodash';
import { useDeliveryRestrictionsContext } from 'src/components/deliveryRestrictionsContext/useDeliveryRestrictionsContext';
import { EMPTY_CHAR } from 'src/constants';
import type { GridTableCellProps } from '@theorchard/suite-components';
import type { CountryxServiceGroup } from 'src/types';

export interface Props {
    items: Record<string, CountryxServiceGroup>;
    loading: boolean;
    onEditServiceCountry: (restriction: CountryxServiceGroup) => void;
    onRemoveServiceCountry: (restriction: CountryxServiceGroup) => void;
    onBulkRemove: (selection: string[]) => void;
}

export const CLASS_NAME = 'countryServiceTable';
export const INTL_PREFIX = 'contentReview.countryServiceTable';

const CountryServiceTable: FC<Props> = ({
    items,
    loading,
    onEditServiceCountry,
    onRemoveServiceCountry,
    onBulkRemove,
}) => {
    const { stores: contextStores, territories: contextTerritories } =
        useDeliveryRestrictionsContext();

    const [selectedRows, setSelectedRows] = useState<string[]>([]);

    const tableData = useMemo(() => values(items), [items]);

    const ServicesCell = ({
        data: { stores },
    }: GridTableCellProps<CountryxServiceGroup>) => {
        if (!stores || stores.length === 0) {
            return <></>;
        }

        return (
            <div className={`${CLASS_NAME}-cell-services`}>
                <TagCloud
                    className={`${CLASS_NAME}-cell-services-tag-cloud`}
                    maxVisibleCount={5}
                    disableRemove
                    items={contextStores
                        .filter(contextStore =>
                            stores.includes(contextStore.id)
                        )
                        .map(store => ({
                            label: store.name,
                            value: store.id,
                        }))}
                />
            </div>
        );
    };
    const CountriesCell = ({
        data: { countries },
    }: GridTableCellProps<CountryxServiceGroup>) => {
        if (!countries || countries.length === 0) {
            return <></>;
        }

        return (
            <div className={`${CLASS_NAME}-cell-countries`}>
                <TagCloud
                    className={`${CLASS_NAME}-cell-countries-tag-cloud`}
                    maxVisibleCount={5}
                    items={contextTerritories
                        .filter(contextTerritory =>
                            countries.includes(contextTerritory.territoryCodeA2)
                        )
                        .map(countries => ({
                            label: countries.territoryName,
                            value: countries.territoryCodeA2,
                            flag: countries.territoryCodeA2,
                        }))}
                />
            </div>
        );
    };

    return (
        <Section.Table
            variant="edit"
            testId={CLASS_NAME}
            className={CLASS_NAME}
        >
            <GridTable
                data={tableData}
                loading={loading}
                className="delivery-table"
                bordered
                rowKey="id"
                variant="zebra"
                stickyHeader
                paginationText={$t(`${INTL_PREFIX}.items`, {
                    count: tableData?.length || EMPTY_CHAR,
                })}
                maxHeight={460}
                columnDefs={[
                    {
                        name: 'services',
                        title: $t(`${INTL_PREFIX}.services`),
                        Cell: ServicesCell,
                    },
                    {
                        name: 'countries',
                        title: $t(`${INTL_PREFIX}.countries`),
                        Cell: CountriesCell,
                    },
                ]}
                selectable
                selectedRowKeys={selectedRows}
                onSelectedRowsChanged={setSelectedRows}
                rowActionsHeader={''}
                emptyStateComponent={
                    <div className="delivery-table-empty-state">
                        <InfoMessage
                            message={$t(
                                `${INTL_PREFIX}.serviceXCountryEmptyStateTitle`
                            )}
                            body={$t(
                                `${INTL_PREFIX}.serviceXCountryEmptyStateSubtitle`
                            )}
                            size="sm"
                        />
                    </div>
                }
                rowActions={{
                    edit: onEditServiceCountry,
                    delete: {
                        icon: <GlyphIcon name="trash" size={16} />,
                        onClick: onRemoveServiceCountry,
                    },
                }}
                rowBulkActions={{
                    delete: {
                        icon: <GlyphIcon name="trash" size={16} />,
                        onClick: () => onBulkRemove(selectedRows),
                    },
                }}
            />
        </Section.Table>
    );
};

export default CountryServiceTable;
