import {
  Alert,
  Autocomplete,
  Box,
  Button,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  Grid,
  IconButton,
  MenuItem,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography
} from "@mui/material";
import { IconTrash } from "@tabler/icons-react";
import Image from "next/image";
import { useCallback, useEffect, useState } from "react";
import { useAddTransfer, useGetOrgProducts } from "../../store/inventory.store";
import { useGetWarehouse } from "../../store/warehouse.store";
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";

const STATUS_OPTIONS = {
  PENDING: "Pending",
  IN_TRANSIT: "InTransit",
  COMPLETED: "Completed",
  CANCELLED: "Cancelled",
};

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

const InventoryStockTransfer: React.FC<InventoryStockTransferProps> = ({ open, onClose, productId, onSuccess }) => {
  const [selectedProducts, setSelectedProducts] = useState<DTO.ProductDetail[]>([]);
  const [searchValue, setSearchValue] = useState("");
  const [searchResults, setSearchResults] = useState<DTO.ProductDetail[]>([]);
  const [productError, setProductError] = useState<string>();
  const [status, setStatus] = useState("");
  const [fromWarehouseId, setFromWarehouseId] = useState<string>();
  const [toWarehouseId, setToWarehouseId] = useState<string>();
  const { getOrgProducts, isLoading } = useGetOrgProducts();
  const { getWarehouse, warehouses, isLoading: isLoadingWarehouse } = useGetWarehouse();
  const { addTransfer, isLoading: isSaving } = useAddTransfer();

  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 handleTransfer = () => {
    if (!fromWarehouseId || !toWarehouseId) {
      setProductError("Please choose warehouses to continue");
      return;
    }

    if (fromWarehouseId === toWarehouseId) {
      setProductError("From and To warehouse cannot be the same");
      return;
    }

    if (selectedProducts.length < 1) {
      setProductError("Please add at least one product");
      return;
    }

    addTransfer({
      fromWarehouseId,
      toWarehouseId,
      status,
      items: selectedProducts.map((product) => ({
        productId: product.id,
        qty: product.minQuantity || 1
      }))
    }, {
      onSuccess: () => {
        onSuccess();
      }
    });
  };


  const handleAddProduct = (product) => {
    const isExisting = selectedProducts.some((p) => p.id === product.id);
    if (!isExisting) {
      setSelectedProducts([...selectedProducts, { ...product, minQuantity: 1 }]);
    }
    setSearchValue("");
    setProductError("");
  };

  const handleRemoveProduct = (id) => {
    setSelectedProducts(selectedProducts.filter((p) => p.id !== id));
  };

  const handleQuantityChange = (id, value) => {
    setSelectedProducts(
      selectedProducts.map((p) => (p.id === id ? { ...p, minQuantity: parseInt(value, 10) || 1 } : p))
    );
  };

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

          <Grid item xs={12} sm={6}>
            <FormControl fullWidth>
              <CustomFormLabel>
                To Warehouse
              </CustomFormLabel>
              <CustomSelect
                fullWidth
                value={toWarehouseId}
                onChange={(event) => {
                  setToWarehouseId(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>
                Status
              </CustomFormLabel>
              <CustomTextField
                select
                label="Status"
                fullWidth
                value={status}
                onChange={(e) => setStatus(e.target.value)}
              >
                {Object.entries(STATUS_OPTIONS).map(([key, value]) => (
                  <MenuItem key={key} value={key}>
                    {value}
                  </MenuItem>
                ))}
              </CustomTextField>
            </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}
                      />
                    )}
                    <Grid container spacing={1} ml={1}>
                      <Grid item xs={12}>
                        <TruncatedText text={option.name} maxLength={80} disableTooltip />
                      </Grid>
                      <Grid item xs={6}>
                        <Typography variant="body1">
                          <strong>SKU</strong>: {option.sku}
                        </Typography>
                      </Grid>
                      <Grid item xs={6}>
                        <Typography variant="body1">
                          <strong>Store</strong>: {option.storeName}
                        </Typography>
                      </Grid>
                    </Grid>
                  </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>
        )}

        {selectedProducts.length === 0 && (
          <Typography variant="h5" align="center" sx={{ mt: 2 }}>
            No products added.
          </Typography>
        )}

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

        {selectedProducts.length > 0 && (
          <TableContainer component={Paper} sx={{ marginTop: 2 }}>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>Product</TableCell>
                  <TableCell>Store Name</TableCell>
                  <TableCell>Min Quantity</TableCell>
                  <TableCell>Action</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {selectedProducts.map((product) => (
                  <TableRow key={product.id}>
                    <TableCell>
                      <Box display="flex" alignItems="center">
                        {product.imageUrl && (
                          <Image
                            src={product.imageUrl}
                            alt={product.name}
                            height={50}
                            width={50}
                          />
                        )}
                        <Grid container spacing={1} ml={1}>
                          <Grid item xs={12}>
                            <TruncatedText text={product.name} maxLength={50} />
                          </Grid>
                          <Grid item xs={12}>
                            <Typography variant="body1">
                              <strong>SKU</strong>: {product.sku}
                            </Typography>
                          </Grid>
                        </Grid>
                      </Box>
                    </TableCell>
                    <TableCell>{product.storeName}</TableCell>
                    <TableCell>
                      <TextField
                        type="number"
                        value={product.minQuantity}
                        onChange={(e) => handleQuantityChange(product.id, e.target.value)}
                        inputProps={{ min: 1 }}
                      />
                    </TableCell>
                    <TableCell>
                      <IconButton
                        color="error"
                        onClick={() => handleRemoveProduct(product.id)}
                      >
                        <IconTrash />
                      </IconButton>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        )}
      </DialogContent>
      <DialogActions>

        <Button onClick={handleTransfer} disabled={isSaving} variant="contained" color="primary">
          Transfer
        </Button>
        <Button onClick={onClose} disabled={isSaving}>Cancel</Button>
      </DialogActions>
    </Dialog>
  );
};

export default InventoryStockTransfer;

update above code to make below changes

Update Stock Transfer to Stock Adjustment
Remove FromWarehouse
Rename ToWarehouse to Warehouse
Remove Status
Add Quantity as numeric text box allow only positive and default value as 1
Add Reson select option and make constant of key value pair for options like RETURN_CUSTOMER, DAMAGED, INTERNAL_TRANSFER_OUT, INTERNAL_TRANSFER_IN, ORDER_FULFILLMENT, ORDER_CANCELLATION, EXPIRED, LOST, STOCK_REFILL, STOCK_ADJUSTMENT, MISC_ADJUSTMENT, SAMPLE, TESTING, FBA_SHIPMENT