import {
  Alert,
  Autocomplete,
  Box,
  Button,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  Grid,
  IconButton,
  MenuItem,
  TextField,
  Typography
} from "@mui/material";
import { IconTrash } from "@tabler/icons-react";
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 { 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;
    }

    addAdjustment({
      warehouseId,
      reasonCode: reason as number,
      productId: selectedProduct.id,
      quantity: quantity || 1,
      inventoryId: ''
    }, {
      onSuccess: () => {
        onSuccess();
      }
    });
  };

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

  const handleRemoveProduct = () => {
    setSelectedProduct(null);
  };

  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>
                Quantity
              </CustomFormLabel>
              <TextField
                type="number"
                value={quantity}
                onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value, 10) || 1))}
                inputProps={{ min: 1 }}
                fullWidth
              />
            </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>
        )}

        {productError && (
          <Alert variant="outlined" severity="error" sx={{ mt: 2 }}>
            {productError}
          </Alert>
        )}

        {selectedProduct && (
          <Box display="flex" alignItems="center" sx={{ marginTop: 2 }}>
            {selectedProduct.imageUrl && (
              <Image
                src={selectedProduct.imageUrl}
                alt={selectedProduct.name}
                height={50}
                width={50}
              />
            )}
            <Box ml={1}>
              <Typography variant="body1"><strong>Selected Product:</strong></Typography>
              <TruncatedText text={selectedProduct.name} maxLength={50} />
              <Typography variant="body2"><strong>SKU:</strong> {selectedProduct.sku}</Typography>
              <IconButton color="error" onClick={handleRemoveProduct}>
                <IconTrash />
              </IconButton>
            </Box>
          </Box>
        )}
      </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;

Update above code to make below changes
- add option like "Add" / "Remove" using radio button group 
- if Add option selected show Quantity prefix in green + else red -