Allow user to remove the product if removed show the search product auto complete only if product is not added 

import {
  Alert,
  Autocomplete,
  Box,
  Button,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  FormControlLabel,
  Grid,
  InputAdornment,
  MenuItem,
  Paper,
  Radio,
  RadioGroup,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography
} from "@mui/material";
import Image from "next/image";
import { useCallback, useEffect, useState } from "react";
import { useAddAdjustment, useGetOrgProducts } from "../../store/inventory.store";
import { useGetWarehouse } from "../../store/warehouse.store";
import { REASON_OPTIONS } from "../../utils/constants";
import { TruncatedText } from "../common/truncatedText";
import CustomFormLabel from "../forms/theme-elements/CustomFormLabel";
import CustomSelect from "../forms/theme-elements/CustomSelect";
import CustomTextField from "../forms/theme-elements/CustomTextField";

interface InventoryStockAdjustmentProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
  productId?: string;
}

const InventoryStockAdjustment: React.FC<InventoryStockAdjustmentProps> = ({ open, onClose, productId, onSuccess }) => {
  const [selectedProduct, setSelectedProduct] = useState<DTO.ProductDetail | null>(null);
  const [searchValue, setSearchValue] = useState("");
  const [searchResults, setSearchResults] = useState<DTO.ProductDetail[]>([]);
  const [productError, setProductError] = useState<string>();
  const [warehouseId, setWarehouseId] = useState<string>();
  const [reason, setReason] = useState<number>();
  const [quantity, setQuantity] = useState<number>(1);
  const [adjustmentType, setAdjustmentType] = useState<string>("add");
  const { getOrgProducts, isLoading } = useGetOrgProducts();
  const { getWarehouse, warehouses, isLoading: isLoadingWarehouse } = useGetWarehouse();
  const { addAdjustment, isLoading: isSaving } = useAddAdjustment();

  useEffect(() => {
    getWarehouse();
  }, []);

  const debounce = (func, delay) => {
    let timer;
    return (...args) => {
      clearTimeout(timer);
      timer = setTimeout(() => func(...args), delay);
    };
  };

  const fetchProducts = useCallback(
    debounce(async (query) => {
      if (query.trim()) {
        await getOrgProducts({ searchText: query }, {
          onSuccess: (response) => {
            setSearchResults(response.data.data);
          },
        });
      }
    }, 500),
    []
  );

  const handleSearchInputChange = (event, newInputValue) => {
    if (event?.type === 'change') {
      setSearchValue(newInputValue);
      setSearchResults([]);
      fetchProducts(newInputValue);
    }
  };

  const handleAdjustment = () => {
    if (!warehouseId) {
      setProductError("Please choose a warehouse to continue");
      return;
    }

    if (!selectedProduct) {
      setProductError("Please add a product");
      return;
    }

    if (!reason) {
      setProductError("Please select a reason");
      return;
    }

    addAdjustment({
      warehouseId,
      reasonCode: reason as number,
      productId: selectedProduct.id,
      quantity: adjustmentType === "remove" ? -Math.abs(quantity) : quantity,
      inventoryId: ''
    }, {
      onSuccess: () => {
        onSuccess();
      }
    });
  };

  const handleAddProduct = (product) => {
    setSelectedProduct(product);
    setSearchValue("");
    setProductError("");
  };

  return (
    <Dialog open={open} onClose={onClose} disableRestoreFocus maxWidth="lg">
      <DialogTitle>Stock Adjustment</DialogTitle>
      <DialogContent sx={{ width: "800px" }}>
        <Grid container spacing={2}>
          <Grid item xs={12}>
            <FormControl fullWidth>
              <CustomFormLabel>Warehouse</CustomFormLabel>
              <CustomSelect
                value={warehouseId}
                fullWidth
                onChange={(event) => {
                  setWarehouseId(event.target.value);
                }}
              >
                {warehouses?.map((warehouse) => (
                  <MenuItem key={warehouse.warehouseId} value={warehouse.warehouseId}>
                    {warehouse.name}
                  </MenuItem>
                ))}
              </CustomSelect>
            </FormControl>
          </Grid>

          <Grid item xs={4}>
            <FormControl fullWidth>
              <CustomFormLabel>Reason</CustomFormLabel>
              <CustomTextField
                select
                label="Reason"
                fullWidth
                value={reason}
                onChange={(e) => setReason(e.target.value)}
              >
                {Object.entries(REASON_OPTIONS).map(([key, value]) => (
                  <MenuItem key={key} value={key}>
                    {value}
                  </MenuItem>
                ))}
              </CustomTextField>
            </FormControl>
          </Grid>

          <Grid item xs={4}>
            <FormControl fullWidth>
              <CustomFormLabel>Adjustment Type</CustomFormLabel>
              <RadioGroup
                value={adjustmentType}
                onChange={(e) => setAdjustmentType(e.target.value)}
                row
              >
                <FormControlLabel value="add" control={<Radio />} label="Add" />
                <FormControlLabel value="remove" control={<Radio />} label="Remove" />
              </RadioGroup>
            </FormControl>
          </Grid>

          <Grid item xs={4}>
            <FormControl fullWidth>
              <CustomFormLabel>Quantity</CustomFormLabel>
              <TextField
                type="number"
                value={quantity}
                onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value, 10) || 1))}
                inputProps={{ min: 1 }}
                fullWidth
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start" sx={{ color: adjustmentType === 'add' ? 'green' : 'red' }}>
                      {adjustmentType === 'add' ? '+' : '-'}
                    </InputAdornment>
                  ),
                }}
                sx={{
                  '& .MuiOutlinedInput-root': {
                    '&.Mui-focused fieldset': {
                      borderColor: adjustmentType === 'add' ? 'green' : 'red',
                    },
                  },
                }}
              />
              <Typography variant="body2" sx={{ color: adjustmentType === 'add' ? 'green' : 'red' }}>
                {adjustmentType === 'add' ? 'Adding' : 'Removing'} Quantity
              </Typography>
            </FormControl>
          </Grid>
        </Grid>

        {!productId && (
          <FormControl fullWidth>
            <CustomFormLabel>Search Products</CustomFormLabel>
            <Autocomplete
              options={searchResults}
              getOptionLabel={(option) => {
                if (typeof option === 'string') return option;
                return option.name || "";
              }}
              value={null}
              onChange={(event, newValue) => handleAddProduct(newValue)}
              inputValue={searchValue}
              onInputChange={handleSearchInputChange}
              renderOption={(props, option) => (
                <li {...props}>
                  <Box display="flex" alignItems="center">
                    {option.imageUrl && (
                      <Image
                        src={option.imageUrl}
                        alt={option.name}
                        height={50}
                        width={50}
                      />
                    )}
                    <Box ml={1}>
                      <TruncatedText text={option.name} maxLength={80} disableTooltip />
                      <Typography variant="body1">
                        <strong>SKU</strong>: {option.sku}
                      </Typography>
                    </Box>
                  </Box>
                </li>
              )}
              renderInput={(params) => (
                <TextField
                  {...params}
                  fullWidth
                  placeholder="Search products..."
                  InputProps={{
                    ...params.InputProps,
                    endAdornment: (
                      <>
                        {isLoading ? <CircularProgress color="inherit" size={20} /> : null}
                        {params.InputProps.endAdornment}
                      </>
                    ),
                  }}
                />
              )}
              isOptionEqualToValue={(option, value) => option.id === value?.id}
              filterOptions={(x) => x}
              freeSolo
            />
          </FormControl>
        )}

        {selectedProduct && (
          <TableContainer component={Paper} sx={{ marginTop: 2 }}>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>Product</TableCell>
                  <TableCell>Store Name</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>

                <TableRow key={selectedProduct.id}>
                  <TableCell>
                    <Box display="flex" alignItems="center">
                      {selectedProduct.imageUrl && (
                        <Image
                          src={selectedProduct.imageUrl}
                          alt={selectedProduct.name}
                          height={50}
                          width={50}
                        />
                      )}
                      <Grid container spacing={1} ml={1}>
                        <Grid item xs={12}>
                          <TruncatedText text={selectedProduct.name} maxLength={50} />
                        </Grid>
                        <Grid item xs={12}>
                          <Typography variant="body1">
                            <strong>SKU</strong>: {selectedProduct.sku}
                          </Typography>
                        </Grid>
                      </Grid>
                    </Box>
                  </TableCell>
                  <TableCell>{selectedProduct.storeName}</TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </TableContainer>
        )}

        {productError && (
          <Alert variant="outlined" severity="error" sx={{ mt: 2 }}>
            {productError}
          </Alert>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleAdjustment} disabled={isSaving} variant="contained" color="primary">
          Adjust
        </Button>
        <Button onClick={onClose} disabled={isSaving}>Cancel</Button>
      </DialogActions>
    </Dialog>
  );
};

export default InventoryStockAdjustment;