import { Box, Button, Divider, Grid, Modal, Typography } from "@mui/material";
import { Field, Formik } from "formik";
import React, { useRef } from "react";
import { ProductManageFields } from "../../../data/ProductManageFields";
import { updateVendorInfo } from "../../../services/axios/allApi";
import TextFieldCommon from "../../common/Form/TextFieldCommon";
import SelectFieldCommon from "../../common/Form/SelectFieldCommon";
import * as Yup from "yup";

const style = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  width: 700,
  maxWidth: "98vw",
  bgcolor: "background.paper",
  boxShadow: 24,
  borderRadius: 2,
};

const ManageProductForm = ({
  open,
  setOpen,
  title,
  vendorInfo,
  getVendorInfo,
  setToastMsg,
  setToastType,
}) => {
  const handleClose = () => setOpen(false);

  // initial field values
  const initialValues = {
    first_name: vendorInfo?.user?.first_name ?? "",
    last_name: vendorInfo?.user?.last_name ?? "",
    shop_name: vendorInfo?.vendor?.shop_name ?? "",
    shop_phone: vendorInfo?.vendor?.shop_phone ?? "",
    shop_email: vendorInfo?.vendor?.shop_email ?? "",
    shop_address: vendorInfo?.vendor?.shop_address ?? "",
    shop_profile_pic: "",
    shop_cover_pic: "",
    myAutocomplete: "",
  };

  // validation
  const validationSchema = Yup.object({
    status: Yup.object().nullable().required("Required"),
  });

  // submit form with ref
  const formikRef = useRef();
  // console.log("formikRef errors:", formikRef.current?.errors)

  const handleSubmit = () => {
    if (formikRef.current) {
      handleClose();
      formikRef.current.submitForm();
    }
  };

  // submit form
  const handleSubmitForm = async (values, setSubmitting) => {
    console.log("handleSubmitForm - values:", values);
    // try {
    //   const updateResponse = await updateVendorInfo(values);
    //   if (updateResponse?.data?.success) {
    //     setToastMsg("Info updated successfully!");
    //     setToastType("success");
    //     getVendorInfo();
    //   }

    //   setSubmitting(false);
    // } catch (err) {
    //   setToastMsg("Info update failed!");
    //   setToastType("error");
    //   setSubmitting(false);
    // }
  };

  return (
    <>
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
      >
        <Box sx={style}>
          {/* header */}
          <Typography
            variant="h6"
            component="h2"
            textAlign={"center"}
            fontWeight={600}
            fontSize={"26px"}
            sx={{
              px: 1,
              py: 2,
            }}
          >
            {title}
          </Typography>
          <Divider sx={{ borderColor: "#aaa" }} />
          {/* body */}
          <Box
            sx={{
              px: 1,
              py: 2,
              maxHeight: "calc(100vh - 150px)",
              overflowY: "auto",
            }}
          >
            {/* form start */}
            <Formik
              initialValues={{ status: null }}
              validationSchema={validationSchema}
              onSubmit={(values, { setSubmitting }) =>
                handleSubmitForm(values, setSubmitting)
              }
              innerRef={formikRef}
            >
              {({
                values,
                errors,
                touched,
                handleChange,
                handleBlur,
                handleSubmit,
                isSubmitting,
                setFieldValue,
              }) => (
                <Box
                  component="form"
                  noValidate
                  autoComplete="off"
                  p={2}
                  onSubmit={handleSubmit}
                >
                  <Grid container spacing={2}>
                    {ProductManageFields.map((field, i) => {
                      if (field?.type === "select") {
                        return (
                          <Grid item md={6} xs={12} key={i}>
                            <SelectFieldCommon
                              name={field?.name}
                              options={field?.options}
                              label={field?.label}
                              isRequired={field?.required}
                            />
                          </Grid>
                        );
                      }
                      return (
                        <Grid item md={6} xs={12} key={i}>
                          <TextFieldCommon
                            id={field.id}
                            label={field.label}
                            variant={"outlined"}
                            type={field.type}
                            name={field.name}
                            requiredStatus={field.required}
                            disabledStatus={field.disabled ?? false}
                            value={values[field.name]}
                            onchangeInputValue={handleChange}
                          />
                          <Typography component={"span"} color={"primary.main"}>
                            {errors[field.name] &&
                              touched[field.name] &&
                              errors[field.name]}
                          </Typography>
                        </Grid>
                      );
                    })}
                  </Grid>
                </Box>
              )}
            </Formik>
          </Box>
          {/* footer */}
          <Divider sx={{ borderColor: "#aaa" }} />
          <Box
            display={"flex"}
            justifyContent={"end"}
            gap={1}
            sx={{
              px: 1,
              py: 2,
            }}
          >
            <Button variant="outlined" color="secondary" onClick={handleClose}>
              Cancel
            </Button>
            <Button
              type="submit"
              variant="outlined"
              color="success"
              onClick={handleSubmit}
            >
              Update
            </Button>
          </Box>
        </Box>
      </Modal>
    </>
  );
};

export default ManageProductForm;
