import React, { useEffect, useMemo, useState } from "react";
import {
  Box,
  Button,
  Card,
  Checkbox,
  Dialog,
  FormControlLabel,
  FormHelperText,
  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 { useCreateCustomerTransactionMutation } from "../../../Api/attoDeskApi";
import { useNotifier } from "../../../Core/Notifier";
import {
  ICustomer,
  ICustomerTransaction,
} from "../../../Api/Interface/api.interface";
import { useStyles } from "../../../theme/styles";
import {
  CollectionType,
  ReminderMedianType,
  TableColumnTypeLevel,
  TransactionCollectionDate,
} from "../../../Core/Enum/enum";
import {
  DatePicker,
  DateTimePicker,
  LocalizationProvider,
  renderTimeViewClock,
} from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import dayjs, { Dayjs } from "dayjs";
import CustomSwitch from "../../../Components/Switch/CustomSwitch";

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

const Customer = ({
  openModel = false,
  handleCloseDialog,
  data,
  customerId,
}: ITaxpopup) => {
  const classes = useStyles();
  const [open] = React.useState(openModel);
  const [newCustomer, { isLoading }] = useCreateCustomerTransactionMutation();
  const { showErrorMessage, showMessage } = useNotifier();
  const [error, setError] = useState<string | null>(null);
  const handleClose = () => {
    handleCloseDialog(false);
  };

  const formik = useFormik({
    initialValues: {
      id: data?.id,
      transactionName: data?.transactionName || "",
      customerId: data?.customerId || customerId,
      transactionAmount: data?.transactionAmount,
      transactionDescription: data?.transactionDescription || "",
      transactionCollection: data?.transactionCollection || "",
      transactionCollectionDate: data?.transactionCollection
      ? data.transactionCollection === CollectionType.Custom
        ? dayjs(data.transactionCollectionDate)
        : String(data.transactionCollectionDate)
      : null,
      istransactionReminder: data?.istransactionReminder || false,
      transactionReminderDate: data?.transactionReminderDate
        ? dayjs(data.transactionReminderDate)
        : null,
      transactionReminderMedia: data?.transactionReminderMedia || [],
    },
    onSubmit: async (values) => {
      try {
        const temData = {
          id: values?.id,
          transactionName: values.transactionName,
          customerId: values.customerId,
          transactionAmount: values.transactionAmount,
          transactionDescription: values.transactionDescription,
          transactionCollection: values.transactionCollection,
          transactionCollectionDate: values.transactionCollectionDate,
          istransactionReminder: values.istransactionReminder,
          transactionReminderDate: values.transactionReminderDate,
          transactionReminderMedia: values.transactionReminderMedia,
        };

        if (!data) {
          delete temData.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.transactionAmount === "" ||
      formik.values.transactionAmount === undefined ||
      formik.values.transactionName === "" ||
      formik.values.transactionName === undefined
      ? false
      : true;
  }, [formik]);

  const handleTransactionCollectionChange = (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const value = event.target.value;
    formik.setFieldValue("transactionCollection", value);

    // Reset transactionCollectionDate to null when changing transactionCollection
    if (value == CollectionType.Custom) {
      formik.setFieldValue("transactionCollectionDate", null);
    }

    if (value !== CollectionType.Custom) {
      formik.setFieldValue("transactionCollectionDate", "");
    }
  };

  const isCustomCollection =
    formik.values.transactionCollection === CollectionType.Custom;

 
  const handleCheckboxChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value;
    if (formik.values.transactionReminderMedia.includes(value)) {
      formik.setFieldValue(
        "transactionReminderMedia",
        formik.values.transactionReminderMedia.filter((item) => item !== value)
      );
    } else {
      formik.setFieldValue("transactionReminderMedia", [
        ...formik.values.transactionReminderMedia,
        value,
      ]);
    }
  };

  return (
    <form onSubmit={formik.handleSubmit}>
      <Dialog
        open={open}
        PaperProps={{
          style: {
            maxWidth: "1700px",
          },
        }}
      >
        <Grid container>
          <Grid item lg={12} md={12} sm={12} xs={12} className={classes.grid1}>
            <Card
              sx={{
                p: 2,
                width: "100%",
                boxShadow: "none",
                pb: 2,
              }}
            >
              <Grid container spacing={5}>
                <Grid
                  item
                  lg={12}
                  md={12}
                  sm={12}
                  xs={12}
                  sx={{ borderBottom: 1 }}
                  className={classes.cardTitleGrid}
                >
                  <Typography className={classes.cardTitleTypography}>
                    New Customer Transaction
                  </Typography>
                </Grid>
                <Grid item lg={6} md={6} 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 Transaction Name"
                        size="small"
                        {...formik.getFieldProps("transactionName")}
                        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}
                      >
                        Amount
                      </Typography>
                    </Grid>
                    <Grid item lg={9} md={9} sm={12} xs={12}>
                      <TextField
                        placeholder="Enter Transaction Amount"
                        size="small"
                        {...formik.getFieldProps("transactionAmount")}
                        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}
                      >
                        Collection
                      </Typography>
                    </Grid>
                    <Grid item lg={9} md={9} sm={12} xs={12}>
                      <TextField
                        select
                        size="small"
                        fullWidth
                        defaultValue=""
                        {...formik.getFieldProps("transactionCollection")}
                        onChange={handleTransactionCollectionChange}
                      >
                        {Object.entries(CollectionType).map(([key, value]) => (
                          <MenuItem key={value} value={value}>
                            {key}
                          </MenuItem>
                        ))}
                      </TextField>
                    </Grid>
                  </Grid>
                  {isCustomCollection && (
                    <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}
                        >
                          Collection Date
                        </Typography>
                      </Grid>
                      <Grid item lg={9} md={9} sm={12} xs={12}>
                        <LocalizationProvider dateAdapter={AdapterDayjs}>
                          <DatePicker
                            value={
                              formik.values.transactionCollectionDate
                                ? dayjs(formik.values.transactionCollectionDate as string | Dayjs)
                                : null
                            }
                            onChange={(date) =>
                              formik.setFieldValue(
                                "transactionCollectionDate",
                                date
                              )
                            }
                            slotProps={{
                              textField: {
                                size: "small",
                                sx: { width: "100%" },
                                InputProps: {
                                  sx: { fontSize: 14 },
                                },
                                InputLabelProps: {
                                  sx: { fontSize: 14 },
                                },
                              },
                            }}
                          />
                        </LocalizationProvider>
                      </Grid>
                    </Grid>
                  )}
                  {!isCustomCollection && (
                    <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}
                        >
                          Collection Date
                        </Typography>
                      </Grid>
                      <Grid item lg={9} md={9} sm={12} xs={12}>
                        <TextField
                          select
                          size="small"
                          sx={{ width: "100%" }}
                          SelectProps={{
                            native: false,
                            MenuProps: {
                              PaperProps: {
                                style: {
                                  maxHeight: 40 * 5,
                                },
                              },
                            },
                          }}
                          defaultValue=""
                          InputLabelProps={{ shrink: true }}
                          {...formik.getFieldProps("transactionCollectionDate")}
                        >
                          <MenuItem value="" disabled>
                            Select some option
                          </MenuItem>
                          {Object.entries(TransactionCollectionDate).map(
                            ([key, value], index) => (
                              <MenuItem key={index} value={value}>
                                {key}
                              </MenuItem>
                            )
                          )}
                        </TextField>
                      </Grid>
                    </Grid>
                  )}
                </Grid>
                <Grid item lg={6} md={6} 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}
                      >
                        Reminder
                      </Typography>
                    </Grid>
                    <Grid item lg={9} md={9} sm={12} xs={12}>
                      <CustomSwitch
                        color="primary"
                        sx={{ mr: 2 }}
                        formik={formik}
                        name="istransactionReminder"
                      />
                    </Grid>
                  </Grid>
                  {formik.values.istransactionReminder == true && (
                    <>
                      <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}
                          >
                            Reminder Date
                          </Typography>
                        </Grid>
                        <Grid item lg={9} md={9} sm={12} xs={12}>
                          <LocalizationProvider dateAdapter={AdapterDayjs}>
                            <DateTimePicker
                              value={formik.values.transactionReminderDate}
                              onChange={(date) =>
                                formik.setFieldValue(
                                  "transactionReminderDate",
                                  date
                                )
                              }
                              viewRenderers={{
                                hours: renderTimeViewClock,
                                minutes: renderTimeViewClock,
                                seconds: renderTimeViewClock,
                              }}
                              slotProps={{
                                textField: {
                                  size: "small",
                                  sx: { width: "100%" },
                                  InputProps: {
                                    sx: { fontSize: 14 },
                                  },
                                  InputLabelProps: {
                                    sx: { fontSize: 14 },
                                  },
                                },
                              }}
                            />
                          </LocalizationProvider>
                        </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}
                          >
                            Reminder Media
                          </Typography>
                        </Grid>
                        <Grid item lg={9} md={9} sm={12} xs={12}>
                          {Object.entries(ReminderMedianType).map(
                            ([key, value]) => (
                              <FormControlLabel
                                key={key}
                                control={
                                  <Checkbox
                                    value={value}
                                    checked={formik.values.transactionReminderMedia.includes(
                                      value
                                    )}
                                    onChange={handleCheckboxChange}
                                    sx={{
                                      "& .MuiSvgIcon-root": { fontSize: 22 },
                                    }}
                                  />
                                }
                                label={value}
                                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("transactionDescription")}
                        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;
