import React, {useEffect, useMemo, useRef} from 'react';
import {Box, CloseButton, Input, Stack, Table} from "@chakra-ui/react";
import {useAppStore} from "../appstore";
import {B2BQOMOrderListItem} from "../types/b2bqom";
import {Tooltip} from "../components/tooltip";
import {LuInfo, LuTriangleAlert} from "react-icons/lu";
import {PasteZone} from "./pasteZone";

type OrderListProps = {}


function countListItemTotal(listItem: B2BQOMOrderListItem) {
  return (listItem.price * listItem.quantity).toFixed(2);
}

export function OrderList({}: OrderListProps) {
  const {
    orderList,
    updateInOrderList,
    removeFromOrderList,
    clearOrderList
  } = useAppStore();

  const listRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const el = listRef.current;
    if (!el) return;

    const handleCopy = (e: ClipboardEvent) => {
      if (!orderList.length) return;

      e.preventDefault();

      const tsv = orderList.map(item => `${item.sku}\t${item.quantity}`).join("\n");
      e.clipboardData?.setData("text/plain", tsv);
    };

    el.addEventListener("copy", handleCopy);
    return () => {
      el.removeEventListener("copy", handleCopy);
    };
  }, [orderList]);

  const subTotalAmount = useMemo(() => {
    const total = orderList.reduce((sum, oli) => sum + oli.quantity * oli.price, 0) || 0;
    return total.toFixed(2);
  }, [orderList]);

  const orderListEmpty = orderList.length === 0;

  return (
    <Stack direction="column" display="flex" justifyContent="center" alignContent="center"
           style={{maxHeight: "70vh", overflowY: "auto"}}>
      {
        orderListEmpty
          ? <PasteZone/>
          :
          <Box
            ref={listRef}
            tabIndex={0}
            style={{outline: 'none', overflowY: 'auto', scrollPaddingTop: '40px'}}
          >
            <Table.Root size="sm" tableLayout="fixed" width="100%">
              <Table.Header style={{position: "sticky", top: 0, background: "white", zIndex: 1}}>
                <Table.Row>
                  <Table.ColumnHeader w="50px" fontWeight="bold">#</Table.ColumnHeader>
                  <Table.ColumnHeader w="150px" fontWeight="bold">SKU</Table.ColumnHeader>
                  <Table.ColumnHeader fontWeight="bold">Product</Table.ColumnHeader>
                  <Table.ColumnHeader w="80px" fontWeight="bold">In stock</Table.ColumnHeader>
                  <Table.ColumnHeader w="100px" fontWeight="bold">Price</Table.ColumnHeader>
                  <Table.ColumnHeader w="100px" fontWeight="bold">Quantity</Table.ColumnHeader>
                  <Table.ColumnHeader w="100px" fontWeight="bold" textAlign="end">Item Total</Table.ColumnHeader>
                  <Table.ColumnHeader w="100px" textAlign="center">
                    <CloseButton size="sm" onClick={() => clearOrderList()}/>
                  </Table.ColumnHeader>
                </Table.Row>
              </Table.Header>
              <Table.Body>
                {orderList.map((item, index) => {
                  return (
                    <Table.Row key={item.sku} data-sku={item.sku}>
                      <Table.Cell color="gray.500">{index + 1}</Table.Cell>
                      <Table.Cell>
                        <Tooltip content={`${item.sku}`} hasArrow>
                          <Box maxW="150px" whiteSpace="nowrap" overflow="hidden" textOverflow="ellipsis">
                            {item.sku}
                          </Box>
                        </Tooltip>
                      </Table.Cell>
                      <Table.Cell>
                        <Tooltip content={`${item.name}`} hasArrow>
                          <Box whiteSpace="nowrap" overflow="hidden" textOverflow="ellipsis">
                            {item.name}
                          </Box>
                        </Tooltip>
                      </Table.Cell>
                      <Table.Cell>
                        <Stack direction="row" align="center" gap={1}>
                          <Box>{item.stock_quantity ?? 0}</Box>
                          {item.stock_quantity != null && item.quantity > item.stock_quantity && (
                            <Tooltip content={`Requested ${item.quantity} but only ${item.stock_quantity} in stock`} hasArrow>
                              <Box color="orange.500" display="flex" alignItems="center">
                                <LuTriangleAlert />
                              </Box>
                            </Tooltip>
                          )}
                        </Stack>
                      </Table.Cell>
                      <Table.Cell>{item.price}</Table.Cell>
                      <Table.Cell>
                        <Stack direction="row">
                          <Input
                            key={`${item.sku}-${item.quantity}`}
                            width="150px"
                            type="number"
                            min={0}
                            step={1}
                            defaultValue={item.quantity}
                            borderColor={item.stock_quantity != null && item.quantity > item.stock_quantity ? "orange.400" : undefined}
                            bg={item.stock_quantity != null && item.quantity > item.stock_quantity ? "orange.50" : undefined}
                            _hover={{
                              borderColor: item.stock_quantity != null && item.quantity > item.stock_quantity ? "orange.500" : undefined
                            }}
                            onBlur={(e) => {
                              let value = Number.parseInt(e.target.value)
                              if (isNaN(value) || value < 0) {
                                value = 0;
                              }

                              e.target.value = `${Math.trunc(value)}`;
                              updateInOrderList({
                                ...item,
                                quantity: Math.trunc(value),
                              })
                            }}
                          />
                        </Stack>
                      </Table.Cell>
                      <Table.Cell textAlign="end">{countListItemTotal(item) || 0}</Table.Cell>
                      <Table.Cell textAlign="center">
                        <CloseButton size="sm" onClick={() => {
                          removeFromOrderList(item.id);
                        }}/>
                      </Table.Cell>
                    </Table.Row>
                  );
                })}
                <Table.Row
                  style={{
                    position: "sticky",
                    bottom: 0,
                    background: "white",
                    zIndex: 1,
                  }}
                >
                  <Table.Cell></Table.Cell>
                  <Table.Cell></Table.Cell>
                  <Table.Cell></Table.Cell>
                  <Table.Cell></Table.Cell>
                  <Table.Cell></Table.Cell>
                  <Table.Cell>
                    <Tooltip content="This does not include taxes, promos, discounts, delivery etc.">
                      <Stack direction="row" align="center">
                        <LuInfo cursor="pointer"/>
                        <Box>Subtotal:</Box>
                      </Stack>
                    </Tooltip>
                  </Table.Cell>
                  <Table.Cell textAlign="right" fontWeight="semibold">{subTotalAmount}</Table.Cell>
                  <Table.Cell>&nbsp;</Table.Cell>
                </Table.Row>
              </Table.Body>
            </Table.Root>
          </Box>
      }
    </Stack>
  );
}