import React, { useState } from "react";
import {
  Grid,
  Card,
  Typography,
  TextField,
  Button,
  Box,
  IconButton,
  MenuItem,
} from "@mui/material";
import SaveAltIcon from "@mui/icons-material/SaveAlt";
import CloseIcon from "@mui/icons-material/Close";
import { useFormik } from "formik";
import * as yup from "yup";
import { useStyles } from "../../../theme/appStyles";
import CircularProgress from "@mui/material/CircularProgress";
import { useNotifier } from "../../../Core/Notifier";
import axios from "axios";
import { useNavigate } from 'react-router-dom';
import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { uploadImage } from "../../../Components/UploadFile/upload";
import dayjs, { Dayjs } from "dayjs";

const ProjectForm = () => {
  const API_URL = process.env.REACT_APP_API_URL;
  const classes = useStyles();
  const [loading, setLoading] = useState(false);
  const { showErrorMessage, showMessage } = useNotifier();
  const navigate = useNavigate();
  const [selectedImage, setSelectedImage] = useState<File | undefined>(undefined);
  const [isImageUploading, setIsImageUploading] = useState(false);


  const formik = useFormik({
    initialValues: {
     projectName:  "",
          // customerId:  null,
          projectStatus: "",
          projectType: "",
          projectDomainName:  "",
          projectPhoneNumber:  "",
          projectEmail: "",
          projectProvince:"",
          projectCity:"",
          projectPostalCode:"",
          projectStreetNumber:"",
          projectStreetName:"",
          projectStartDate:  null,
          projectEstimatedEndDate:  null,
          projectImg: "",
          projectDescription:  "",
        },
    validationSchema: yup.object({
      projectName: yup
        .string()
        .required("Project name is required")
        .max(50, "Project name must not exceed 50 characters"),
    }),
    onSubmit: async (values) => {
      setLoading(true);
     
        try {
          const formData = new FormData();
         let projectImg: string | undefined;

        if (selectedImage) {
          setIsImageUploading(true);
          // formData.append("projectImg", selectedImage);
          projectImg = (await uploadImage(selectedImage)) || "";
          setIsImageUploading(false);
        }

          formData.append("projectName", values.projectName || "");  
          formData.append("projectType", values.projectType || "");
          formData.append("projectStatus", values.projectStatus || "");
    formData.append("projectDomainName", values.projectDomainName || "");
    formData.append("projectPhoneNumber", values.projectPhoneNumber || "");
    formData.append("projectEmail", values.projectEmail || "");
    formData.append("projectProvince", values.projectProvince || "");
    formData.append("projectCity", values.projectCity || "");
    formData.append("projectPostalCode", values.projectPostalCode || "");
    formData.append("projectStreetNumber", values.projectStreetNumber || "");
    formData.append("projectStreetName", values.projectStreetName || "");
   formData.append("projectStartDate",
  values?.projectStartDate ? dayjs(values.projectStartDate).format("YYYY-MM-DD") : "");
 formData.append("projectEstimatedEndDate",
  values?.projectEstimatedEndDate ? dayjs(values.projectEstimatedEndDate).format("YYYY-MM-DD") : "");
   
    formData.append("projectImg", projectImg || "");
    formData.append("projectDescription", values.projectDescription || "");

      
          const response = await axios.post(`${API_URL}/save-project`, formData, {
            headers: {
               Authorization: `Bearer ${localStorage.getItem("token") || ""}`,
            },
          });
       if (response.status === 422) {
       }

            showMessage("Project saved successfully!");
            formik.resetForm();
            navigate("/project/list");
         
        } catch (error: any) {
          if (error.response && error.response.status === 422) {
    showErrorMessage(error.response.data.message);
  } else {
    showErrorMessage("An error occurred while saving the project.");
  }
        } finally {
          setLoading(false);
        }
      }
  });

 const resizeImage = (
    file: File,
    maxWidth: number,
    maxHeight: number
  ): Promise<File> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);

      reader.onload = (event) => {
        const img = new Image();
        img.src = event.target?.result as string;

        img.onload = () => {
          const canvas = document.createElement("canvas");
          const ctx = canvas.getContext("2d");

          let width = img.width;
          let height = img.height;

          // Calculate the new dimensions while maintaining aspect ratio
          if (width > height) {
            if (width > maxWidth) {
              height *= maxWidth / width;
              width = maxWidth;
            }
          } else {
            if (height > maxHeight) {
              width *= maxHeight / height;
              height = maxHeight;
            }
          }

          canvas.width = width;
          canvas.height = height;
          ctx?.drawImage(img, 0, 0, width, height);

          canvas.toBlob((blob) => {
            if (blob) {
              const resizedFile = new File([blob], file.name, {
                type: file.type,
              });
              resolve(resizedFile);
            } else {
              reject(new Error("Canvas is empty"));
            }
          }, file.type);
        };

        img.onerror = (error) => reject(error);
      };
    });
  };



  const handleImageChange = async (
      event: React.ChangeEvent<HTMLInputElement>
    ) => {
      const files = event.target.files;
  
      if (files && files.length > 0) {
        const file = files[0];
        const validTypes = ["image/jpeg", "image/png", "image/jpg", "image/gif"];
        const maxSize = 2048 * 1024;
  
        if (!validTypes.includes(file.type)) {
          showErrorMessage("The file must be an image (jpeg, png, jpg, gif).");
          setSelectedImage(undefined);
        } else if (file.size > maxSize) {
          showErrorMessage("The file must be smaller than 2 MB.");
          setSelectedImage(undefined);
        } else {
          try {
            const resizedImage = await resizeImage(file, 500, 500);
            setSelectedImage(resizedImage);
          } catch (error) {
            showErrorMessage("Failed to resize the image.");
            setSelectedImage(undefined);
          }
        }
      } else {
        setSelectedImage(undefined);
      }
    };
  

  return (  
    <div>
      <Grid container spacing={3}>
        <Grid item lg={3} md={3} sm={12} xs={12}>
          <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}>
                    Create Project
                  </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}>
                                       Project Information
                                    </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">
                              Project Name
                            </Typography>
                          </Grid>
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                            <TextField
                              placeholder="Enter Project Name"
                              size="small"
                              {...formik.getFieldProps("projectName")}
                               error={
                          formik.touched.projectName &&
                          Boolean(formik.errors.projectName)
                        }
                        helperText={
                          formik.touched.projectName &&
                          formik.errors.projectName
                        }
                              className={classes.textField}
                              InputProps={{
                                sx: {
                                  fontSize: 14,
                                },
                              }}
                              InputLabelProps={{
                                sx: {
                                  fontSize: 14,
                                },
                              }}
                            />
                          </Grid>
                        </Grid>
                      </Grid>


           <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">
                              Project Status
                            </Typography>
                          </Grid>
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                          <TextField
                            select
                            size="small"
                            className={classes.textField}
                            SelectProps={{
                              native: false,
                            }}
                            defaultValue=""
                            InputLabelProps={{ shrink: true }}
                            {...formik.getFieldProps("projectStatus")}
                          >
                            <MenuItem value="" disabled>
                              Select an option
                            </MenuItem>
                            <MenuItem value="1">Ongoing</MenuItem>
                            <MenuItem value="2">Pending</MenuItem>
                            <MenuItem value="3">Done</MenuItem>
                           
                          </TextField>
                        </Grid>



                          
                        </Grid>
                      </Grid>
          
                     
                      <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">
                              Mobile Number
                            </Typography>
                          </Grid>
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                            <TextField
                              placeholder="Enter Mobile Number"
                              size="small"
                              {...formik.getFieldProps("projectPhoneNumber")}
                              className={classes.textField}
                              InputProps={{
                                sx: {
                                  fontSize: 14,
                                },
                              }}
                              InputLabelProps={{
                                sx: {
                                  fontSize: 14,
                                },
                              }}
                              error={
                                formik.touched.projectPhoneNumber &&
                                Boolean(formik.errors.projectPhoneNumber)
                              }
                              helperText={
                                formik.touched.projectPhoneNumber &&
                                formik.errors.projectPhoneNumber
                              }
                            />
                          </Grid>
                        </Grid>
                      </Grid>
                      <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">E-mail</Typography>
                          </Grid>
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                            <TextField
                              placeholder="Enter E-mail"
                              size="small"
                              {...formik.getFieldProps("projectEmail")}
                              className={classes.textField}
                              InputProps={{
                                sx: {
                                  fontSize: 14,
                                },
                              }}
                              InputLabelProps={{
                                sx: {
                                  fontSize: 14,
                                },
                              }}
                              error={
                                formik.touched.projectEmail &&
                                Boolean(formik.errors.projectEmail)
                              }
                              helperText={
                                formik.touched.projectEmail &&
                                formik.errors.projectEmail
                              }
                            />
                          </Grid>
                        </Grid>
                      </Grid>
                      <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">
                              Start Date
                            </Typography>
                          </Grid>
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                            <LocalizationProvider dateAdapter={AdapterDayjs}>
                              <DatePicker
                                value={formik.values.projectStartDate}
                                onChange={(date) =>
                                  formik.setFieldValue("projectStartDate", date)
                                }
                                slotProps={{
                                  textField: {
                                    size: "small",
                                    sx: { width: "100%" },
                                    InputProps: {
                                      sx: { fontSize: 14 },
                                    },
                                    InputLabelProps: {
                                      sx: { fontSize: 14 },
                                    },
                                  },
                                }}
                              />
                            </LocalizationProvider>
                          </Grid>
                        </Grid>
                      </Grid>
                      <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">
                              Estimated End date
                            </Typography>
                          </Grid>
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                            <LocalizationProvider dateAdapter={AdapterDayjs}>
                              <DatePicker
                                value={formik.values.projectEstimatedEndDate}
                                onChange={(date) =>
                                  formik.setFieldValue(
                                    "projectEstimatedEndDate",
                                    date
                                  )
                                }
                                slotProps={{
                                  textField: {
                                    size: "small",
                                    sx: { width: "100%" },
                                    InputProps: {
                                      sx: { fontSize: 14 },
                                    },
                                    InputLabelProps: {
                                      sx: { fontSize: 14 },
                                    },
                                  },
                                }}
                              />
                            </LocalizationProvider>
                          </Grid>
                        </Grid>
                      </Grid>
                      {/* <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">
                              Proposal date
                            </Typography>
                          </Grid>
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                            <LocalizationProvider dateAdapter={AdapterDayjs}>
                              <DatePicker
                                value={formik.values.projectProposalDate}
                                onChange={(date) =>
                                  formik.setFieldValue(
                                    "projectProposalDate",
                                    date
                                  )
                                }
                                slotProps={{
                                  textField: {
                                    size: "small",
                                    sx: { width: "100%" },
                                    InputProps: {
                                      sx: { fontSize: 14 },
                                    },
                                    InputLabelProps: {
                                      sx: { fontSize: 14 },
                                    },
                                  },
                                }}
                              />
                            </LocalizationProvider>
                          </Grid>
                        </Grid>
                      </Grid> */}
                      <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">
                              Project Domain Name
                            </Typography>
                          </Grid>
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                            <TextField
                              placeholder="Enter project Domain Name"
                              size="small"
                              {...formik.getFieldProps("projectDomainName")}
                              className={classes.textField}
                              InputProps={{
                                sx: {
                                  fontSize: 14,
                                },
                              }}
                              InputLabelProps={{
                                sx: {
                                  fontSize: 14,
                                },
                              }}
                            />
                          </Grid>
                        </Grid>
                      </Grid>


<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">
                              Project Type
                            </Typography>
                          </Grid>
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                          <TextField
                            select
                            size="small"
                            className={classes.textField}
                            SelectProps={{
                              native: false,
                            }}
                            defaultValue=""
                            InputLabelProps={{ shrink: true }}
                            {...formik.getFieldProps("projectType")}
                          >
                            <MenuItem value="" disabled>
                              Select an option
                            </MenuItem>
                            <MenuItem value="1">Software Development</MenuItem>
                            <MenuItem value="2">Website Design & Development</MenuItem>
                            <MenuItem value="3">SEO</MenuItem>
                            <MenuItem value="4">Mobile App</MenuItem>
                            <MenuItem value="5">Flyers & Designs</MenuItem>
                            <MenuItem value="6">Other</MenuItem>
                              
                           
                          </TextField>
                        </Grid>



                          
                        </Grid>
                      </Grid>

                      {/* <Grid item lg={12} md={12} sm={12} xs={12}>
                        <Grid container alignItems="center">
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                            <Typography variant="subtitle1">Address</Typography>
                          </Grid>
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                            <TextField
                              placeholder="Enter Address .."
                              size="small"
                              multiline
                              rows={3}
                              {...formik.getFieldProps("projectAddress")}
                              className={classes.discriptionTextField}
                              InputProps={{
                                sx: {
                                  fontSize: 14,
                                },
                              }}
                              InputLabelProps={{
                                sx: {
                                  fontSize: 14,
                                },
                              }}
                            />
                          </Grid>
                        </Grid>
                      </Grid> */}

                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <Grid container alignItems="center">
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                            <Typography variant="subtitle1">
                              Description
                            </Typography>
                          </Grid>
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                            <TextField
                              placeholder="Enter Description .."
                              size="small"
                              multiline
                              rows={8}
                              {...formik.getFieldProps("projectDescription")}
                              className={classes.discriptionTextField}
                              InputProps={{
                                sx: {
                                  fontSize: 14,
                                },
                              }}
                              InputLabelProps={{
                                sx: {
                                  fontSize: 14,
                                },
                              }}
                            />
                          </Grid>
                        </Grid>
                      </Grid>
                    </Grid>
                  </Card>
                </Grid>


                <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}>
                       Address
                    </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">
                           Street No.
                        </Typography>
                      </Grid>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <TextField
                          placeholder="Enter Street No."
                          size="small"
                          {...formik.getFieldProps("projectStreetNumber")}
                          className={classes.textField}
                          InputProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                        />
                      </Grid>
                    </Grid>
                  </Grid>

                  <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">
                           Street Name
                        </Typography>
                      </Grid>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <TextField
                          placeholder="Enter Street Name"
                          size="small"
                          {...formik.getFieldProps("projectStreetName")}
                          className={classes.textField}
                          InputProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                        />
                      </Grid>
                    </Grid>
                  </Grid>

                <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">
                           City
                        </Typography>
                      </Grid>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <TextField
                          placeholder="Enter City"
                          size="small"
                          {...formik.getFieldProps("projectCity")}
                          className={classes.textField}
                          InputProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                        />
                      </Grid>
                    </Grid>
                  </Grid>

                  <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">
                           Province
                        </Typography>
                      </Grid>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <TextField
                          placeholder="Enter Province"
                          size="small"
                          {...formik.getFieldProps("projectProvince")}
                          className={classes.textField}
                          InputProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                        />
                      </Grid>
                    </Grid>
                  </Grid>

              

                  <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">
                           Postal Code
                        </Typography>
                      </Grid>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <TextField
                          placeholder="Enter Postal Code"
                          size="small"
                          {...formik.getFieldProps("projectPostalCode")}
                          className={classes.textField}
                          InputProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                        />
                      </Grid>
                    </Grid>
                  </Grid>

                  
                </Grid>
              </Card>
            </Grid>


                <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}>
                          Upload Image
                        </Typography>
                      </Grid>
                    </Grid>

                    <Grid container spacing={2} p={"24px"}>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                      <Box className={classes.imgBox}>
                        {selectedImage && (
                          <img
                            src={URL.createObjectURL(selectedImage)}
                            alt="Uploaded"
                            className={classes.SelectImageBox}
                          />
                        )}
                        <div>
                          <input
                            accept="image/*"
                            style={{ display: "none" }}
                            id="icon-button-file-1"
                            type="file"
                            onChange={handleImageChange}
                          />
                          <div
                            style={{
                              textAlign: "center",
                            }}
                          >
                            <label htmlFor="icon-button-file-1">
                              <IconButton
                                color="primary"
                                aria-label="upload picture"
                                component="span"
                              >
                                <CloudUploadIcon sx={{ fontSize: 45 }} />
                              </IconButton>
                            </label>
                          </div>
                        </div>
                      </Box>
                      </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={() =>navigate('/project/list')}
                        >
                          Cancel
                        </Button>
                        <Box m={0.5}></Box>
                        <Button
                        variant="contained"
                        className={classes.addButton}
                        startIcon={<SaveAltIcon />}
                        type="submit"
                        disabled={loading}
                      >
                        {loading ? (
                          <CircularProgress size={24} />
                        ) : (
                          "Submit"
                        )}
                         </Button>
                      </Grid>
                    </Grid>
                  </Card>
                </Grid>
              </Grid>
            </form>
        </Grid>
      </Grid>
    </div>
  );
};

export default ProjectForm;
