import React, { useMemo, useState } from "react";
import {
  Box,
  Button,
  Card,
  Grid,
  MenuItem,
  TextField,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import SaveAltIcon from "@mui/icons-material/SaveAlt";
import CloseIcon from "@mui/icons-material/Close";
import {
  useCreateDepartmentMutation,
  useGetPrinterQuery,
} from "../../../Api/attoDeskApi";
import { useNotifier } from "../../../Core/Notifier";
import { IPrinter } from "../../../Api/Interface/api.interface";
import NewPrinter from "../../Printer/Components/NewPopUpPrinter";
import AddIcon from "@mui/icons-material/Add";
import { useStyles } from "../../../theme/styles";

const Department: React.FC = () => {
  const classes = useStyles();
  const [newDepartment, { isLoading }] = useCreateDepartmentMutation();
  const { showErrorMessage, showMessage } = useNotifier();
  const {
    data: printerData,
    isLoading: printerLoading,
    refetch: refetchPrinters,
  } = useGetPrinterQuery({
    searchText: "",
  });
  const [openPrinter, setOpenPrinter] = useState(false);
  const [newPrinterAdded, setNewPrinterAdded] = useState(false);

  const printerList = useMemo(() => {
    return printerData?.data as IPrinter[];
  }, [printerData?.data]);

  const formik = useFormik({
    initialValues: {
      departmentName: "",
      description: "",
      DepartmentPrinterIds: [],
    },
    onSubmit: async (values, { resetForm }) => {
      try {
        const temData = {
          departmentName: values.departmentName,
          description: values.description,
          DepartmentPrinterIds: values.DepartmentPrinterIds,
        };

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

  const formValid = useMemo(() => {
    return (
      formik.values.departmentName !== "" &&
      formik.values.departmentName !== undefined
    );
  }, [formik]);

  const handlePrinterDialogClose = () => {
    setOpenPrinter(false);
    setNewPrinterAdded(true);
    refetchPrinters();
  };

  // useEffect(() => {
  //   if (newPrinterAdded && printerList && printerList.length > 0) {
  //     // Select the first printer from the updated list after adding a new printer
  //     formik.setFieldValue("DepartmentPrinterIds", [printerList[0].id]);
  //     setNewPrinterAdded(false);
  //   }
  // }, [newPrinterAdded, printerList, formik]);

  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 Department
                </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 Department Name"
                      size="small"
                      {...formik.getFieldProps("departmentName")}
                      sx={{ width: "100%" }}
                      InputProps={{
                        sx: {
                          fontSize: 14,
                        },
                      }}
                      InputLabelProps={{
                        sx: {
                          fontSize: 14,
                        },
                      }}
                    />
                  </Grid>
                </Grid>
                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Department Printers
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={9}
                    md={9}
                    sm={12}
                    xs={12}
                    display="flex"
                    alignItems="center"
                  >
                    <TextField
                      select
                      size="small"
                      sx={{ width: "100%" }}
                      SelectProps={{
                        multiple: true,
                        native: false,
                      }}
                      defaultValue={[]}
                      InputLabelProps={{ shrink: true }}
                      {...formik.getFieldProps("DepartmentPrinterIds")}
                      onChange={(event) => {
                        const {
                          target: { value },
                        } = event;
                        formik.setFieldValue(
                          "DepartmentPrinterIds",
                          typeof value === "string" ? value.split(",") : value
                        );
                      }}
                    >
                      {printerList && printerList.length > 0 ? (
                        printerList.map((printer: IPrinter) => (
                          <MenuItem key={printer.id} value={printer.id}>
                            {printer.printerName}
                          </MenuItem>
                        ))
                      ) : (
                        <MenuItem value="" disabled style={{ color: "gray" }}>
                          Select an option
                        </MenuItem>
                      )}
                    </TextField>

                    <Button
                      variant="contained"
                      size="small"
                      sx={{ ml: 2 }}
                      className={classes.addButton}
                      onClick={() => {
                        setOpenPrinter(true);
                      }}
                    >
                      <AddIcon sx={{ fontSize: 30 }} />
                    </Button>
                  </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="Description"
                      size="small"
                      {...formik.getFieldProps("description")}
                      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={() => formik.resetForm()}
                >
                  Cancel
                </Button>
                <Box m={0.5}></Box>
                <Button
                  type="submit"
                  variant="contained"
                  startIcon={<SaveAltIcon />}
                  className={classes.saveButton}
                  disabled={!formValid || isLoading}
                >
                  Save
                </Button>
              </Grid>
            </Grid>
          </Card>
        </Grid>
      </Grid>
      {openPrinter && (
        <NewPrinter
          handleCloseDialog={handlePrinterDialogClose}
          openModel={openPrinter}
        />
      )}
    </form>
  );
};

export default Department;
