import {
  Alert,
  Autocomplete,
  Box,
  Button,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  FormControlLabel,
  Grid,
  IconButton,
  MenuItem,
  Paper,
  Radio,
  RadioGroup,
  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, useGetStockTransfer } from "../../store/inventory.store";
import { useGetWarehouse } from "../../store/warehouse.store";
import { TRANSFER_STATUS_OPTIONS } from "../../utils/constants";
import { TruncatedText } from "../common/truncatedText";
import CustomFormLabel from "../forms/theme-elements/CustomFormLabel";
import CustomLoadingButton from "../forms/theme-elements/CustomLoadingButton";
import CustomSelect from "../forms/theme-elements/CustomSelect";
interface InventoryStockTransferProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
  productId?: string;
  showCancelledOption?: boolean;
}

const InventoryStockTransfer: React.FC<InventoryStockTransferProps> = ({ open, onClose, productId, onSuccess, showCancelledOption }) => {
  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("0");
  const [fromWarehouseId, setFromWarehouseId] = useState<string>();
  const [toWarehouseId, setToWarehouseId] = useState<string>();
  const [notes, setNotes] = useState("");
  const { getOrgProducts, isLoading } = useGetOrgProducts();
  const { getWarehouse, warehouses, isLoading: isLoadingWarehouse } = useGetWarehouse();
  const { getStockTransfer, stockTransfer, isLoading: isLoadingDetails } = useGetStockTransfer();
  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,
      notes,
      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={12}>
            <FormControl fullWidth>
              <CustomFormLabel>
                Status
              </CustomFormLabel>
              <RadioGroup
                row
                value={status}
                onChange={(e) => setStatus(e.target.value)}
              >
                {Object.entries(TRANSFER_STATUS_OPTIONS).map(([key, value]) => (
                  (showCancelledOption || key !== 'CANCELLED') ? (
                    <FormControlLabel
                      key={key}
                      control={<Radio />}
                      label={value}
                      value={key}
                    />
                  ) : null
                ))}
              </RadioGroup>
            </FormControl>
          </Grid>

          <Grid item xs={12}>
            <FormControl fullWidth>
              <CustomFormLabel>
                Notes
              </CustomFormLabel>
              <TextField
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                fullWidth
                multiline
                rows={1}
                placeholder="Optional notes..."
              />
            </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>
        <CustomLoadingButton
          loading={isSaving}
          text="Save"
          variant="contained"
          sx={{ ml: 2 }}
          onClick={handleTransfer}
        />
        <Button onClick={onClose} disabled={isSaving}>Cancel</Button>
      </DialogActions>
    </Dialog>
  );
};

export default InventoryStockTransfer;

Update above code to add param like stockTransferId and if it is not empty open modal in edit mode and get stock Transfer details using getStockTransfer and show loader untill content is loaded 

once loaded select the details accordingly like fromWarehouseId, towarehouseId status etc

if status is draft allow user to add more products and warehouses else do not allow any changes except the status.

if status is completed status then show it in read only form 

DTO for references

  export interface StockTransferItemsDetail {
    inventoryId: string;
    quantity: number;
  }

  export interface StockTransfer {
    inventoryTransferId: string;
    status: string;
    fromWarehouseName: string;
    fromWarehouseId: string;
    toWarehouseName: string;
    toWarehouseId: string;
    createdOn: Date;
    bookedOutTime?: Date;
    bookedInTime?: Date;
    transferItems: StockTransferItemsDetail[];
  }

export const TRANSFER_STATUS_OPTIONS = {
  0: "Draft",
  1: "Ready to Send",
  2: "In Transit",
  3: "Ready to Receive",
  4: "Completed",
  5: "Cancelled",
};