import React, { useMemo, useState } from "react";
import {
  Box,
  Button,
  Card,
  Dialog,
  Grid,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import SaveAltIcon from "@mui/icons-material/SaveAlt";
import CloseIcon from "@mui/icons-material/Close";
import { useNotifier } from "../../../Core/Notifier";
import {
  useCreateCategoryMutation,
  useGetAllCategoryNameQuery,
  useGetAllMainCategoryQuery,
  useGetCategoryQuery,
  useGetSubCategoryByArrayQuery,
} from "../../../Api/attoDeskApi";
import { ICategory, ISubCategory } from "../../../Api/Interface/api.interface";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import CustomSwitch from "../../../Components/Switch/CustomSwitch";
import { useStyles } from "../../../theme/styles";
import { uploadImage } from "../../../Components/UploadFile/upload";
import ChangeCircleIcon from "@mui/icons-material/ChangeCircle";
import AlertPopUp from "../../../Components/AlertPopUp/AlertPopup";

interface IProductCategoryPopUp {
  openModel?: boolean;
  handleCloseDialog: (close: boolean) => void;
  data?: ISubCategory;
}

const ProductCategory = ({
  openModel = false,
  handleCloseDialog,
  data,
}: IProductCategoryPopUp) => {
  const classes = useStyles();
  const [open] = React.useState(openModel);
  const [showCategorySelection, setShowCategorySelection] = useState(false);
  const [newProductCategory, { isLoading }] = useCreateCategoryMutation();
  const { showErrorMessage, showMessage } = useNotifier();
  const { data: categoryData } = useGetAllMainCategoryQuery({
    departmentId: "",
    coursingId: "",
    roleId: null,
    taxeId: "",
    createdDateStart: null,
    createdDateEnd: null,
    searchText: "",
    numberOfLength: 0,
    isActive: true,
    categoryIsLooping: null,
    createdDate: null
  });
  const [deleteAlert, setDeleteAlert] = useState(false);
  const [alertMessage, setAlertMessage] = useState("");

  const { data: allCategoryData, isLoading: allCategoryLoading } =
    useGetAllCategoryNameQuery();
  const [selectedImage, setSelectedImage] = React.useState<File | undefined>(
    undefined
  );
  const [isImageUploading, setIsImageUploading] = React.useState(false);

  const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(
    null
  );
  const [selectedSubCategoryId, setSelectedSubCategoryId] = useState<
    number | null
  >(null);

  const [selectedSubToSubCategoryId, setSelectedSubToSubCategoryId] = useState<
    number | null
  >(null);

  const { data: subCategoryData, refetch: refetchSubCategories } =
    useGetSubCategoryByArrayQuery({
      parent_ids: selectedCategoryId ? [Number(selectedCategoryId)] : [],
    });

  const { data: subCategory2Data, refetch: refetchS2bCategories } =
    useGetSubCategoryByArrayQuery({
      parent_ids: selectedSubCategoryId
        ? [Number(selectedCategoryId), Number(selectedSubCategoryId)]
        : [],
    });

  const allCategoryList = useMemo(() => {
    return allCategoryData?.data as ICategory[];
  }, [allCategoryData?.data]);

  const allCategoryMap = useMemo(() => {
    const map = new Map();
    allCategoryList?.forEach((printer) => {
      map.set(printer.id, printer.categoryName);
    });
    return map;
  }, [allCategoryList]);

  const categoryList = useMemo(() => {
    return categoryData?.data as ICategory[];
  }, [categoryData?.data]);

  const subCategoryList = useMemo(() => {
    return subCategoryData?.data as ICategory[];
  }, [subCategoryData?.data]);

  const subToSubCategoryList = useMemo(() => {
    return subCategory2Data?.data as ICategory[];
  }, [subCategory2Data?.data]);

  const handleClose = () => {
    handleCloseDialog(false);
  };
  const formik = useFormik({
    initialValues: {
      id: data?.id,
      categoryName: data?.categoryName || "",
      subCatDescription: data?.subCatDescription || "",
      parent_ids: data?.parent_ids || [],
      subCatImg: data?.subCatImg || null,
      mainCatId: data?.mainCatId || null,
      isActive: data?.isActive,
      subIsMain: data?.subIsMain,
      categoryIsLooping: data?.categoryIsLooping,
      categoryLoopingConstant: data?.categoryLoopingConstant,
    },
    onSubmit: async (values) => {
      try {
        const formData = new FormData();
        let subCatImg: string | undefined = data?.subCatImg;

        if (selectedImage) {
          setIsImageUploading(true);
          formData.append("subCatImg", selectedImage);
          subCatImg = (await uploadImage(selectedImage)) || "";
          setIsImageUploading(false);
        }

        let parent_ids;

        if (showCategorySelection) {
          if (selectedSubToSubCategoryId) {
            parent_ids = [
              Number(selectedCategoryId),
              Number(selectedSubCategoryId),
              Number(selectedSubToSubCategoryId),
            ];
          } else if (selectedSubCategoryId) {
            parent_ids = [
              Number(selectedCategoryId),
              Number(selectedSubCategoryId),
            ];
          } else if (selectedCategoryId) {
            parent_ids = [Number(selectedCategoryId)];
          } else {
            parent_ids = [Number(values.mainCatId)];
          }
        } else {
          parent_ids = formik.values.parent_ids;
        }

        const temData = {
          id: values.id,
          categoryName: values.categoryName,
          // mainCatId: Number(values.mainCatId),
          parent_ids: parent_ids,
          subCatDescription: values.subCatDescription,
          subCatImg,
          isActive: values.isActive,
          subIsMain: values.subIsMain,
          categoryIsLooping: values.categoryIsLooping,
          categoryLoopingConstant: values.categoryLoopingConstant,
        };
        if (!data) {
          delete temData.id;
        }

        const addCompanyResponse = await newProductCategory(temData).unwrap();
        if (!addCompanyResponse.status) {
          setAlertMessage(addCompanyResponse.message);
          setDeleteAlert(true);
        } else {
          showMessage(addCompanyResponse.message);
          handleClose();
        }
      } catch (error) {
        showErrorMessage("Something went wrong");
      }
    },
  });

  const formValid = useMemo(() => {
    return formik.values.categoryName !== "";
  }, [formik]);

  const handleMainCategoryChange = (
    event: React.ChangeEvent<{ value: unknown }>
  ) => {
    const categoryId = event.target.value as number;
    setSelectedCategoryId(categoryId);
    setSelectedSubCategoryId(null);
    setSelectedSubToSubCategoryId(null);
    formik.setFieldValue("mainCatId", categoryId);

    const selectedCategory = categoryList.find(
      (category) => category.id == categoryId
    );

    if (selectedCategory) {
      // Update Formik values for categoryIsLooping and categoryLoopingConstant
      formik.setFieldValue(
        "categoryIsLooping",
        selectedCategory.categoryIsLooping
      );
      formik.setFieldValue(
        "categoryLoopingConstant",
        selectedCategory.categoryLoopingConstant
      );
    }
  };

  const handleSubCategoryChange = (
    event: React.ChangeEvent<{ value: unknown }>
  ) => {
    const subCategoryId = event.target.value as number;
    setSelectedSubCategoryId(subCategoryId);
    setSelectedSubToSubCategoryId(null);
  };

  const handleSubToSubCategoryChange = (
    event: React.ChangeEvent<{ value: unknown }>
  ) => {
    const selectedSubToSubCategoryId = event.target.value as number;
    setSelectedSubToSubCategoryId(selectedSubToSubCategoryId);
  };

  const handleImageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;

    if (files && files.length > 0) {
      const file = files[0];
      const validTypes = ["image/jpeg", "image/png", "image/jpg", "image/gif"];
      const maxSize = 2048 * 1024;

      if (!validTypes.includes(file.type)) {
        showErrorMessage("The file must be an image (jpeg, png, jpg, gif).");
        setSelectedImage(undefined);
      } else if (file.size > maxSize) {
        showErrorMessage("The file must be smaller than 2 MB.");
        setSelectedImage(undefined);
      } else {
        setSelectedImage(file);
        showErrorMessage("");
      }
    } else {
      setSelectedImage(undefined);
      showErrorMessage("");
    }
  };

  const handleShowCategorySelection = () => {
    setShowCategorySelection(true);
  };

  return (
    <Box>
      <form onSubmit={formik.handleSubmit}>
        <Dialog open={open}>
          <Grid container>
            <Grid
              item
              lg={12}
              md={12}
              sm={12}
              xs={12}
              className={classes.grid1}
            >
              <Card
                sx={{
                  p: 2,
                  maxWidth: 900,
                  boxShadow: "none",
                  pb: 2,
                }}
              >
                <Grid container justifyContent="space-between">
                  <Grid
                    item
                    lg={12}
                    md={12}
                    sm={12}
                    xs={12}
                    sx={{ borderBottom: 1 }}
                    className={classes.cardTitleGrid}
                  >
                    <Typography className={classes.cardTitleTypography}>
                      New Sub Category
                    </Typography>
                  </Grid>

                  <Grid item lg={12} md={10} sm={12} xs={12} py={2}>
                    <Grid
                      container
                      direction="row"
                      alignItems="center"
                      spacing={2}
                    >
                      <Grid item lg={3} md={3} sm={12} xs={12}>
                        <Typography
                          variant="subtitle1"
                          className={classes.typography}
                        >
                          Name
                        </Typography>
                      </Grid>
                      <Grid item lg={9} md={9} sm={12} xs={12}>
                        <TextField
                          placeholder="Enter Product Category Name"
                          size="small"
                          {...formik.getFieldProps("categoryName")}
                          sx={{ width: "100%" }}
                          InputProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                        />
                      </Grid>
                    </Grid>

                    <Grid
                      container
                      direction="row"
                      alignItems="center"
                      spacing={2}
                      sx={{ mt: 1 }}
                    >
                      <Grid item lg={3} md={3} sm={12} xs={12}>
                        <Typography
                          variant="subtitle1"
                          className={classes.typography}
                        >
                          Category
                        </Typography>
                      </Grid>
                      <Grid
                        item
                        lg={9}
                        md={9}
                        sm={12}
                        xs={12}
                        display="flex"
                        alignItems="center"
                      >
                        <TextField
                          placeholder="Enter Product Category Name"
                          size="small"
                          sx={{ width: "100%" }}
                          InputProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                          value={formik.values.parent_ids
                            .map((id) => allCategoryMap.get(id))
                            .join(", ")}
                        />
                        <Box m={0.5}></Box>
                        <Tooltip title="Change Category">
                          <Button
                            variant="contained"
                            className={classes.searchButton}
                            onClick={handleShowCategorySelection}
                          >
                            <ChangeCircleIcon />
                          </Button>
                        </Tooltip>
                      </Grid>
                    </Grid>

                    {showCategorySelection && (
                      <>
                        <Grid
                          container
                          direction="row"
                          alignItems="center"
                          spacing={2}
                          sx={{ mt: 1 }}
                        >
                          <Grid item lg={3} md={3} sm={12} xs={12}>
                            <Typography
                              variant="subtitle1"
                              className={classes.typography}
                            >
                              Main Category
                            </Typography>
                          </Grid>
                          <Grid
                            item
                            lg={9}
                            md={9}
                            sm={12}
                            xs={12}
                            display="flex"
                            alignItems="center"
                          >
                            <TextField
                              select
                              fullWidth
                              size="small"
                              sx={{ flexGrow: 1 }}
                              SelectProps={{
                                native: true,
                              }}
                              value={selectedCategoryId || ""}
                              onChange={handleMainCategoryChange}
                              InputLabelProps={{ shrink: true }}
                            >
                              <option
                                value=""
                                disabled
                                style={{ color: "gray" }}
                              >
                                Select an option
                              </option>
                              {categoryList &&
                                categoryList
                                  .filter(
                                    (category) =>
                                      category.id !== formik.values.id
                                  )
                                  .map((category) => (
                                    <option
                                      key={category.id}
                                      value={category.id}
                                    >
                                      {category.categoryName}
                                    </option>
                                  ))}
                            </TextField>
                          </Grid>
                        </Grid>

                        {selectedCategoryId && subCategoryList.length > 0 && (
                          <Grid
                            container
                            direction="row"
                            alignItems="center"
                            spacing={2}
                            sx={{ mt: 1 }}
                          >
                            <Grid item lg={3} md={3} sm={12} xs={12}>
                              <Typography
                                variant="subtitle1"
                                className={classes.typography}
                              >
                                Sub Category
                              </Typography>
                            </Grid>
                            <Grid
                              item
                              lg={9}
                              md={9}
                              sm={12}
                              xs={12}
                              display="flex"
                              alignItems="center"
                            >
                              <TextField
                                select
                                fullWidth
                                size="small"
                                sx={{ flexGrow: 1 }}
                                SelectProps={{
                                  native: true,
                                }}
                                value={
                                  selectedSubCategoryId === null
                                    ? ""
                                    : selectedSubCategoryId
                                }
                                onChange={handleSubCategoryChange}
                                InputLabelProps={{ shrink: true }}
                              >
                                <option
                                  value=""
                                  disabled
                                  style={{ color: "gray" }}
                                >
                                  Select an option
                                </option>
                                {subCategoryList
                                  .filter(
                                    (subcategory) =>
                                      subcategory.id !== formik.values.id
                                  )
                                  .map((subcategory) => (
                                    <option
                                      key={subcategory.id}
                                      value={subcategory.id}
                                    >
                                      {subcategory.categoryName}
                                    </option>
                                  ))}
                              </TextField>
                            </Grid>
                          </Grid>
                        )}

                        {selectedCategoryId &&
                          selectedSubCategoryId &&
                          subToSubCategoryList.length > 0 && (
                            <Grid
                              container
                              direction="row"
                              alignItems="center"
                              spacing={2}
                              sx={{ mt: 1 }}
                            >
                              <Grid item lg={3} md={3} sm={12} xs={12}>
                                <Typography
                                  variant="subtitle1"
                                  className={classes.typography}
                                >
                                  Sub-to-Sub Category
                                </Typography>
                              </Grid>
                              <Grid
                                item
                                lg={9}
                                md={9}
                                sm={12}
                                xs={12}
                                display="flex"
                                alignItems="center"
                              >
                                <TextField
                                  select
                                  fullWidth
                                  size="small"
                                  sx={{ flexGrow: 1 }}
                                  SelectProps={{
                                    native: true,
                                  }}
                                  value={
                                    selectedSubToSubCategoryId === null
                                      ? ""
                                      : selectedSubToSubCategoryId
                                  }
                                  onChange={handleSubToSubCategoryChange}
                                  InputLabelProps={{ shrink: true }}
                                >
                                  <option
                                    value=""
                                    disabled
                                    style={{ color: "gray" }}
                                  >
                                    Select an option
                                  </option>
                                  {subToSubCategoryList
                                    .filter(
                                      (subcategory) =>
                                        subcategory.id !== formik.values.id
                                    )
                                    .map((subcategory) => (
                                      <option
                                        key={subcategory.id}
                                        value={subcategory.id}
                                      >
                                        {subcategory.categoryName}
                                      </option>
                                    ))}
                                </TextField>
                              </Grid>
                            </Grid>
                          )}
                      </>
                    )}

                    <Grid
                      container
                      direction="row"
                      alignItems="center"
                      spacing={2}
                      sx={{ mt: 1 }}
                    >
                      <Grid item lg={3} md={3} sm={12} xs={12}>
                        <Typography
                          variant="subtitle1"
                          className={classes.typography}
                        >
                          Description
                        </Typography>
                      </Grid>
                      <Grid item lg={9} md={9} sm={12} xs={12}>
                        <TextField
                          placeholder="Enter Sub Category Description"
                          size="small"
                          {...formik.getFieldProps("subCatDescription")}
                          sx={{ width: "100%" }}
                          InputProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                        />
                      </Grid>
                    </Grid>

                    <Grid
                      container
                      direction="row"
                      alignItems="center"
                      spacing={2}
                      sx={{ mt: 1 }}
                    >
                      <Grid item lg={3} md={3} sm={12} xs={12}>
                        <Typography
                          variant="subtitle1"
                          className={classes.typography}
                        >
                          Main Active
                        </Typography>
                      </Grid>
                      <Grid item lg={9} md={9} sm={12} xs={12}>
                        <CustomSwitch
                          color="primary"
                          sx={{ mr: 2 }}
                          formik={formik}
                          name="subIsMain"
                        />
                      </Grid>
                    </Grid>

                    <Grid
                      container
                      direction="row"
                      alignItems="center"
                      spacing={2}
                      sx={{ mt: 1 }}
                    >
                      <Grid item lg={3} md={3} sm={12} xs={12}>
                        <Typography
                          variant="subtitle1"
                          className={classes.typography}
                        >
                          Active
                        </Typography>
                      </Grid>
                      <Grid item lg={9} md={9} sm={12} xs={12}>
                        <CustomSwitch
                          color="primary"
                          sx={{ mr: 2 }}
                          formik={formik}
                          name="isActive"
                        />
                      </Grid>
                    </Grid>

                    <Grid
                      container
                      direction="row"
                      alignItems="center"
                      spacing={2}
                      sx={{ mt: 1 }}
                    >
                      <Grid item lg={3} md={3} sm={12} xs={12}>
                        <Typography
                          variant="subtitle1"
                          className={classes.typography}
                        >
                          Image
                        </Typography>
                      </Grid>
                      <Grid
                        item
                        lg={9}
                        md={9}
                        sm={12}
                        xs={12}
                        display="flex"
                        alignItems="center"
                      >
                        <Box
                          sx={{
                            border: 1,
                            borderColor: "#d3d3d3",
                            borderRadius: 1,
                            display: "flex",
                            justifyContent: "flex-end",
                            alignItems: "center",
                            padding: 1,
                            width: "100%",
                          }}
                        >
                          {selectedImage && (
                            <img
                              alt="Selected"
                              height="160px"
                              src={URL.createObjectURL(selectedImage)}
                              style={{ position: "inherit" }}
                              width="80%"
                            />
                          )}
                          {!selectedImage && data && (
                            <img
                              alt="Selected"
                              height="160px"
                              src={data.subCatImg}
                              style={{ position: "inherit" }}
                              width="80%"
                            />
                          )}
                          <div>
                            <input
                              accept="image/*"
                              style={{ display: "none" }}
                              id="icon-button-file-1"
                              type="file"
                              onChange={handleImageChange}
                            />
                            <label htmlFor="icon-button-file-1">
                              <Tooltip title="Select image from desk">
                                <IconButton
                                  color="primary"
                                  aria-label="upload picture"
                                  component="span"
                                >
                                  <CloudUploadIcon
                                    sx={{ fontSize: 45, color: "green" }}
                                  />
                                </IconButton>
                              </Tooltip>
                            </label>
                          </div>
                        </Box>
                      </Grid>
                    </Grid>
                  </Grid>

                  <Grid
                    item
                    lg={12}
                    md={12}
                    sm={12}
                    xs={12}
                    sx={{ display: "flex", justifyContent: "flex-end" }}
                  >
                    <Button
                      variant="contained"
                      startIcon={<CloseIcon />}
                      className={classes.cancelButton}
                      onClick={handleClose}
                    >
                      Cancel
                    </Button>
                    <Box m={0.5}></Box>
                    <Button
                      variant="contained"
                      startIcon={<SaveAltIcon />}
                      className={classes.saveButton}
                      onClick={() => formik.handleSubmit()}
                      disabled={!formValid || isLoading}
                    >
                      Save
                    </Button>
                  </Grid>
                </Grid>
              </Card>
            </Grid>
          </Grid>
        </Dialog>
      </form>
      <AlertPopUp
        open={deleteAlert}
        onCloseAlert={setDeleteAlert}
        message={alertMessage}
      />
    </Box>
  );
};

export default ProductCategory;
