import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react'
import {
    Table, Thead, Th, Tbody, Tr, Td,
    Heading,
    Text,
    Stack,
    Skeleton,
    Box,
    Tag,
    VisuallyHidden
} from '@chakra-ui/react'
import { Link } from 'react-router-dom'
import moment from 'moment'

import { Order } from 'Order';
import { useOrders } from 'hooks';
import { OrderDatePicker, OrderSearchBar, OrderStatusMenu, tagColorMap } from './index'

const OrderRow = ({ 
    order: {
        id,
        orderTrackingCode,
        orderStatus, 
        orderCreatedAt, orderUpdatedAt, 
        customerEmailAddress, 
        orderItems
    } 
}: { order: Order }) => {
    return (
        <Tr>
            <Td fontSize="sm" fontWeight="semibold"><Link to={`/orders/${id}`}>{id}</Link></Td>
            <Td><Tag colorScheme={tagColorMap.get(orderStatus)}>{orderStatus}</Tag></Td>
            <Td fontSize="sm" paddingX={10}>{orderItems.length} item{orderItems.length > 1 && "s"}</Td>
            <Td fontSize="sm">{customerEmailAddress}</Td>
            <Td fontSize="small">{moment(orderUpdatedAt).calendar()}</Td>
            <Td fontSize="small">{moment(orderCreatedAt).calendar()}</Td>
            <Td fontSize="smaller">{orderTrackingCode}</Td>
        </Tr> 
    )
}

const OrdersPage = () => {
    const { 
        status, 
        orders, 
        error,
        ResStatus,
        pagFilters, setPagFilters,
        dateFilters, setDateFilters,
        searchFilters, setSearchFilters,
        statusFilters, setStatusFilters
    } = useOrders()

    const tableHeaders = ['Order #', 'Status', 'Item Count', 'Customer email', 'Updated at', 'Created at', 'Tracking #']

    const isLoading = useMemo(() => status === ResStatus.FETCHING, [status])

    const $loader = useRef<any>();

    // const handleObserver = (entities: any) => {
    //     const target = entities[0];
    //     if (target.isIntersecting && !isLoading) {   
    //         setPagFilters((prev: any) => ({...prev, page: prev.page + 1}))
    //     }
    // }

    // useEffect(() => {
    //      var options = {
    //         root: null,
    //         rootMargin: "20px",
    //         threshold: 1.0
    //      };
    //     // initialize IntersectionObserver
    //     // and attaching to Load More div
    //      const observer = new IntersectionObserver(handleObserver, options);
    //      if ($loader.current) {
    //         observer.observe($loader.current)
    //      }
    // }, []);

    return (
        <div>
            <div>
                <Heading>Orders</Heading>
                <Stack p={2} isInline>
                    <OrderSearchBar 
                        searchFilters={searchFilters} 
                        setSearchFilters={setSearchFilters}
                        status={status}
                        STATUSES={ResStatus}
                    />
                    <OrderDatePicker 
                        dateFilters={dateFilters} 
                        setDateFilters={setDateFilters}
                    />
                    <OrderStatusMenu 
                        statusFilters={statusFilters} 
                        setStatusFilters={setStatusFilters} 
                    />
                </Stack>
            </div>
            <div>
                <Table variant="striped">
                    <Thead>
                        <Tr>
                            {tableHeaders.map((headerText, idx) => (
                                <Th key={idx}>
                                    <Text>{headerText}</Text>
                                </Th>
                            ))}
                        </Tr>
                    </Thead>
                    <Tbody >
                        {orders.map(order => <OrderRow 
                            key={order.id} 
                            order={order}
                        />)}
                    </Tbody>
                    <span ref={$loader}></span>
                </Table>
            </div>
        </div>
        
    )
}

export default OrdersPage