import React, { useEffect, useMemo, useState } from "react";
import {
  Box,
  Button,
  Card,
  Checkbox,
  Dialog,
  FormControlLabel,
  FormHelperText,
  Grid,
  IconButton,
  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 {
  useGetSelectorWorkOrderByCustomerProjectQuery,
  useUpdateWorkOrderByCustomerProjectMutation,
} from "../../../Api/attoDeskApi";
import { useNotifier } from "../../../Core/Notifier";
import {
  ICustomer,
  ICustomerProject,
  ICustomerTransaction,
  IQuoteWorkOrder,
} from "../../../Api/Interface/api.interface";
import { useStyles } from "../../../theme/appStyles";
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";
import { validatePhoneNumber } from "../../../Components/Validation/validationUtils";
import { uploadPDF } from "../../../Components/UploadPdf/fillPDF";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";

interface IProjectWorkOrderpopup {
  openModel?: boolean;
  handleCloseDialog: (close: boolean) => void;
  data?: IQuoteWorkOrder;
  quoteWorkOrderCustomerId?: string;
  quoteWorkOrderCustomerProjectId?: string;
}

const CustomerProject = ({
  openModel = false,
  handleCloseDialog,
  data,
  quoteWorkOrderCustomerId,
  quoteWorkOrderCustomerProjectId,
}: IProjectWorkOrderpopup) => {
  const classes = useStyles();
  const [open] = React.useState(openModel);
  const [newCustomer, { isLoading }] =
    useUpdateWorkOrderByCustomerProjectMutation();
  const { showErrorMessage, showMessage } = useNotifier();
  const [error, setError] = useState<string | null>(null);
  const handleClose = () => {
    handleCloseDialog(false);
  };
  const [selectedPdf, setSelectedPdf] = useState<File | undefined>(undefined);
  const [isPdfUploading, setIsPdfUploading] = useState(false);

  const {
    data: workOrderProjectData,
    isLoading: workOrderProjectDataIsLoading,
    refetch: workOrderProjectRefetch,
  } = useGetSelectorWorkOrderByCustomerProjectQuery({
    quoteWorkOrderCustomerId: String(quoteWorkOrderCustomerId),
  });

  const WorkOrderList = useMemo(() => {
    return workOrderProjectData?.data as IQuoteWorkOrder[];
  }, [workOrderProjectData?.data]);

  const formik = useFormik({
    initialValues: {
      id: "",
      quoteWorkOrderCustomerId: quoteWorkOrderCustomerId,
      quoteWorkOrderCustomerProjectId: quoteWorkOrderCustomerProjectId,
    },
    enableReinitialize: true,

    onSubmit: async (values) => {
      try {
        const temData = {
          id: values.id,
          quoteWorkOrderCustomerId: values.quoteWorkOrderCustomerId,
          quoteWorkOrderCustomerProjectId:
            values.quoteWorkOrderCustomerProjectId,
        };

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

  const handlePdfChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.currentTarget.files?.[0];
    if (file && file.type === "application/pdf") {
      setSelectedPdf(file);
    } else {
      showErrorMessage("Please select a valid PDF file");
    }
  };

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

  return (
    <Dialog
      open={open}
      PaperProps={{
        style: {
          maxWidth: "1700px",
          //   minWidth: "1000px",
        },
      }}
    >
      <Grid className={classes.Dialog}>
        <Grid container spacing={3}>
          <Grid item lg={3} md={3} sm={12} xs={12}>
            <Card className={classes.stepperCard}>
              <Grid
                container
                justifyContent={"space-between"}
                spacing={5}
                sx={{ borderBottom: 2, padding: 2 }}
                className={classes.titleGrid}
              >
                <Grid
                  item
                  lg={12}
                  md={12}
                  sm={12}
                  xs={12}
                  pt={2}
                  alignContent={"center"}
                >
                  <Typography className={classes.cardTitle}>
                    Assign Work Order
                  </Typography>
                </Grid>
              </Grid>
            </Card>
          </Grid>
          <Grid item lg={9} md={9} sm={12} xs={12}>
            <form onSubmit={formik.handleSubmit}>
              <Grid container spacing={3}>
                <Grid item lg={12} md={12} sm={12} xs={12}>
                  <Card className={classes.card}>
                    <Grid
                      container
                      justifyContent={"space-between"}
                      spacing={5}
                      sx={{ borderBottom: 2, padding: 2 }}
                      className={classes.titleGrid}
                    >
                      <Grid
                        item
                        lg={12}
                        md={12}
                        sm={12}
                        xs={12}
                        pt={2}
                        alignContent={"center"}
                      >
                        <Typography className={classes.cardTitle}>
                          Assign Work Order
                        </Typography>
                      </Grid>
                    </Grid>

                    <Grid container spacing={3} p={"24px"}>
                      <Grid item lg={6} md={6} sm={12} xs={12}>
                        <Grid container alignItems="center">
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                            <Typography variant="subtitle1">
                              Work Order
                            </Typography>
                          </Grid>
                          <Grid item lg={10.5} md={10.5} sm={10.5} xs={10.5}>
                            <TextField
                              select
                              size="small"
                              className={classes.textField}
                              defaultValue=""
                              InputLabelProps={{ shrink: true }}
                              {...formik.getFieldProps("id")}
                            >
                              <MenuItem
                                value=""
                                disabled
                                style={{ color: "gray" }}
                              >
                                Select an option
                              </MenuItem>
                              {WorkOrderList &&
                                WorkOrderList.map((workOrder) => (
                                  <MenuItem
                                    key={workOrder.id}
                                    value={workOrder.id}
                                  >
                                    {workOrder.quoteWorkOrderNo}
                                  </MenuItem>
                                ))}
                            </TextField>
                          </Grid>
                        </Grid>
                      </Grid>
                    </Grid>
                  </Card>
                </Grid>

                <Grid item lg={12} md={12} sm={12} xs={12} pt={3}>
                  <Card className={classes.card}>
                    <Grid container spacing={3} p={"24px"}>
                      <Grid
                        item
                        lg={12}
                        md={12}
                        sm={12}
                        xs={12}
                        sx={{ display: "flex", justifyContent: "flex-end" }}
                      >
                        <Button
                          variant="outlined"
                          startIcon={<CloseIcon />}
                          className={classes.addButton}
                          onClick={handleClose}
                        >
                          Cancel
                        </Button>
                        <Box m={0.5}></Box>

                        <Button
                          variant="contained"
                          startIcon={<SaveAltIcon />}
                          className={classes.addButton}
                          onClick={() => formik.handleSubmit()}
                          disabled={!formValid || isLoading}
                        >
                          Save
                        </Button>
                      </Grid>
                    </Grid>
                  </Card>
                </Grid>
              </Grid>
            </form>
          </Grid>
        </Grid>
      </Grid>
    </Dialog>
  );
};

export default CustomerProject;
