import React, { useMemo, useState } from "react";
import {
  Box,
  Button,
  Card,
  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 {
  useCreateCategoryMutation,
  useGetAllMainCategoryQuery,
  useGetSubCategoryByArrayQuery,
} from "../../../Api/attoDeskApi";
import { useNotifier } from "../../../Core/Notifier";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import { ICategory } from "../../../Api/Interface/api.interface";
import CustomSwitch from "../../../Components/Switch/CustomSwitch";
import { useStyles } from "../../../theme/styles";
import { uploadImage } from "../../../Components/UploadFile/upload";

const ProductCategory: React.FC = () => {
  const classes = useStyles();
  const [newProductCategory, { isLoading }] = useCreateCategoryMutation();
  const { showErrorMessage, showMessage } = useNotifier();
  const { data: categoryData } = useGetAllMainCategoryQuery({
    departmentId: "",
    coursingId: "",
    roleId: null,
    taxeId: "",
    createdDateStart: null,
    createdDateEnd: null,
    searchText: "",
    numberOfLength: null,
    isActive: true,
    categoryIsLooping: null,
    createdDate: null
  });

  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 [selectedImage, setSelectedImage] = React.useState<File | undefined>(
    undefined
  );
  const [isImageUploading, setIsImageUploading] = React.useState(false);

  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 formik = useFormik({
    initialValues: {
      categoryName: "",
      mainCatId: "",
      parent_ids: null,
      subCatDescription: "",
      subCatImg: "",
      isActive: true,
      subIsMain: false,
      categoryIsLooping: false,
      categoryLoopingConstant: "",
    },
    onSubmit: async (values, { resetForm }) => {
      try {
        const formData = new FormData();
        let subCatImg: string | undefined = "";

        if (selectedImage) {
          setIsImageUploading(true);
          formData.append("subCatImg", selectedImage);
          subCatImg = (await uploadImage(selectedImage)) || "";
          setIsImageUploading(false);
        }
        const parent_ids = selectedSubToSubCategoryId
          ? [
              Number(selectedCategoryId),
              Number(selectedSubCategoryId),
              Number(selectedSubToSubCategoryId),
            ]
          : selectedSubCategoryId
          ? [Number(selectedCategoryId), Number(selectedSubCategoryId)]
          : selectedCategoryId
          ? [Number(selectedCategoryId)]
          : [Number(values.mainCatId)];

        const tempData = {
          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,
        };

        const addProductCategory = await newProductCategory(tempData).unwrap();
        if (!addProductCategory.status) {
          showErrorMessage(addProductCategory.message);
        } else {
          showMessage(addProductCategory.message);
          resetForm();
          if (selectedCategoryId) {
            refetchSubCategories();
          }
          setSelectedCategoryId(null);
          setSelectedSubCategoryId(null);
          setSelectedSubToSubCategoryId(null);
          setSelectedImage(undefined);
        }
      } catch (error) {
        showErrorMessage("Something went wrong");
      }
    },
  });

  const formValid = useMemo(() => {
    return formik.values.categoryName !== "" && formik.values.mainCatId !== "";
  }, [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];
  //     setSelectedImage(file);
  //   } else {
  //     setSelectedImage(undefined);
  //   }
  // };

  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);
      }
    } else {
      setSelectedImage(undefined);
    }
  };

  const cancelFunction = () => {
    formik.resetForm();
    if (selectedCategoryId) {
      refetchSubCategories();
    }
    setSelectedCategoryId(null);
    setSelectedSubCategoryId(null);
    setSelectedSubToSubCategoryId(null);
    setSelectedImage(undefined);
  };

  return (
    <form onSubmit={formik.handleSubmit}>
      <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}
                    >
                      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.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.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.map((subToSubcategory) => (
                            <option
                              key={subToSubcategory.id}
                              value={subToSubcategory.id}
                            >
                              {subToSubcategory.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
                          src={URL.createObjectURL(selectedImage)}
                          alt="Uploaded"
                          style={{
                            maxWidth: "200px",
                            maxHeight: "200px",
                            marginRight: "auto",
                          }}
                        />
                      )}
                      <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={cancelFunction}
                >
                  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>
    </form>
  );
};

export default ProductCategory;
