import {
  Autocomplete,
  Box,
  Chip,
  Dialog,
  DialogContent,
  DialogTitle,
  FormGroup,
  Grid,
  InputAdornment,
  MenuItem,
  OutlinedInput,
  Skeleton,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableFooter,
  TableHead,
  TablePagination,
  TableRow,
  TextField,
  Typography,
  createFilterOptions,
  debounce,
} from "@mui/material";
import { IconCircleXFilled, IconSearch } from "@tabler/icons-react";
import { useFormik } from "formik";
import { useEffect, useMemo, useState } from "react";
import * as yup from "yup";
import { TruncatedText } from "../../../src/components/common/truncatedText";
import DeleteConfirmation from "../../components/common/deleteConfirmation";
import CustomFormLabel from "../../components/forms/theme-elements/CustomFormLabel";
import CustomTextField from "../../components/forms/theme-elements/CustomTextField";
import { useAlert } from "../../helpers/alert.provider";
import { useSharedData } from "../../hooks/useSharedData";
import ActionMenu from "../../layouts/full/ActionMenu";
import BlankCard from "../../layouts/full/BlankCard";
import ParentCard from "../../layouts/full/ParentCard";
import { TablePaginationActions } from "../../layouts/full/TablePaginationActions";
import {
  useDeleteRestrictedItem,
  useGetReasons,
  useGetRestrictedItemsPaged,
  useSaveRestrictedItem,
} from "../../store/restrictedItem.store";
import { useGetStores } from "../../store/store.store";
import { ColorOptions, Conditions, LABELS_CONFIG } from "../../utils/constants";
import PageContainer from "../containers/PageContainer";
import CustomSelect from "../forms/theme-elements/CustomSelect";
import CustomLoadingButton from "../forms/theme-elements/CustomLoadingButton";

const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
  PaperProps: {
    style: {
      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
      width: 250,
    },
  },
};

const filter = createFilterOptions<string>();

const RestrictedItem = () => {
  const { storeId } = useSharedData();
  const { showSuccess, showError } = useAlert();
  const [showDeleteConfirmation, setShowDeleteConfirmation] = useState<{
    show: boolean;
    item: string;
  }>({ show: false, item: "" });
  const [isModalOpen, setModalOpen] = useState(false);
  const [restrictedItem, setRestrictedItem] = useState<DTO.RestrictedItem | undefined>();
  const { getRestrictedItemsPaged, isLoading, restrictedItems, totalItems } =
    useGetRestrictedItemsPaged();
  const { deleteRestrictedItem, isLoading: isDeleting } = useDeleteRestrictedItem();
  const { reasons, getReasons } = useGetReasons();
  const { saveRestrictedItem, isLoading: isSaving } = useSaveRestrictedItem();
  const { stores, isLoading: isLoadingStores, mutate: getStores } = useGetStores();
  const [searchValue, setSearchValue] = useState<string>("");
  const [pagedRequest, setPagedRequest] = useState<DTO.PagedListRequest>({
    pageNumber: 0,
    pageSize: 10,
    searchText: "",
    sortBy: "-createdOn",
  });

  useEffect(() => {
    if (!isLoadingStores) {
      getStores();
    }
  }, []);

  const fetchRestrictedItems = async () => {
    try {
      getRestrictedItemsPaged({ ...pagedRequest, storeId });
    } catch (error: any) {
      const errorMessage =
        error?.response?.data?.message || LABELS_CONFIG.errors.genericErrorMessage;
      showError(errorMessage);
    }
  };

  const fetchReason = async () => {
    try {
      if (storeId) {
        await getReasons({ storeId });
      }
    } catch (error: any) {
      const errorMessage =
        error?.response?.data?.message || LABELS_CONFIG.errors.genericErrorMessage;
      showError(errorMessage);
    }
  };

  useEffect(() => {
    if (storeId) {
      fetchRestrictedItems();
      fetchReason();
    }
  }, [pagedRequest, storeId]);

  const handleChangePage = (_event: any, newPage: any) => {
    setPagedRequest({ ...pagedRequest, pageNumber: newPage + 1 });
  };

  const handleChangeRowsPerPage = (event: any) => {
    setPagedRequest({
      ...pagedRequest,
      pageSize: event.target.value,
      pageNumber: 1,
    });
  };

  const validationSchema = yup.object({
    name: yup.string().trim().required("Please provide a name."),
    type: yup.string().trim().required("Please specify the type."),
    reason: yup.string().trim().required("Please provide a reason."),
    color: yup.string().trim().required("Please specify a color."),
    condition: yup.array().required("Please mention the condition."),
    notes: yup.string().trim(),
  });

  const initialValues: DTO.RestrictedItem = {
    id: "",
    name: "",
    type: "",
    reason: "",
    color: "",
    condition: [],
    notes: "",
    store: [],
    restrictedStore: [storeId],
  };

  const formik = useFormik({
    initialValues: restrictedItem
      ? {
          ...restrictedItem,
          condition: restrictedItem.condition ? restrictedItem.condition.split(",") : [],
          store: restrictedItem.store ? restrictedItem.store.split(",") : [],
          restrictedStore: [storeId],
        }
      : initialValues,
    validationSchema: validationSchema,
    enableReinitialize: true,
    onSubmit: async (values) => {
      if (storeId) {
        try {
          await saveRestrictedItem(
            {
              data: {
                ...values,
                name: values.name.trim(),
                condition: values.condition.toString(),
                store: values.store.toString(),
                restrictedStore: values.restrictedStore.toString(),
              },
            },
            {
              onSuccess: () => {
                showSuccess(LABELS_CONFIG.success.restrictedItemSaved);
                setRestrictedItem(undefined);
                formik.resetForm({ values: initialValues });
                setModalOpen(false);
                fetchRestrictedItems();
              },
            }
          );
        } catch (error: any) {
          const errorMessage =
            error?.response?.data?.message || LABELS_CONFIG.errors.genericErrorMessage;
          showError(errorMessage);
        }
      }
    },
  });

  const openModal = (itemId: string | null) => {
    if (itemId) {
      const editItem =
        restrictedItems && restrictedItems.find((item) => item.id === itemId);
      setRestrictedItem(editItem);
    } else {
      setRestrictedItem(undefined);
      formik.resetForm({ values: initialValues });
    }
    setModalOpen(true);
  };

  const closeModal = () => {
    setRestrictedItem(undefined);
    formik.resetForm({ values: initialValues });
    setModalOpen(false);
  };

  const deleteRestrictedItemFn = async () => {
    if (showDeleteConfirmation.show) {
      try {
        await deleteRestrictedItem(showDeleteConfirmation.item, {
          onSuccess: () => {
            showSuccess(LABELS_CONFIG.success.restrictedItemDeleted);
            setShowDeleteConfirmation({ show: false, item: "" });
            if (storeId) {
              fetchRestrictedItems();
              fetchReason();
            }
          },
        });
      } catch (error: any) {
        const errorMessage =
          error?.response?.data?.message || LABELS_CONFIG.errors.genericErrorMessage;
        showError(errorMessage);
        setShowDeleteConfirmation({ show: false, item: "" });
      }
    }
  };

  const onInputChange = (e) => {
    setPagedRequest((c) => {
      return { ...c, searchText: e.target.value, pageNumber: 1 };
    });
  };

  const handleSearch = useMemo(() => debounce(onInputChange, 500), [onInputChange]);

  const handleConditionChange = (event) => {
    const {
      target: { value },
    } = event;
    formik.setFieldValue(
      "condition",
      typeof value === "string" ? value.split(",") : value
    );
  };

  const handleStoreChange = (event) => {
    const {
      target: { value },
    } = event;
    formik.setFieldValue("store", typeof value === "string" ? value.split(",") : value);
  };

  const handleRestrictedStoreChange = (event) => {
    const {
      target: { value },
    } = event;
    formik.setFieldValue(
      "restrictedStore",
      typeof value === "string" ? value.split(",") : value
    );
  };

  const getColorLabel = (value) => {
    const foundOption = ColorOptions.find((option) => option.value === value);
    return foundOption ? foundOption.label : "";
  };

  return (
    <PageContainer>
      <ParentCard
        title="Restricted Items"
        action={
          <CustomLoadingButton
            loading={false}
            text="Add"
            variant="contained"
            onClick={() => setModalOpen(true)}
          />
        }
      >
        <>
          <Box textAlign="right" sx={{ mb: 2 }}>
            <Grid container>
              <Grid item xs={6} textAlign="left">
                <CustomTextField
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <IconSearch size="1.1rem" />
                      </InputAdornment>
                    ),
                  }}
                  placeholder="Search restricted item"
                  inputProps={{
                    style: { fontSize: "1rem", fontWeight: "bold" },
                  }}
                  onChange={(e) => {
                    setSearchValue(e.target.value);
                    handleSearch(e);
                  }}
                  value={searchValue}
                  width={250}
                  size="small"
                />
              </Grid>
              <Grid item xs={6}></Grid>
            </Grid>
          </Box>
          {isLoading ? (
            <Skeleton
              variant="rounded"
              animation="wave"
              width="100%"
              height={220}
            ></Skeleton>
          ) : (
            <>
              {!restrictedItems || restrictedItems?.length === 0 ? (
                <Box margin={2}>
                  <Typography align="center" variant="h4">
                    No Restricted Items found.
                  </Typography>
                </Box>
              ) : (
                <BlankCard>
                  <TableContainer component={Box}>
                    <Table
                      aria-label="custom pagination table"
                      sx={{
                        width: "100%",
                        tableLayout: "fixed",
                      }}
                      size="small"
                    >
                      <TableHead>
                        <TableRow>
                          <TableCell style={{ width: "10%" }}>
                            <Typography variant="h6">Name</Typography>
                          </TableCell>
                          <TableCell style={{ width: "7%" }}>
                            <Typography variant="h6">Type</Typography>
                          </TableCell>
                          <TableCell style={{ width: "25%" }}>
                            <Typography variant="h6">Reason</Typography>
                          </TableCell>
                          <TableCell style={{ width: "7%" }}>
                            <Typography variant="h6">Color</Typography>
                          </TableCell>
                          <TableCell style={{ width: "20%" }}>
                            <Typography variant="h6">Condition</Typography>
                          </TableCell>
                          <TableCell style={{ width: "24%" }}>
                            <Typography variant="h6">Notes</Typography>
                          </TableCell>
                          <TableCell align="right" style={{ width: "7%" }}>
                            <Typography variant="h6">Actions</Typography>
                          </TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {restrictedItems &&
                          restrictedItems.map((row) => (
                            <TableRow key={row.id}>
                              <TableCell>
                                <Typography
                                  color="textSecondary"
                                  variant="h6"
                                  fontWeight="400"
                                >
                                  {row.name}
                                </Typography>
                              </TableCell>
                              <TableCell>
                                <Typography
                                  color="textSecondary"
                                  variant="h6"
                                  fontWeight="400"
                                >
                                  {row.type}
                                </Typography>
                              </TableCell>
                              <TableCell>
                                <Typography
                                  color="textSecondary"
                                  variant="h6"
                                  fontWeight="400"
                                >
                                  {row.reason}
                                </Typography>
                              </TableCell>
                              <TableCell>
                                <Typography
                                  color="textSecondary"
                                  variant="h6"
                                  fontWeight="400"
                                >
                                  {getColorLabel(row.color)}
                                </Typography>
                              </TableCell>
                              <TableCell>
                                <Typography
                                  color="textSecondary"
                                  variant="h6"
                                  fontWeight="400"
                                >
                                  {row.condition.split(",").map((value) => {
                                    const selectedOption = Conditions.find(
                                      (option) => option.value === value
                                    );
                                    return (
                                      <Chip
                                        key={value}
                                        label={
                                          selectedOption ? selectedOption.label : value
                                        }
                                        size="small"
                                        sx={{ m: 1 }}
                                      />
                                    );
                                  })}
                                </Typography>
                              </TableCell>
                              <TableCell>
                                <Typography
                                  color="textSecondary"
                                  variant="h6"
                                  fontWeight="400"
                                >
                                  <TruncatedText text={row.notes} maxLength={200} />
                                </Typography>
                              </TableCell>

                              <TableCell align="right">
                                <ActionMenu>
                                  <MenuItem
                                    key="1"
                                    onClick={() => {
                                      openModal(row.id || "");
                                    }}
                                  >
                                    Edit
                                  </MenuItem>
                                  <MenuItem
                                    key="3"
                                    onClick={() =>
                                      setShowDeleteConfirmation({
                                        show: true,
                                        item: row.id || "",
                                      })
                                    }
                                  >
                                    Delete
                                  </MenuItem>
                                </ActionMenu>
                              </TableCell>
                            </TableRow>
                          ))}
                      </TableBody>
                      <TableFooter>
                        <TableRow>
                          <TablePagination
                            rowsPerPageOptions={[5, 10, 25, { label: "All", value: -1 }]}
                            colSpan={7}
                            count={totalItems || 0}
                            rowsPerPage={pagedRequest?.pageSize || 10}
                            page={
                              pagedRequest?.pageNumber ? pagedRequest.pageNumber - 1 : 0
                            }
                            SelectProps={{
                              native: true,
                            }}
                            onPageChange={handleChangePage}
                            onRowsPerPageChange={handleChangeRowsPerPage}
                            ActionsComponent={TablePaginationActions}
                          />
                        </TableRow>
                      </TableFooter>
                    </Table>
                  </TableContainer>
                  <DeleteConfirmation
                    isLoading={isDeleting}
                    open={showDeleteConfirmation.show}
                    onClose={() => {
                      setShowDeleteConfirmation({ show: false, item: "" });
                    }}
                    onConfirm={deleteRestrictedItemFn}
                  />
                </BlankCard>
              )}
              <Dialog
                open={isModalOpen}
                onClose={closeModal}
                fullWidth
                maxWidth="sm"
                disableRestoreFocus
              >
                <DialogTitle>
                  {restrictedItem ? "Edit Restricted Item" : "Add Restricted Item"}
                </DialogTitle>
                <DialogContent>
                  <form onSubmit={formik.handleSubmit}>
                    <Grid container spacing={2}>
                      <Grid item xs={12}>
                        <CustomFormLabel>Item Name / Id</CustomFormLabel>
                        <CustomTextField
                          fullWidth
                          id="name"
                          name="name"
                          value={formik.values.name}
                          onChange={formik.handleChange}
                          error={formik.touched.name && Boolean(formik.errors.name)}
                          helperText={formik.touched.name && formik.errors.name}
                        />
                      </Grid>
                      <Grid item xs={12}>
                        <CustomFormLabel>Type</CustomFormLabel>
                        <CustomSelect
                          id="type"
                          name="type"
                          value={formik.values["type"]}
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          error={formik.touched.type && Boolean(formik.errors.type)}
                          helperText={formik.touched.type && formik.errors.type}
                          style={{ minWidth: "300px" }}
                        >
                          <MenuItem value="ASIN" key="ASIN">
                            ASIN
                          </MenuItem>
                          <MenuItem value="Brand" key="Brand">
                            Brand
                          </MenuItem>
                          <MenuItem value="SKU" key="SKU">
                            SKU
                          </MenuItem>
                          <MenuItem value="Other" key="Other">
                            Other
                          </MenuItem>
                        </CustomSelect>
                      </Grid>
                      <Grid item xs={12}>
                        <CustomFormLabel>Reason</CustomFormLabel>
                        <Autocomplete
                          value={formik.values.reason}
                          onChange={(_event, newValue) => {
                            formik.setFieldValue("reason", newValue);
                          }}
                          filterOptions={(options, params) => {
                            const filtered = filter(options, params);

                            const { inputValue } = params;
                            // Suggest the creation of a new value
                            const isExisting = options.some(
                              (option) => inputValue === option
                            );
                            if (inputValue !== "" && !isExisting) {
                              filtered.push(inputValue);
                            }

                            return filtered;
                          }}
                          selectOnFocus
                          clearOnBlur
                          handleHomeEndKeys
                          id="reason"
                          options={reasons || []}
                          getOptionLabel={(option) => {
                            return option;
                          }}
                          renderOption={(props, option) => <li {...props}>{option}</li>}
                          freeSolo
                          renderInput={(params) => (
                            <TextField
                              {...params}
                              label="Write a reason OR select from list"
                              error={
                                formik.touched.reason && Boolean(formik.errors.reason)
                              }
                              helperText={formik.touched.reason && formik.errors.reason}
                            />
                          )}
                        />
                      </Grid>
                      <Grid item xs={12}>
                        <CustomFormLabel>Color</CustomFormLabel>
                        <CustomSelect
                          id="color"
                          name="color"
                          value={formik.values.color}
                          onChange={formik.handleChange}
                          error={formik.touched.color && Boolean(formik.errors.color)}
                          helperText={formik.touched.color && formik.errors.color}
                          style={{ minWidth: "300px" }}
                        >
                          {ColorOptions.map((option, index) => (
                            <MenuItem key={index} value={option.value}>
                              {option.label}
                            </MenuItem>
                          ))}
                        </CustomSelect>
                      </Grid>
                      <Grid item xs={12}>
                        <CustomFormLabel>Condition</CustomFormLabel>
                        <CustomSelect
                          id="condition"
                          name="condition"
                          multiple
                          fullWidth
                          value={formik.values.condition}
                          onChange={handleConditionChange}
                          input={<OutlinedInput id="condition-chip" label="Chip" />}
                          renderValue={(selected) => (
                            <Box
                              sx={{
                                display: "flex",
                                flexWrap: "wrap",
                                gap: 0.5,
                              }}
                            >
                              {selected.map((value) => {
                                const user = Conditions?.find((d) => d.value === value);
                                return (
                                  <Chip
                                    key={value}
                                    label={user?.label}
                                    onDelete={() =>
                                      formik.setFieldValue(
                                        "condition",
                                        formik.values.condition.filter(
                                          (item) => item !== value
                                        )
                                      )
                                    }
                                    deleteIcon={
                                      <IconCircleXFilled
                                        onMouseDown={(event) => event.stopPropagation()}
                                      />
                                    }
                                  />
                                );
                              })}
                            </Box>
                          )}
                          MenuProps={MenuProps}
                          error={
                            formik.touched.condition && Boolean(formik.errors.condition)
                          }
                          helperText={formik.touched.condition && formik.errors.condition}
                        >
                          {Conditions.map((option) => (
                            <MenuItem key={option.value} value={option.value}>
                              {option.label}
                            </MenuItem>
                          ))}
                        </CustomSelect>
                      </Grid>
                      {!restrictedItem && (
                        <Grid item xs={12}>
                          <CustomFormLabel>Restricted on stores</CustomFormLabel>
                          <CustomSelect
                            id="restrictedStore"
                            name="restrictedStore"
                            multiple
                            fullWidth
                            value={formik.values.restrictedStore}
                            onChange={handleRestrictedStoreChange}
                            input={<OutlinedInput id="store-chip" label="Chip" />}
                            renderValue={(selected) => (
                              <Box
                                sx={{
                                  display: "flex",
                                  flexWrap: "wrap",
                                  gap: 0.5,
                                }}
                              >
                                {selected.map((value) => {
                                  const st = stores?.find((d) => d.id === value);
                                  if (st?.storeName) {
                                    return (
                                      <Chip
                                        key={value}
                                        label={st?.storeName}
                                        onDelete={() =>
                                          formik.setFieldValue(
                                            "restrictedStore",
                                            formik.values.restrictedStore.filter(
                                              (item) => item !== value
                                            )
                                          )
                                        }
                                        deleteIcon={
                                          <IconCircleXFilled
                                            onMouseDown={(event) =>
                                              event.stopPropagation()
                                            }
                                          />
                                        }
                                      />
                                    );
                                  }
                                })}
                              </Box>
                            )}
                            MenuProps={MenuProps}
                            error={
                              formik.touched.restrictedStore &&
                              Boolean(formik.errors.restrictedStore)
                            }
                            helperText={
                              formik.touched.restrictedStore &&
                              formik.errors.restrictedStore
                            }
                          >
                            {stores &&
                              stores.map((option) => (
                                <MenuItem key={option.id} value={option.id}>
                                  {option.storeName}
                                </MenuItem>
                              ))}
                          </CustomSelect>
                        </Grid>
                      )}
                      <Grid item xs={12}>
                        <CustomFormLabel>Sellable on stores</CustomFormLabel>
                        <CustomSelect
                          id="store"
                          name="store"
                          multiple
                          fullWidth
                          value={formik.values.store}
                          onChange={handleStoreChange}
                          input={<OutlinedInput id="store-chip" label="Chip" />}
                          renderValue={(selected) => (
                            <Box
                              sx={{
                                display: "flex",
                                flexWrap: "wrap",
                                gap: 0.5,
                              }}
                            >
                              {selected.map((value) => {
                                const st = stores?.find((d) => d.id === value);
                                if (st?.storeName) {
                                  return (
                                    <Chip
                                      key={value}
                                      label={st?.storeName}
                                      onDelete={() =>
                                        formik.setFieldValue(
                                          "store",
                                          formik.values.store.filter(
                                            (item) => item !== value
                                          )
                                        )
                                      }
                                      deleteIcon={
                                        <IconCircleXFilled
                                          onMouseDown={(event) => event.stopPropagation()}
                                        />
                                      }
                                    />
                                  );
                                }
                              })}
                            </Box>
                          )}
                          MenuProps={MenuProps}
                          error={formik.touched.store && Boolean(formik.errors.store)}
                          helperText={formik.touched.store && formik.errors.store}
                        >
                          {stores &&
                            stores.map((option) => {
                              const isRestricted =
                                option.id === storeId ||
                                (formik.values.restrictedStore &&
                                  formik.values.restrictedStore.includes(option.id));

                              return (
                                !isRestricted && (
                                  <MenuItem key={option.id} value={option.id}>
                                    {option.storeName}
                                  </MenuItem>
                                )
                              );
                            })}
                        </CustomSelect>
                      </Grid>
                      <Grid item xs={12}>
                        <CustomFormLabel>Notes</CustomFormLabel>
                        <CustomTextField
                          fullWidth
                          multiline
                          row={3}
                          id="notes"
                          name="notes"
                          value={formik.values.notes}
                          onChange={formik.handleChange}
                          error={formik.touched.notes && Boolean(formik.errors.notes)}
                          helperText={formik.touched.notes && formik.errors.notes}
                        />
                      </Grid>
                    </Grid>

                    <Stack spacing={2} direction="row" style={{ marginTop: "16px" }}>
                      <FormGroup>
                        <CustomLoadingButton
                          loading={isSaving}
                          text={isSaving ? "Saving" : "Save"}
                          variant="contained"
                          type="submit"
                        />
                      </FormGroup>
                      <CustomLoadingButton
                        loading={false}
                        text="Cancel"
                        onClick={() => {
                          setRestrictedItem(undefined);
                          formik.resetForm({ values: initialValues });
                          setModalOpen(false);
                        }}
                      />
                    </Stack>
                  </form>
                </DialogContent>
              </Dialog>
            </>
          )}
        </>
      </ParentCard>
    </PageContainer>
  );
};

export default RestrictedItem;

Make below changes 
- Make it page for Stock Transfers
- Table fields 
	Created
	From Warehouse
	To Warehouse
	Booked Out
	Booked In
	Status
Create/Edit functionality use  InventoryStockTransfer component and add support for edit