import React, {useEffect} from 'react';
import './app.css';
import {ChakraProvider, defaultSystem, Stack} from "@chakra-ui/react";

import {AppHeader} from "./appHeader";
import {OrderList} from "../orderlist/orderList";
import {useAppStore} from "../appstore";
import {api} from "../api";
import {parseCSVOrTSV} from "../utils/parsing";
import {toast, updateToast} from "../components/ui/toaster";
import {Toaster} from "../components/ui/toasterComponent";
import {NotificationsArea} from "./notificationsArea";
import {SubmitOrderButton} from "./submitOrderButton";

export function App({root}: { root: HTMLElement }) {

  useEffect(() => {
    const handlePaste = async (e: ClipboardEvent) => {
      if (
        e.target instanceof HTMLInputElement ||
        e.target instanceof HTMLTextAreaElement ||
        (e.target as HTMLElement)?.isContentEditable
      ) {
        return; // let user paste inside inputs
      }

      const {parseMode, addAllToOrderList, setUnresolvedSkus} = useAppStore.getState();

      const pasted = e.clipboardData?.getData("text") ?? "";
      if (!pasted.trim()) {
        toast({
          type: "warning",
          title: "Nothing to paste",
          description: "Clipboard is empty",
        });
        return;
      }

      const parsedSkuQtyPairs = parseCSVOrTSV(pasted.trim(), parseMode);

      if (parsedSkuQtyPairs.length === 0) {
        toast({type: "error", title: "Could not parse SKUs and quantities", description: "See example in paste area tooltip"});
        return;
      }

      const resolveToastId = toast({
        title: "Resolving SKUs...",
        type: "loading",
      });

      try {
        const parsedSkus = parsedSkuQtyPairs.map(p => p.sku);
        const b2BQOMItems = await api.resolveSkus(parsedSkus);
        const resolvedItems = b2BQOMItems.map(item => ({
          ...item,
          quantity: parsedSkuQtyPairs.find(i => i.sku === item.sku)?.qty as number,
        }));

        if (resolvedItems.length === 0) {
          updateToast(resolveToastId, {type: "warning", title: `None of the SKUs were resolved`});
          return;
        }

        // const unresolvedSkus = skuQtyMap.keys().filter(key => orderListItems.)
        if (resolvedItems.length === parsedSkuQtyPairs.length) {
          setUnresolvedSkus([]);
          updateToast(resolveToastId, {
            type: "success",
            title: `All ${resolvedItems.length} SKU(s) resolved successfully`
          });
        } else {
          const resolvedSkus = new Set(resolvedItems.map(i => i.sku));
          const unresolvedSkus = parsedSkus.filter(key => !resolvedSkus.has(key));
          setUnresolvedSkus(unresolvedSkus);
          updateToast(resolveToastId, {
            type: "warning",
            title: "Some SKUs could not be resolved",
            description: `${resolvedSkus.size} resolved, ${unresolvedSkus.length} not found`,
          });
        }
        addAllToOrderList(resolvedItems);
      } catch (err) {
        console.error(err);
        updateToast(resolveToastId, {
          type: "error",
          title: "Failed to resolve SKUs",
          description: err instanceof Error ? err.message : "Please try again"
        });
      }
    };

    root.addEventListener("paste", handlePaste);
    return () => root.removeEventListener("paste", handlePaste);
  }, []);

  return (
    <ChakraProvider value={defaultSystem}>
      <Stack direction='column' style={{gap: '2rem', margin: '2rem', height: '90vh', minWidth: '900px'}}>
        <AppHeader/>
        <OrderList/>
        <NotificationsArea/>
        <SubmitOrderButton/>
      </Stack>
      <Toaster/>
    </ChakraProvider>
  );
}
