import React, { useEffect, useState } from 'react';
import { formatMessage } from '@orchard/frontend-localization';
import { map } from 'lodash';
import { Table } from '@orchard/frontend-react-components';
import { renderConfigurationIcon } from 'src/utils/configuration-icon';
import Segment from 'src/utils/segment';
import { formatProductName } from 'src/utils/formatters';
import { Collaborator } from 'src/pages/collaborator-page/queries/collaborator';
import usePagination from 'src/hooks/pagination';
import {
    SEGMENT_CATEGORIES,
    SEGMENT_EVENTS
} from '../../constants';
import CellLoader from '../loaders/table-cell-loader';
import messages from './i18n';
import { getViewProductUrl } from '../../urls/collaborator';
import { useCollaboratorWithProductsLazyQuery, Product } from './queries/collaborator-with-products';

const CLASS_NAME = 'ProductsList';

type Props = {
    collaborator?: Collaborator | null;
    isLoading: boolean;
    productsPerPage?: number;
};

const ProductsList : React.FC<Props> = ({ collaborator, isLoading, productsPerPage = 20 }) => {
    const collaboratorId = collaborator?.id;

    // Pagination
    const [totalProducts, setTotalProducts] = useState(0);
    const [products, setProducts] = useState<Product[]>([]);

    const [fetchData, { loading, data, fetchMore }] = useCollaboratorWithProductsLazyQuery();

    const fetchMoreWrapper = ({ variables }: { variables: { offset: number, limit: number } }) => {
        if (collaboratorId)
            fetchMore!({ variables: { collaboratorId, ...variables } });
    };

    const { renderPagination } = usePagination({
        fetchMore: fetchMoreWrapper,
        totalItemCount: totalProducts,
        itemsPerPage: productsPerPage,
    });

    useEffect(() => {
        if (collaboratorId)
            fetchData({
                variables: { collaboratorId, offset: 0, limit: productsPerPage }
            });
    }, [fetchData, collaboratorId, productsPerPage]);

    useEffect(() => {
        if (data) {
            const collabProducts = data.collaborator?.products;
            setProducts(collabProducts?.products || []);
            setTotalProducts(collabProducts?.totalProducts || 0);
        }
    }, [data]);

    const handleProductClick = () => Segment.trackEvent(
        SEGMENT_EVENTS.COLLAB_PRODUCT_CLICK,
        SEGMENT_CATEGORIES.COLLAB_PRODUCTS
    );

    const renderTableBody = () => {
        if (isLoading || loading) {
            const displayableProducts = Array(productsPerPage).fill({
                product: {
                    productId: null,
                    productName: null,
                    productConfiguration: null,
                    upc: null
                },
            });

            return map(displayableProducts, (_, index) => (
                <tr key={ index }>
                    <td><CellLoader /></td>
                    <td><CellLoader /></td>
                    <td><CellLoader /></td>
                </tr>
            ));
        }

        return products.length > 0 ? map(products, (product) => (
            <tr key={ product.productId }>
                <td>
                    <a
                        href={ getViewProductUrl(product.productId) }
                        onClick={ handleProductClick }
                        data-testid={ `product-link-${product.productId}` }
                    >
                        { formatProductName(product?.productName || '', product.deliveredVersion) }
                    </a>
                </td>
                <td>
                    { renderConfigurationIcon(
                        product.productConfiguration
                    ) }
                    { product.productConfiguration }
                </td>
                <td>{ product.displayUpc }</td>
            </tr>
        )) : (
            <tr>
                <td colSpan={ 5 } className={ `${CLASS_NAME}-empty-message` }>
                    { formatMessage(messages.noCollaboratorProducts) }
                </td>
            </tr>
        );
    };

    return (
        <div>
            <Table>
                <thead>
                    <tr>
                        <th>{ formatMessage(messages.product) }</th>
                        <th>{ formatMessage(messages.productType) }</th>
                        <th>{ formatMessage(messages.upc) }</th>
                    </tr>
                </thead>
                <tbody>
                    { renderTableBody() }
                </tbody>
            </Table>
            { renderPagination() }
        </div>
    );
};

export default ProductsList;
