import type { FC } from 'react';
import React, { useCallback, useState } from 'react';
import { Page } from '@theorchard/suite-frontend';
import { useGetPhysicalOrdersQuery } from 'src/data/queries';
import {
    ensureSortByType,
    ensureDeliveryType,
} from 'src/pages/monitorPage/utils';
import { ensureSortDirectionType } from 'src/utils';
import { recordPhysicalOrdersSortingByKey } from 'src/utils/segment';
import Filters from '../components/filters';
import {
    DEFAULT_SORT_DIR_MONITOR_PAGE,
    DEFAULT_SORT_FIELD_MONITOR_PAGE,
    PAGE_SIZE,
} from '../constants';
import OrdersTable from './ordersTable';
import type { MonitorRouteParams } from '../types';
import type { SortBy, SortDirection } from 'src/types';
import type { SetParamsCallback, ParamValue } from 'src/utils';

export const CLASSNAME = 'Orders';

interface Props {
    params: MonitorRouteParams;
    handleParams: SetParamsCallback;
}

const Orders: FC<Props> = ({ params, handleParams }) => {
    const [page, setPage] = useState(0);
    const [pageSize, setPageSize] = useState(PAGE_SIZE);
    const { selectedOrder, selectedStore, deliveryType, orderBy, orderDir } =
        params;
    const { data, loading, error } = useGetPhysicalOrdersQuery({
        limit: pageSize,
        orderBy: ensureSortByType(orderBy),
        orderDir: ensureSortDirectionType(orderDir),
        storeIds: selectedStore ? [selectedStore] : null,
        deliveryTypes: ensureDeliveryType(deliveryType),
        orderIds: selectedOrder ? [selectedOrder] : null,
        offset: page * pageSize,
    });

    // Not including selectedStore as applied filter for now bc we only show Above Board currently
    const filtersApplied = !!(selectedOrder || deliveryType);
    const sortingApplied =
        orderDir !== DEFAULT_SORT_FIELD_MONITOR_PAGE ||
        orderBy !== DEFAULT_SORT_DIR_MONITOR_PAGE;

    const handleSort = (sortBy: SortBy[]) => {
        recordPhysicalOrdersSortingByKey(sortBy[0].key, sortBy[0].direction);
        handleParams({ orderBy: sortBy[0].key, orderDir: sortBy[0].direction });
    };

    const handleClearFilters = useCallback(() => {
        setPage(0);
        handleParams({
            orderId: undefined,
            // store: undefined, commented out for now as we have the store filter permanently set to show Above Board only
            deliveryType: undefined,
            tab: 'physical',
        });
    }, [handleParams]);

    const handleFiltersChange = useCallback(
        (filters: string | Record<string, ParamValue | undefined>) => {
            // reset pagination when filters change
            setPage(0);
            handleParams(filters);
        },
        [handleParams]
    );

    return (
        <div className={CLASSNAME}>
            <Page.View error={error} loading={loading} hasData={!!data}>
                <Filters setParams={handleFiltersChange} params={params} />
                <OrdersTable
                    orders={data?.orders ?? []}
                    totalOrders={data?.totalCount}
                    loading={loading && (filtersApplied || sortingApplied)}
                    onClearFilters={handleClearFilters}
                    filtersApplied={filtersApplied}
                    onSort={handleSort}
                    sortBy={{
                        key: orderBy,
                        direction: orderDir as SortDirection,
                    }}
                    page={page}
                    pageSize={pageSize}
                    handlePageChange={setPage}
                    handlePageSizeChange={setPageSize}
                />
            </Page.View>
        </div>
    );
};

export default Orders;
