import React, { useMemo, useState } from "react";
import {
  Box,
  Button,
  Card,
  Dialog,
  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 { appColor } from "../../../theme/appColor";
import { IDepartment, IPrinter } from "../../../Api/Interface/api.interface";
import NewPrinter from "../../Printer/Components/NewPopUpPrinter";
import AddIcon from "@mui/icons-material/Add";
import { useStyles } from "../../../theme/styles";

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

const Department = ({
  openModel = false,
  handleCloseDialog,
  data,
}: IDepartmentPopUp) => {
  const classes = useStyles();
  const [open] = React.useState(openModel);
  const [newDepartment, { isLoading }] = useCreateDepartmentMutation();
  const { showErrorMessage, showMessage } = useNotifier();
  const [openPrinter, setOpenPrinter] = useState(false);
  const { data: printerData, isLoading: printerLoading } = useGetPrinterQuery({
    searchText: "",
  });

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

  const handleClose = () => {
    handleCloseDialog(false);
  };

  const formik = useFormik({
    initialValues: {
      id: data?.id,
      departmentName: data?.departmentName,
      description: data?.description,
      DepartmentPrinterIds: data?.DepartmentPrinterIds,
    },
    onSubmit: async (values) => {
      try {
        const temData = {
          id: values?.id,
          departmentName: values.departmentName,
          description: values.description,
          DepartmentPrinterIds: values.DepartmentPrinterIds,
        };
        if (!data) {
          delete values.id;
        }

        const addCompanyResponse = await newDepartment(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.departmentName === "" ||
      formik.values.departmentName === undefined
      ? false
      : true;
  }, [formik]);

  return (
    <form onSubmit={formik.handleSubmit}>
      <Dialog open={open}>
        <Grid container>
          <Grid item lg={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={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>

      {openPrinter && (
        <NewPrinter
          handleCloseDialog={() => setOpenPrinter(false)}
          openModel={openPrinter}
        />
      )}
    </form>
  );
};

export default Department;
