import React, { useMemo } from "react";
import {
  Box,
  Button,
  Card,
  Dialog,
  Grid,
  TextField,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import SaveAltIcon from "@mui/icons-material/SaveAlt";
import CloseIcon from "@mui/icons-material/Close";
import { useCreateCustomerMutation } from "../../../Api/attoDeskApi";
import { useNotifier } from "../../../Core/Notifier";
import { ICustomer } from "../../../Api/Interface/api.interface";
import { useStyles } from "../../../theme/styles";

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

const Customer = ({ openModel = false, handleCloseDialog, data }: ITaxpopup) => {
  const classes = useStyles();
  const [open] = React.useState(openModel);
  const [newCustomer, { isLoading }] = useCreateCustomerMutation();
  const { showErrorMessage, showMessage } = useNotifier();
  const handleClose = () => {
    handleCloseDialog(false);
  };

  const validateEmail = (value: string) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(value);
  };

  const formik = useFormik({
    initialValues: {
      id: data?.id,
      customerFirstName: data?.customerFirstName,
      customerLastName: data?.customerLastName,
      customerMobileNum: data?.customerMobileNum,
      customerEmail: data?.customerEmail,
      customerAddress: data?.customerAddress,
      customerDescription: data?.customerDescription,
    },
    onSubmit: async (values) => {
      try {

        if (!validateEmail(values.customerEmail || '')) {
          showErrorMessage('Please enter a valid email address.');
          return;
        }

        const temData = {
          id: values?.id,
          customerFirstName: values.customerFirstName,
          customerLastName: values.customerLastName,
          customerMobileNum: values.customerMobileNum,
          customerEmail: values.customerEmail,
          customerAddress: values.customerAddress,
          customerDescription: values.customerDescription,
        };
        if (!data) {
          delete values.id;
        }

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

  const formValid = useMemo(() => {
    return formik.values.customerMobileNum === "" ||
      formik.values.customerMobileNum === undefined
      ? false
      : true;
  }, [formik]);

  return (
    <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 Customer
                  </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}
                      >
                        First Name
                      </Typography>
                    </Grid>
                    <Grid item lg={9} md={9} sm={12} xs={12}>
                      <TextField
                        placeholder="Enter First Name"
                        size="small"
                        {...formik.getFieldProps("customerFirstName")}
                        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}
                      >
                        Last Name
                      </Typography>
                    </Grid>
                    <Grid item lg={9} md={9} sm={12} xs={12}>
                      <TextField
                        placeholder="Enter Last Name"
                        size="small"
                        {...formik.getFieldProps("customerLastName")}
                        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}
                      >
                        Mobile Number
                      </Typography>
                    </Grid>
                    <Grid item lg={9} md={9} sm={12} xs={12}>
                      <TextField
                        placeholder="Enter Mobile Number"
                        size="small"
                        {...formik.getFieldProps("customerMobileNum")}
                        sx={{ width: "100%" }}
                        type="number"
                        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}
                      >
                        E-mail
                      </Typography>
                    </Grid>
                    <Grid item lg={9} md={9} sm={12} xs={12}>
                      <TextField
                        placeholder="Enter E-mail"
                        size="small"
                        type="email"
                        {...formik.getFieldProps("customerEmail")}
                        sx={{ width: "100%" }}
                        InputProps={{
                          sx: {
                            fontSize: 14,
                          },
                        }}
                        InputLabelProps={{
                          sx: {
                            fontSize: 14,
                          },
                        }}
                        error={
                          formik.touched.customerEmail &&
                          (!validateEmail(formik.values.customerEmail || '') ||
                            formik.values.customerEmail?.length === 0)
                        }
                        helperText={
                          (formik.touched.customerEmail &&
                            (!validateEmail(formik.values.customerEmail || '') ||
                              formik.values.customerEmail?.length === 0)) &&
                              <span style={{ textTransform: 'none' }}>
                                Please enter valid email id.
                              </span>
                        }
                      />
                    </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}
                      >
                        Address
                      </Typography>
                    </Grid>
                    <Grid item lg={9} md={9} sm={12} xs={12}>
                      <TextField
                        placeholder="Enter Address"
                        size="small"
                        {...formik.getFieldProps("customerAddress")}
                        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}
                      >
                        Description
                      </Typography>
                    </Grid>
                    <Grid item lg={9} md={9} sm={12} xs={12}>
                      <TextField
                        placeholder="Enter Description"
                        size="small"
                        multiline
                        rows={3}
                        {...formik.getFieldProps("customerDescription")}
                        sx={{ width: "100%" }}
                        InputProps={{
                          sx: {
                            fontSize: 14,
                          },
                        }}
                        InputLabelProps={{
                          sx: {
                            fontSize: 14,
                          },
                        }}
                      />
                    </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>
  );
};

export default Customer;
