import { ArrowLeftOutlined, UploadOutlined } from "@ant-design/icons";
import {
  Button,
  Grid,
  InputLabel,
  MenuItem,
  Stack,
  TextField,
  Typography,
  Autocomplete,
  ListItemText,
  Box,
} from "@mui/material";
import axios from "axios";
import MainCard from "components/MainCard";
import Titlecard from "pages/titleCard";
import React, { useEffect, useState } from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import { useNavigate } from "react-router";
import { handleFileChange } from "components/s3img"; //s3 bucket
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  fetchAppLocations,
  getproductcategories,
  getproductsubcategories,
  getProductUnits,
  productCreate,
} from "pages/api/api";
import { enqueueSnackbar } from "notistack";
import uploadImage from "../../assets/images/uploadImage.png";

const validationSchema = yup.object({
  applocationid: yup.number().required("Please select location "),
  categoryid: yup.number().required("Please select a  category "),
  subcategoryid: yup
    .number()
    // .typeError("Subcategory must be a number")
    // .nullable()
    .required("Please select subcategory"),
  // .test("not-null", "Please select subcategory", (value) => {
  //   return value !== null && value !== 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.string().required(" Unit Value 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"),
  // productimage: yup
  //   .mixed()
  //   .required("Image is required")
  //   // .test("fileSize", "File too large", (value) => {
  //   //   return value && value.size <= 1024 * 1024; // <= 1 MB
  //   // })
  //   .test("fileType", "Unsupported file type", (value) => {
  //     return (
  //       value && ["image/jpeg", "image/png", "image/webp"].includes(value.type)
  //     );
  //   }),
});

const statuss = [
  { value: "available", label: "Available" },
  { value: "outofstock", label: "Out of Stock" },
];
/* ============================================= || opentoast || ============================================= */

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

const Addproducts = () => {
  const [selectedCat, setSelectedCat] = useState(null);
  const [selectedSubCat, setSelectedSubCat] = useState(null);
  const navigate = useNavigate();

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

    return useMutation({
      mutationFn: productCreate,

      onSuccess: (data) => {
        console.log("✅ Product created:", data);
        opentoast("Product Deleted Succesfully", "success", 1000);
        // Invalidate relevant queries after creation (adjust keys as per your app)
        queryClient.invalidateQueries({ queryKey: ["productlist"] });
        navigate("../products");
      },

      onError: (error) => {
        console.error("❌ Product creation failed:", error);
        opentoast(error.message, "erroe", 1000);
      },
    });
  };

  const { mutate: createProduct, isPending: isCreating } = useCreateProduct();

  const handleCreate = (values) => {
    createProduct(values); // values = formik.values
  };

  const formik = useFormik({
    initialValues: {
      applocationid: null,
      categoryid: null,
      subcategoryid: null,
      productname: "",
      productdesc: "",
      productunit: "",
      unitvalue: null,
      productcost: null,
      taxamount: null,
      taxpercent: null,
      producttax: 0,
      productstock: null,
      othercost: 0.0,
      approve: 1,
      productstatus: "",
      productimage: null,
    },
    validationSchema,
    onSubmit: handleCreate,
    // onSubmit: async (values) => {
    //   try {
    //     console.log("Submitted:", values);

    //     const response = await axios.post(
    //       `${process.env.REACT_APP_URL}/products/create`,
    //       { ...values, tenantid: 1 }
    //     );
    //     console.log("postres", response.data);
    //   } catch (error) {
    //     console.error(
    //       "Submission error:",
    //       error.response?.data || error.message
    //     );
    //   }
    // },
  });

  const { data: locations } = useQuery({
    queryKey: ["applocation"],
    queryFn: fetchAppLocations,
  });

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

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

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

  return (
    <Stack>
      <Titlecard title={"Add New Product"}>
        <Button
          startIcon={<ArrowLeftOutlined />}
          variant="contained"
          color="secondary"
          size="small"
          onClick={() => {
            navigate("../products");
          }}
        >
          Back
        </Button>
      </Titlecard>
      <form onSubmit={formik.handleSubmit} noValidate>
        <MainCard
          sx={{ mt: 4 }}
          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 || []}
                  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 || []}
                  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 || []}
                    getOptionLabel={(option) => option?.subcatname || ""}
                    onChange={(event, value) => {
                      console.log("SubCat", value);

                      formik.setFieldValue(
                        "subcategoryid",
                        +value?.subcatid || 0
                      );
                      formik.setFieldValue("productimage", value.image);
                      setSelectedSubCat(value || 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>
                    <Stack
                      direction="row"
                      spacing={2}
                      alignItems="center"
                      flexWrap="wrap" // ✅ allows wrapping on small screens
                      gap={3}
                      sx={{ mt: 1 }}
                    >
                      {/* <Button
                        component="label"
                        variant="outlined"
                        color="secondary"
                        startIcon={<UploadOutlined />}
                        sx={{ mt: 1, textTransform: "none" }}
                      >
                        Click to Upload
                        <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.values.productimage && ( */}
                      <Box mt={2}>
                        <img
                          src={formik.values.productimage || uploadImage} // ✅ S3 URL
                          alt="Uploaded preview"
                          style={{ maxWidth: "100px", borderRadius: 4 }}
                        />
                      </Box>
                      {/* )} */}
                    </Stack>
                  </Grid>

                  <Grid item xs={12}>
                    <Stack
                      gap={3}
                      sx={{
                        display: "flex",
                        justifyContent: "left",
                        alignItems: "center",
                        flexDirection: "row",
                        flexWrap: "wrap",
                      }}
                    >
                      <Button
                        variant="outlined"
                        color="secondary"
                        onClick={() => {
                          navigate("../products");
                        }}
                      >
                        Back
                      </Button>
                      <Button
                        variant="outlined"
                        color="secondary"
                        onClick={() => {
                          // formik.resetForm();
                          const { applocationid, categoryid, subcategoryid } =
                            formik.values;
                          formik.resetForm({
                            values: {
                              ...formik.initialValues,
                              applocationid,
                              categoryid,
                              subcategoryid,
                            },
                          });
                        }}
                      >
                        Reset
                      </Button>
                      <Button
                        type="submit"
                        variant="contained"
                        sx={{ textTransform: "none" }}
                      >
                        Create
                      </Button>
                    </Stack>
                  </Grid>
                </Grid>
              </MainCard>
            </Grid>
          </Grid>
        </MainCard>
      </form>
    </Stack>
  );
};

export default Addproducts;
