import { Fragment, useEffect, useState } from "react";

// material-ui
import { styled, useTheme } from "@mui/material/styles";
import {
  Box,
  Grid,
  Card,
  CardMedia,
  CardContent,
  Typography,
  Chip,
  IconButton,
  Stack,
  Switch,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  InputLabel,
  TextField,
  Autocomplete,
} from "@mui/material";
import { useFormik } from "formik";
import * as yup from "yup";
import {
  fetchAppLocations,
  getproductcategories,
  getproductsubcategories,
  getProductUnits,
} from "pages/api/api";
import { handleFileChange } from "components/s3img";
import { enqueueSnackbar } from "notistack";

// project import

import ProductEmpty from "sections/apps/e-commerce/products/ProductEmpty";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { getallproducts, productsDelete, productsUpdate } from "pages/api/api";
import {
  CloseOutlined,
  DeleteFilled,
  EditOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import axios from "axios";
import MainCard from "components/MainCard";
import CircularLoader from "components/third-party/CircularLoader";
const statuss = [
  { value: "available", label: "Available" },
  { value: "outofstock", label: "Out of Stock" },
];

const validationSchema = yup.object({
  applocationid: yup.number().required("Please select location "),
  categoryid: yup.number().required("Please select a  category "),
  subcategoryid: yup
    .number()
    .nullable()
    .test("required", "Please select subcategory", (value) => {
      return value !== null && value !== undefined; // The .test() explicitly accepts 0, and only fails if the value is null or undefined.
    }),
  productname: yup.string().required("Product Name is required"),
  productdesc: yup.string().required("Product Description is required"),
  productunit: yup.string().required("Product Unit is required"),
  unitvalue: yup
    .number()
    .typeError("Unit Value must be a number") // in case user enters letters
    .required("Unit Value is required")
    .moreThan(0, "Value must be greater than 0"),
  productcost: yup
    .number()
    .typeError("Product Costmust be a number") // in case user enters letters
    .required(" Product Cost is required")
    .moreThan(0, "Value must be greater than 0"),
  taxamount: yup.number().required(" Tax Amount is required"),
  taxpercent: yup.number().required(" Tax Percent is required"),
  producttax: yup.number().required(" Product Tax is required"),
  productstock: yup
    .number()
    .typeError("Product Stock be a number") // in case user enters letters
    .required(" Product Stock is required")
    .moreThan(0, "Value must be greater than 0"),

  approve: yup.number().required("  is required"),
  productstatus: yup.string().required("Product Status  is required"),
  productimage: yup.string().required("Product Image  is required"),
});

/* ============================================= || opentoast || ============================================= */

const opentoast = (message, variant, duration) => {
  enqueueSnackbar(message, {
    variant: variant,
    anchorOrigin: { vertical: "top", horizontal: "right" },
    autoHideDuration: duration,
  });
};

const ProductsView = ({ sx, selectedCat }) => {
  const theme = useTheme();
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editDialog, setEditDialog] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState({});

  const useDeleteProduct = () => {
    const queryClient = useQueryClient();

    return useMutation({
      mutationFn: productsDelete,
      onSuccess: () => {
        queryClient.invalidateQueries(["productlist"]); // Refresh the list
        opentoast("Product Deleted Succesfully", "success", 1000);
      },
      onError: (error) => {
        console.error("Delete failed:", error);
        opentoast(error.message, "error", 1000);
      },
    });
  };
  const { mutate: deleteProduct, isLoading: deleteLoading } =
    useDeleteProduct();

  const handleDelete = (productid) => {
    deleteProduct({ productid });
  };

  const useUpdateProductStatus = () => {
    const queryClient = useQueryClient();
    return useMutation({
      mutationFn: productsUpdate,
      onSuccess: () => {
        queryClient.invalidateQueries(["productlist"]); // // Refresh the list
        opentoast("Product Updated Succesfully", "success", 1000);
      },
      onError: (error) => {
        console.error("Update failed:", error);
        opentoast(error.message, "error", 1000);
      },
    });
  };

  const { mutate: updateProductStatus, isLoading: updateLoading } =
    useUpdateProductStatus();

  const handleStatusChange = (props) => {
    updateProductStatus(props);
    setEditDialog(false);
  };
  const formik = useFormik({
    initialValues: {},
    validationSchema,
    onSubmit: handleStatusChange,
  });

  const { data: productList, isLoading: productlistloading } = useQuery({
    queryKey: ["productlist", selectedCat?.subcatid],
    queryFn: () => getallproducts(selectedCat?.subcatid || 0),
  });
  const { data: locations, isLoading: locationsloading } = useQuery({
    queryKey: ["applocation"],
    queryFn: fetchAppLocations,
    refetchOnWindowFocus: false,
  });

  const { data: cat, isLoading: catloading } = useQuery({
    queryKey: ["productcategory"],
    queryFn: getproductcategories,
  });

  const { data: SubCat, isLoading: subcatloading } = useQuery({
    queryKey: ["productsubcategory", selectedCat],
    queryFn: () => getproductsubcategories(selectedCat),
  });

  const { data: unitOptions } = useQuery({
    queryKey: ["productunits"],
    queryFn: getProductUnits,
  });

  return (
    <Fragment>
      {(productlistloading ||
        locationsloading ||
        catloading ||
        subcatloading) && <CircularLoader />}
      {/* <MainCard sx={{ mt: 1 }}> */}
      <Grid container spacing={2} sx={{ mt: 1 }}>
        {productList?.length <= 0 && (
          <Grid item xs={12} sx={{}}>
            <ProductEmpty />
          </Grid>
        )}
        {productList?.map((product, index) => (
          <Grid
            item
            xs={12}
            custom350={6}
            custom450={4}
            sm={4}
            md={3}
            lg={3}
            key={index}
          >
            <Card
              sx={{
                height: "100%",
                display: "flex",
                flexDirection: "column",
                borderRadius: 2,
                boxShadow: 4,
                overflow: "hidden",
              }}
            >
              {/* Image Section */}
              <Box sx={{ position: "relative" }}>
                {/* Product Image */}
                <CardMedia
                  component="img"
                  height="180"
                  image={product.productimage}
                  alt={product.productname}
                  sx={{
                    objectFit: "cover",
                    filter:
                      product.productstatus === "outofstock"
                        ? "grayscale(100%) brightness(0.8)"
                        : "none", // ✅ grayscale the image only
                    transition: "filter 0.3s ease",
                  }}
                />

                {/* Status Chip on top-left */}
                <Chip
                  label={
                    product.productstatus === "available"
                      ? "Available"
                      : "Out of Stock"
                  }
                  color={
                    product.productstatus === "available" ? "success" : "error"
                  }
                  size="small"
                  sx={{
                    position: "absolute",
                    top: 8,
                    left: 8,
                    fontSize: 12,
                    fontWeight: 500,
                    backgroundColor:
                      product.productstatus === "available"
                        ? "success.main"
                        : "error.main",
                    color: "#fff",
                  }}
                />
              </Box>

              {/* Content Section */}
              <CardContent sx={{ flexGrow: 1, p: 2 }}>
                <Stack
                  sx={{
                    display: "flex",
                    flexDirection: {
                      xs: "row", //0 to 450
                      custom350: "column", // 450 and above
                      sm: "row",
                    },
                    justifyContent: "space-between",
                    alignItems: "flex-start",
                  }}
                >
                  {/* Product Info */}
                  <Box sx={{ flex: 1, pr: 1 }}>
                    <Typography
                      gutterBottom
                      sx={{
                        display: "flex",
                        flexDirection: "column",
                        fontSize: 10,
                        wordBreak: "break-word",
                      }}
                    >
                      <Box
                        component="span"
                        sx={{
                          fontWeight: 600,
                          lineHeight: 1.2,
                          wordBreak: "break-word",
                          fontSize: {
                            xs: 14, // <600px
                            sm: 16, // ≥600px
                            md: 18, // ≥900px
                            lg: 20, // ≥1200px
                          },
                        }}
                      >
                        {product.productname}
                      </Box>
                      <Box
                        component="span"
                        sx={{ color: "text.secondary", fontSize: 14 }}
                      >
                        ₹{product.productcost} / {product.productunit}
                      </Box>
                    </Typography>

                    <Chip
                      label={`Stock: ${product.productstock}( ${product.productunit})`}
                      size="small"
                      color={
                        product.productstock > 0 &&
                        product.productstatus === "available"
                          ? "primary"
                          : "secondary"
                      }
                      sx={{ mt: 1 }}
                    />
                  </Box>

                  <Stack
                    spacing={1}
                    alignItems="flex-end"
                    sx={{
                      // flexDirection: "column",
                      flexDirection: {
                        xs: "column", // small screens
                        custom350: "row-reverse", // from small screens and up
                        sm: "column", // from small screens and up
                      },
                      display: "flex",
                      // alignItems: "center",
                    }}
                  >
                    <Switch
                      size="small"
                      checked={product.productstatus === "available"}
                      onChange={() =>
                        handleStatusChange({
                          productid: product.productid,
                          productstatus:
                            product.productstatus === "available"
                              ? "outofstock"
                              : "available",
                        })
                      }
                    />
                    <Stack
                      spacing={1}
                      alignItems="flex-end"
                      sx={{
                        flexDirection: "row",
                        display: "flex",
                      }}
                    >
                      <IconButton
                        color="primary"
                        onClick={() => {
                          console.log("editproduct", product);

                          setEditDialog(true);
                          formik.resetForm({
                            values: {
                              ...formik.initialValues,
                              productid: product.productid,
                              applocationid: product.applocationid,
                              categoryid: product.categoryid,
                              subcategoryid: product.subcategoryid,
                              productname: product.productname,
                              productdesc: product.productdesc,
                              productunit: product.productunit,
                              unitvalue: product.unitvalue,
                              productcost: product.productcost,
                              taxamount: product.taxamount,
                              taxpercent: product.taxpercent,
                              producttax: product.producttax,
                              productstock: product.productstock,
                              approve: product.productstock,
                              productstatus: product.productstatus,
                              productimage: product.productimage,
                            },
                          });
                        }}
                      >
                        <EditOutlined />
                      </IconButton>
                      <IconButton
                        color="error"
                        onClick={() => {
                          setSelectedProduct(product);
                          setDialogOpen(true);
                        }}
                      >
                        <DeleteFilled />
                      </IconButton>
                    </Stack>
                  </Stack>
                </Stack>
              </CardContent>
            </Card>
          </Grid>
        ))}
      </Grid>
      {/* ========================= || Delete product Dialog ========================= || */}
      <Dialog
        open={dialogOpen}
        onClose={() => setDialogOpen(false)}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitle sx={{ backgroundColor: theme.palette.error.light }}>
          <Stack
            direction="row"
            justifyContent="space-between"
            alignItems="center"
          >
            {/* Left side - Title with Icon */}
            <Stack direction="row" alignItems="center" spacing={1}>
              <DeleteFilled style={{ color: "#d32f2f" }} />
              <Typography variant="h4">Delete Product</Typography>
            </Stack>

            {/* Right side - Close Button */}
            <IconButton onClick={() => setDialogOpen(false)} size="small">
              <CloseOutlined />
            </IconButton>
          </Stack>
        </DialogTitle>

        <DialogContent>
          <Typography variant="h5" sx={{ mt: 1 }}>
            Are you sure you want to delete this product? This action cannot be
            undone.
          </Typography>
        </DialogContent>

        <DialogActions>
          <Button variant="outlined" onClick={() => setDialogOpen(false)}>
            Cancel
          </Button>
          <Button
            variant="contained"
            color="error"
            onClick={() => {
              handleDelete(selectedProduct.productid); // Replace with your delete logic
              setDialogOpen(false);
            }}
          >
            Delete
          </Button>
        </DialogActions>
      </Dialog>
      {/* ========================= || Delete product Dialog ========================= || */}
      <Dialog open={editDialog} fullWidth scroll="paper">
        <DialogTitle
          sx={{ backgroundColor: theme.palette.primary.main, color: "white" }}
        >
          <Stack
            direction="row"
            justifyContent="space-between"
            alignItems="center"
          >
            {/* Left side - Title with Icon */}
            <Stack direction="row" alignItems="center" spacing={1}>
              <EditOutlined />
              <Typography variant="h4">Edit Product</Typography>
            </Stack>
            <IconButton
              sx={{ color: "white" }}
              onClick={() => setEditDialog(false)}
            >
              <CloseOutlined />
            </IconButton>
          </Stack>
        </DialogTitle>
        <form onSubmit={formik.handleSubmit} noValidate>
          <DialogContent sx={{ overflow: "scroll" }}>
            <MainCard
              sx={{ overflow: "scroll" }}
              title={
                <Grid container spacing={3}>
                  <Grid item xs={12} sm={4}>
                    <InputLabel sx={{ mb: 1 }}>Location</InputLabel>
                    <Autocomplete
                      disablePortal
                      id="combo-box-location"
                      options={locations || []}
                      value={
                        locations?.find(
                          (loc) =>
                            loc.applocationid === formik.values.applocationid
                        ) || null
                      }
                      getOptionLabel={(option) =>
                        `${option.locationname || ""}`
                      }
                      onChange={(event, value) => {
                        formik.setFieldValue(
                          "applocationid",
                          value?.applocationid || null
                        );
                      }}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          placeholder={"Select Location"}
                          error={
                            formik.touched.applocationid &&
                            Boolean(formik.errors.applocationid)
                          }
                          helperText={
                            formik.touched.applocationid &&
                            formik.errors.applocationid
                          }
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} sm={4}>
                    <InputLabel sx={{ mb: 1 }}>Category</InputLabel>
                    <Autocomplete
                      disablePortal
                      id="combo-box-category"
                      options={cat || []}
                      value={
                        cat?.find(
                          (loc) => loc.categoryid === formik.values.categoryid
                        ) || null
                      }
                      getOptionLabel={(option) => option?.categoryname || ""}
                      onChange={(event, value) => {
                        formik.setFieldValue(
                          "categoryid",
                          value?.categoryid || null
                        );
                        // setSelectedCat(value || null);
                      }}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          placeholder={"Select Category"}
                          error={
                            formik.touched.categoryid &&
                            Boolean(formik.errors.categoryid)
                          }
                          helperText={
                            formik.touched.categoryid &&
                            formik.errors.categoryid
                          }
                        />
                      )}
                    />
                  </Grid>
                  {SubCat?.length > 0 && (
                    <Grid item xs={12} sm={4}>
                      <InputLabel sx={{ mb: 1 }}>Sub Category</InputLabel>
                      <Autocomplete
                        disablePortal
                        id="combo-box-category"
                        options={SubCat || []}
                        value={
                          SubCat?.find(
                            (loc) =>
                              loc.subcatid === formik.values.subcategoryid
                          ) || null
                        }
                        getOptionLabel={(option) => option?.subcatname || ""}
                        onChange={(event, value) => {
                          formik.setFieldValue(
                            "subcategoryid",
                            +value?.subcatid || null
                          );
                        }}
                        renderInput={(params) => (
                          <TextField
                            {...params}
                            placeholder={"Select Sub Category"}
                            error={
                              formik.touched.subcategoryid &&
                              Boolean(formik.errors.subcategoryid)
                            }
                            helperText={
                              formik.touched.subcategoryid &&
                              formik.errors.subcategoryid
                            }
                          />
                        )}
                      />
                    </Grid>
                  )}
                </Grid>
              }
            >
              <Grid container spacing={2} sx={{}}>
                <Grid item xs={12} sm={4} sx={{}}>
                  <MainCard>
                    <Grid container spacing={1} direction="column">
                      <Grid item xs={12}>
                        <InputLabel sx={{ mb: 1 }}>Product Name</InputLabel>
                        <TextField
                          name="productname"
                          placeholder="Enter Product name"
                          fullWidth
                          value={formik.values.productname}
                          onChange={formik.handleChange}
                          error={
                            formik.touched.productname &&
                            Boolean(formik.errors.productname)
                          }
                          helperText={
                            formik.touched.productname &&
                            formik.errors.productname
                          }
                        />
                      </Grid>
                      <Grid item xs={12}>
                        <InputLabel sx={{ mb: 1 }}>
                          Product Description
                        </InputLabel>
                        <TextField
                          name="productdesc"
                          placeholder="Enter product description"
                          fullWidth
                          multiline
                          rows={3}
                          value={formik.values.productdesc}
                          onChange={formik.handleChange}
                          error={
                            formik.touched.productdesc &&
                            Boolean(formik.errors.productdesc)
                          }
                          helperText={
                            formik.touched.productdesc &&
                            formik.errors.productdesc
                          }
                        />
                      </Grid>
                      <Grid item xs={12}>
                        <InputLabel sx={{ mb: 1 }}>Product Unit</InputLabel>

                        <Autocomplete
                          disablePortal
                          id="combo-box-category"
                          options={unitOptions || []}
                          value={
                            unitOptions?.find(
                              (option) =>
                                option.typename === formik.values.productunit
                            ) || null
                          }
                          getOptionLabel={(option) => option?.typename || ""}
                          onChange={(event, value) => {
                            formik.setFieldValue(
                              "productunit",
                              value?.typename || null
                            );
                          }}
                          renderInput={(params) => (
                            <TextField
                              {...params}
                              placeholder={"Select Product Unit"}
                              error={
                                formik.touched.productunit &&
                                Boolean(formik.errors.productunit)
                              }
                              helperText={
                                formik.touched.productunit &&
                                formik.errors.productunit
                              }
                            />
                          )}
                        />
                      </Grid>
                      <Grid item xs={12}>
                        <InputLabel sx={{ mb: 1 }}>Unit Value</InputLabel>
                        <TextField
                          name="unitvalue"
                          placeholder="Enter Unit Value"
                          fullWidth
                          value={formik.values.unitvalue ?? ""}
                          onChange={formik.handleChange}
                          error={
                            formik.touched.unitvalue &&
                            Boolean(formik.errors.unitvalue)
                          }
                          helperText={
                            formik.touched.unitvalue && formik.errors.unitvalue
                          }
                        />
                      </Grid>
                    </Grid>
                  </MainCard>
                </Grid>
                <Grid item xs={12} sm={4} sx={{}}>
                  <MainCard>
                    <Grid container direction="column" spacing={2}>
                      <Grid item xs={12}>
                        <InputLabel sx={{ mb: 1 }}>Product Cost</InputLabel>
                        <TextField
                          name="productcost"
                          type="number"
                          placeholder="Enter Unit Value"
                          fullWidth
                          value={formik.values.productcost ?? ""}
                          onChange={(e) => {
                            const value = e.target.value;
                            formik.setFieldValue("productcost", +value);

                            // ⬇️ Trigger tax calculation
                            const cost = parseFloat(value);
                            const percent =
                              parseFloat(formik.values.taxpercent) || 0;
                            if (!isNaN(cost)) {
                              const taxAmount = (cost * percent) / 100;
                              formik.setFieldValue("taxamount", +taxAmount);
                            } else {
                              formik.setFieldValue("taxamount", 0);
                            }
                          }}
                          error={
                            formik.touched.productcost &&
                            Boolean(formik.errors.productcost)
                          }
                          helperText={
                            formik.touched.productcost &&
                            formik.errors.productcost
                          }
                        />
                      </Grid>
                      <Grid item xs={12}>
                        <InputLabel sx={{ mb: 1 }}>Tax Percent</InputLabel>
                        <TextField
                          name="taxpercent"
                          type="number"
                          placeholder="Enter Tax Percent"
                          fullWidth
                          value={formik.values.taxpercent ?? ""}
                          onChange={(e) => {
                            const value = e.target.value;
                            formik.setFieldValue("taxpercent", +value);

                            // ⬇️ Trigger tax calculation
                            const cost =
                              parseFloat(formik.values.productcost) || 0;
                            const percent = parseFloat(value) || 0;
                            const taxAmount = (cost * percent) / 100;
                            formik.setFieldValue("taxamount", +taxAmount);
                          }}
                          error={
                            formik.touched.taxpercent &&
                            Boolean(formik.errors.taxpercent)
                          }
                          helperText={
                            formik.touched.taxpercent &&
                            formik.errors.taxpercent
                          }
                        />
                      </Grid>
                      <Grid item xs={12}>
                        <InputLabel sx={{ mb: 1 }}>Tax Amount</InputLabel>
                        <TextField
                          name="taxamount"
                          placeholder="Calculated Tax Amount"
                          fullWidth
                          value={formik.values.taxamount ?? ""}
                          InputProps={{
                            readOnly: true,
                          }}
                          error={
                            formik.touched.taxamount &&
                            Boolean(formik.errors.taxamount)
                          }
                          helperText={
                            formik.touched.taxamount && formik.errors.taxamount
                          }
                        />
                      </Grid>
                      <Grid item xs={12}>
                        <InputLabel sx={{ mb: 1 }}>Product Stock</InputLabel>
                        <TextField
                          name="productstock"
                          type="number"
                          placeholder="Enter Product Stock"
                          fullWidth
                          value={formik.values.productstock || ""}
                          onChange={formik.handleChange}
                          error={
                            formik.touched.productstock &&
                            Boolean(formik.errors.productstock)
                          }
                          helperText={
                            formik.touched.productstock &&
                            formik.errors.productstock
                          }
                        />
                      </Grid>
                    </Grid>
                  </MainCard>
                </Grid>
                <Grid item xs={12} sm={4} sx={{}}>
                  <MainCard>
                    <Grid container direction="column" spacing={2}>
                      <Grid item xs={12}>
                        <InputLabel sx={{ mb: 1 }}>Status</InputLabel>
                        <Autocomplete
                          fullWidth
                          name="productstatus"
                          options={statuss}
                          getOptionLabel={(option) => option.label || ""}
                          value={
                            statuss.find(
                              (option) =>
                                option.value === formik.values.productstatus
                            ) || null
                          }
                          onChange={(_, selectedOption) => {
                            formik.setFieldValue(
                              "productstatus",
                              selectedOption?.value || ""
                            );
                          }}
                          renderInput={(params) => (
                            <TextField
                              {...params}
                              placeholder="Select Product Status"
                              error={
                                formik.touched.productstatus &&
                                Boolean(formik.errors.productstatus)
                              }
                              helperText={
                                formik.touched.productstatus &&
                                formik.errors.productstatus
                              }
                            />
                          )}
                        />
                      </Grid>

                      <Grid item xs={12}>
                        <InputLabel sx={{ mb: 1 }}>Product Image</InputLabel>

                        <Button
                          component="label"
                          variant="outlined"
                          color="secondary"
                          startIcon={<UploadOutlined />}
                          sx={{ mt: 1, textTransform: "none" }}
                        >
                          Image Change
                          <input
                            name="productimage"
                            type="file"
                            hidden
                            accept="image/png, image/jpeg"
                            onChange={async (event) => {
                              const s3url = await handleFileChange(event);
                              if (
                                s3url &&
                                typeof s3url === "string" &&
                                s3url.startsWith("http")
                              ) {
                                formik.setFieldValue("productimage", s3url);
                              } else {
                                console.error("Upload failed or invalid file.");
                              }
                            }}
                          />
                        </Button>

                        {formik.touched.productimage &&
                          formik.errors.productimage && (
                            <Typography color="error" sx={{ mt: 1 }}>
                              {formik.errors.productimage}
                            </Typography>
                          )}

                        {formik.values.productimage && (
                          <Box mt={2}>
                            <img
                              src={formik.values.productimage} // ✅ S3 URL
                              alt="Uploaded preview"
                              style={{ width: "100px", borderRadius: 4 }}
                            />
                          </Box>
                        )}
                      </Grid>
                    </Grid>
                  </MainCard>
                </Grid>
              </Grid>
            </MainCard>
          </DialogContent>

          <DialogActions
            sx={{
              position: "sticky", // ✅ Keep fixed at the bottom of scroll container
              bottom: 0,
              backgroundColor: "background.paper",
              zIndex: 1,
            }}
          >
            <Button
              variant="outlined"
              color="secondary"
              onClick={() => {
                setEditDialog(false);
              }}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              variant="contained"
              sx={{ textTransform: "none", mr: 4 }}
            >
              Edit Product
            </Button>
          </DialogActions>
        </form>
      </Dialog>
    </Fragment>
  );
};

export default ProductsView;
