import React, {useMemo, useState} from "react";
import {useAppStore} from "../appstore";
import {Box, Button, Stack, Collapsible} from "@chakra-ui/react";
import {toast} from "../components/ui/toaster";
import {PrimaryButton} from "../components/primaryButton";
import {LuChevronDown, LuChevronUp, LuTriangleAlert} from "react-icons/lu";

export function NotificationsArea() {
  const {
    unresolvedSkus,
    setUnresolvedSkus,
    orderList,
    capQuantitiesToStock,
  } = useAppStore();

  const [lowStockDismissed, setLowStockDismissed] = useState(false);
  const [isExpanded, setIsExpanded] = useState(true);

  const lowStockItems = useMemo(() => {
    return orderList.filter(item =>
      item.stock_quantity != null && item.quantity > item.stock_quantity
    );
  }, [orderList]);

  const hasUnresolvedSkus = unresolvedSkus.length > 0;
  const hasLowStock = lowStockItems.length > 0 && !lowStockDismissed;

  const notificationCount = [hasLowStock, hasUnresolvedSkus].filter(Boolean).length;

  if (notificationCount === 0) {
    return null;
  }

  return (
    <Box mt={1} fontSize="14px">
      <Button
        onClick={() => setIsExpanded(!isExpanded)}
        variant="ghost"
        size="sm"
        mb={1}
        colorScheme="orange"
      >
        <Box as={LuTriangleAlert} color="orange.500" mr={2}/>
        {notificationCount} notification{notificationCount > 1 ? 's' : ''}
        {isExpanded ? <LuChevronUp style={{marginLeft: '8px'}}/> : <LuChevronDown style={{marginLeft: '8px'}}/>}
      </Button>

      <Collapsible.Root open={isExpanded}>
        {/* @ts-expect-error chakra dialog typing issue */}
        <Collapsible.Content>
          <Stack direction="column" gap={1.5}>
            {hasUnresolvedSkus && (
              <Box
                borderWidth="1px"
                borderRadius="md"
                borderColor="red.300"
                bg="red.50"
                p={3}
              >
                <Stack direction="row" justify="space-between" align="center" mb={2}>
                  <Box fontWeight="bold" color="red.600">
                    {unresolvedSkus.length} SKU(s) could not be resolved
                  </Box>
                  <Button
                    size="sm"
                    variant="ghost"
                    colorScheme="red"
                    onClick={() => setUnresolvedSkus([])}
                  >
                    Dismiss
                  </Button>
                </Stack>
                <Box maxHeight="100px" overflowY="auto">
                  <Stack direction="row" colorScheme="red" alignContent="center" flexWrap="wrap">
                    {unresolvedSkus.slice(0, 10).map((sku, i) => (
                      <Box key={i}>
                        {sku}
                      </Box>
                    ))}
                    {unresolvedSkus.length > 10 && (
                      <Box fontSize="sm" color="red.500">
                        …and {unresolvedSkus.length - 10} more
                      </Box>
                    )}
                  </Stack>
                </Box>
              </Box>
            )}

            {hasLowStock && (
              <Box
                borderWidth="1px"
                borderRadius="md"
                borderColor="orange.300"
                bg="orange.50"
                p={3}
              >
                <Stack direction="row" justify="space-between" align="center" mb={2}>
                  <Box>
                    <Box fontWeight="bold" color="orange.700">
                      Low stock warning
                    </Box>
                    <Box color="orange.800">
                      {lowStockItems.length} item{lowStockItems.length > 1 ? 's' : ''} exceed{lowStockItems.length === 1 ? 's' : ''} available
                      stock
                    </Box>
                  </Box>
                  <Stack direction="row" gap={2}>
                    <PrimaryButton
                      size="sm"
                      variant="solid"
                      onClick={() => {
                        const adjustedCount = capQuantitiesToStock();
                        toast({
                          type: "success",
                          title: "Quantities adjusted",
                          description: `${adjustedCount} item${adjustedCount > 1 ? 's' : ''} set to available stock`,
                        });
                      }}
                    >
                      Set all to available
                    </PrimaryButton>
                    <Button
                      size="sm"
                      variant="ghost"
                      colorScheme="orange"
                      onClick={() => setLowStockDismissed(true)}
                    >
                      Dismiss
                    </Button>
                  </Stack>
                </Stack>
                <Box maxHeight="100px" overflowY="auto">
                  <Stack direction="row" flexWrap="wrap" gap={2}>
                    {lowStockItems.slice(0, 10).map((item, i) => (
                      <Box
                        key={i}
                        fontSize="sm"
                        color="orange.700"
                        cursor="pointer"
                        textDecoration="underline"
                        _hover={{color: "orange.900", fontWeight: "semibold"}}
                        onClick={() => {
                          const row = document.querySelector(`[data-sku="${item.sku}"]`) as HTMLElement;
                          if (row) {
                            row.scrollIntoView({behavior: "smooth", block: "center"});

                            // Add highlight animation
                            row.style.animation = "none";
                            setTimeout(() => {
                              row.style.animation = "highlight 1.5s ease-out";
                            }, 10);

                            // Remove animation after it completes
                            setTimeout(() => {
                              row.style.animation = "";
                            }, 1600);
                          }
                        }}
                      >
                        {item.sku} (need {item.quantity}, have {item.stock_quantity})
                      </Box>
                    ))}
                    {lowStockItems.length > 10 && (
                      <Box fontSize="sm" color="orange.700">
                        …and {lowStockItems.length - 10} more
                      </Box>
                    )}
                  </Stack>
                </Box>
              </Box>
            )}
          </Stack>
        </Collapsible.Content>
      </Collapsible.Root>
    </Box>
  );
}