"use client";

import React, { useState, useEffect, useRef } from "react";
import {
  Card,
  Box,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableFooter,
  TablePagination,
  TableRow,
  Paper,
  IconButton,
  TableHead,
  Button,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormHelperText,
  MenuItem,
  FormControl,
  InputLabel,
  Checkbox
} from "@mui/material";
import AddIcon from "@mui/icons-material/Add";
import ClearIcon from "@mui/icons-material/Clear";
import InspirationGalleryService, {GalleryInspirationOPData, GalleryInspirationByIdOPData} from "@/service/InspirationGalleryService";
import { ToastContainer, toast} from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { InspirationFormValues, InspirationValidationSchema, InpirationSectionTouchFields } from '@lib/ValidationSchemas';
import { useFormik  } from 'formik';
import TablePaginationActions from "../../Pagination";
import BootstrapDialog from "../../BootstrapModel";
import withAuth from "@/withAuth";
import routes from "@/routes";
import {RoleEnum} from '@constant/StaticData';
import {handleFetchWithTokenRefresh} from '@utils/common';
import { useCookies } from 'react-cookie';
import Image from 'next/image';
import HomeSectionService, {HomeSectionOPData} from "@/service/HomeSectionService";
import Select, { SelectChangeEvent } from "@mui/material/Select";
import { ArrowUpward, ArrowDownward  } from '@mui/icons-material';
import { Fancybox } from "@fancyapps/ui";
import "@fancyapps/ui/dist/fancybox/fancybox.css";

const Inspiration: React.FC = () => {
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [GalleryInspirationData, setGalleryInspirationData] = useState<GalleryInspirationOPData | undefined>(undefined);
  const [GalleryInspirationDataById, setGalleryInspirationDataById] = useState<GalleryInspirationByIdOPData | undefined>(undefined);
  const [open, setOpen] = useState(false);
  const [delOpen, setDelOpen] = useState(false);
  const [viewOpen, setViewOpen] = useState(false);
  const [title, setTitle] = useState("Add New");
  const [delId, setDelId] = useState(0);
  const [refId, setRefId] = useState(0);
  const [IGId, setIGId] = useState(0);
  const [changes, setChanges] = useState("");
  const [btnName, setBtnName] = useState("Create");
  const [cookies, setCookie, removeCookie] = useCookies();
  const [HomeSectionsData, setHomeSectionsData] = useState<HomeSectionOPData | undefined>(undefined);
  const fileImageInputRef = useRef<HTMLInputElement | null>(null);
  const [isPagination, setIsPagination] = useState(false);
  const [sortOrder, setSortOrder] = useState<'DESC' | 'ASC'>('DESC');
  const [isMainUpdate, setIsMainUpdate] = useState(false);
   const [houseSecId, setHouseSecId] = useState(0);

 const addData = async(values:any) =>{
    try {
      const attachment: File[] = [];
      if (values.file_image) {
          attachment.push(values.file_image);
      } 
      const InspirationGalleryFileUpload = {
        attachment,
        input:{
          ref_id : `${values.housesec_id}`,
          file_field : "FILE_IMAGE"
        }
      }
      const InspirationFileUploadData = await InspirationGalleryService.InspirationGalleryFileUpload(InspirationGalleryFileUpload);
      if(InspirationFileUploadData?.InspirationGalleryUpload && InspirationFileUploadData?.InspirationGalleryUpload?.[0]?.id > 0){

        if(values.is_cover == true){
          values.cover = new Date().toLocaleString();
          const InspirationUpdateData = await InspirationGalleryService.createInspirationGallery(values, InspirationFileUploadData?.InspirationGalleryUpload?.[0]?.id);              
          setIsMainUpdate(prevState => !prevState);
        }
        else{
          const GalleryInspirationData = await InspirationGalleryService.getInspirationGalleryById(parseInt(InspirationFileUploadData?.InspirationGalleryUpload?.[0]?.id.toString()));
          setGalleryInspirationData((prevData) => {
            if (!prevData || !prevData.InspirationGalleryFind) {
              return prevData;
            }
            const newRow = GalleryInspirationData?.InspirationGalleryFindOneById;
            if (!newRow) {
              return prevData; 
            }
            const existingRows = prevData?.InspirationGalleryFind?.rows || [];                    
            const total = prevData?.InspirationGalleryFind?.total  || 0;   
            const pages = Math.ceil(total / rowsPerPage); 
            
            return {
              ...prevData,
              InspirationGalleryFind: {
                rows: [newRow, ...existingRows],
                total: total + 1,
                pages: pages
              },
            }; 
        });
      }

      toast.success("Inserted data successfully !!", {
            position: "bottom-left",
            autoClose: 2000,
        });
      }  
    }catch (error:any) {
        console.error("Error adding data:", error);
        toast.error(error, {
          position: "bottom-left",
          autoClose: 2000,
      });
    }
  }
  
  const handleSubmit = async(values:any) =>{
    const errors = await formik.validateForm();
      formik.setTouched(InpirationSectionTouchFields);   
      if (Object.keys(errors).length === 0) {
        try {
          
          let successMsg;

          if (changes === 'Add') {
            //successMsg = "Inserted data successfully !!";
            addData(values);
            
          } else if (changes === 'Edit') {
              successMsg = "Updated data successfully !!";
                            
               if(typeof values.file_image === 'string'){
                if(values.is_cover == true){
                  values.cover = new Date().toLocaleString();
                }
                else{
                  values.cover = null
                }

                const InspirationUpdateData = await InspirationGalleryService.updateInspirationGallery(values, values.id);
                const PastWorkGalleryUpdateHouseSec = await InspirationGalleryService.updateInsirationGalleryHouseSection(values, values.id,houseSecId);
                if(InspirationUpdateData?.InspirationGalleryUpdate && InspirationUpdateData.InspirationGalleryUpdate.affected > 0){
                  if(values.is_cover == true){
                    values.cover = new Date().toLocaleString();
                    const PastWorkGalleryUpdateHouseSec = await InspirationGalleryService.updateInsirationGalleryHouseSection(values, values.id,houseSecId);
                    const InspirationUpdtData = await InspirationGalleryService.createInspirationGallery(values, values.id);
                    setIsMainUpdate(prevState => !prevState);
                  }
                  else{
                    
                    const GalleryInspirationData = await InspirationGalleryService.getInspirationGalleryById(parseInt(values.id));
          
                    setGalleryInspirationData((prevData) => {
                      if (!prevData || !prevData.InspirationGalleryFind) {
                        return prevData;
                      }
                      const newRow = GalleryInspirationData?.InspirationGalleryFindOneById;
                      if (!newRow) {
                        return prevData; 
                      }
                      const existingRows = prevData?.InspirationGalleryFind?.rows || [];                    
                      const total = prevData?.InspirationGalleryFind?.total  || 0;   
                      const pages = Math.ceil(total / rowsPerPage); 

                      const rowIndex = existingRows.findIndex(row => row.id === newRow.id);

                      if (rowIndex > -1) {
                        const updatedRows = [
                          ...existingRows.slice(0, rowIndex),  
                          newRow,  
                          ...existingRows.slice(rowIndex + 1)  
                        ];
                      
                      return {
                        ...prevData,
                        InspirationGalleryFind: {
                          rows: updatedRows,
                          total: total + 1,
                          pages: pages
                        },
                      }; 
                    }
                    });
                  }
                } 
              }
              else{
 
                const GalleryInspirationUploadData = await InspirationGalleryService.InspirationGalleryUploadDelete(GalleryInspirationDataById?.InspirationGalleryFindOneById?.housesec_id.toString() ?? "", values.id);
                
                setGalleryInspirationData((prevData) => {
                  if (!prevData || !prevData.InspirationGalleryFind) {
                      return prevData;
                  }
                  const filteredRows = (prevData.InspirationGalleryFind.rows || []).filter(item => item.id !== values.id);
                  const total = ((prevData.InspirationGalleryFind.total-1) || 0);
                  const pages = Math.ceil(total / rowsPerPage); 
                  setIGId(0);
        
                  return {
                      ...prevData,
                      InspirationGalleryFind: {
                          ...prevData.InspirationGalleryFind,
                          rows: filteredRows,
                          total: total,
                          pages: pages
                      },
                  }; 
               });
                
                if(GalleryInspirationUploadData?.InspirationGalleryUploadDelete && GalleryInspirationUploadData.InspirationGalleryUploadDelete?.[0].affected > 0){
                  await addData(values);
                }
              } 
          }
          setOpen(false);
          setIGId(0);
          toast.success(successMsg, {
              position: "bottom-left",
              autoClose: 2000,
          });
        }catch (error:any) {
          console.log('GraphQL Mutation Error:', error);
          handleFetchWithTokenRefresh(error, cookies, setCookie, handleSubmit, "Error during insert/update entry!!", values);
        }
      } 
  }

  const formik = useFormik<InspirationFormValues>({
    initialValues: {
      file_image: "",
      housesec_id: "",
      cover:"",
      housesec_name:"",
      is_cover:false
    },
    validationSchema: InspirationValidationSchema,
    onSubmit: async(values) => {
      handleSubmit(values);
    },
  });


  const fetchHomeSection = async () => {
    const homesections = await HomeSectionService.getHomeSections();
    if(homesections && homesections?.HouseSectionFind){
      setHomeSectionsData(homesections);
    }
  }

  const fileHandleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    formik.handleChange;
    const file = event.currentTarget.files?.[0] || null;
    if (file) {
      formik.setFieldValue('file_image', file); 
    } else {
      formik.setFieldValue('file_image', null); 
    }
  };

  useEffect(() => {
    fetchHomeSection();
  },[]);

  const fetchData = async () => {
    try {		
      const start = (page)*rowsPerPage;
      const GalleryInspirationData = await InspirationGalleryService.getInspirationGallery(rowsPerPage, start,sortOrder);
      if(GalleryInspirationData != undefined && GalleryInspirationData != null && GalleryInspirationData?.InspirationGalleryFind){
        setGalleryInspirationData(GalleryInspirationData);
      }
    } catch (err:any) {
      console.error('Error during fetch data:', err);
      handleFetchWithTokenRefresh(err, cookies, setCookie, fetchData, "Error during fetch data");
    }
  };

  const handleSort = async() => {
    const newSortOrder = sortOrder === 'ASC' ? 'DESC' : 'ASC';
    setSortOrder(newSortOrder);
    await fetchData(); 
  };

  useEffect(() => {
    fetchData();
  },[page, rowsPerPage, sortOrder, isMainUpdate]);

  useEffect(() => {
    if (isPagination) {
      fetchData();
      setIsPagination(false); 
    }
  }, [isPagination]);

  const fetchDataByID = async () => {
    try {		
      const GalleryInspirationIdData = await InspirationGalleryService.getInspirationGalleryById(IGId);

      if(GalleryInspirationIdData != undefined && GalleryInspirationIdData != null && GalleryInspirationIdData?.InspirationGalleryFindOneById){
        setGalleryInspirationDataById(GalleryInspirationIdData);
      }
    } catch (err:any) {
      console.error('Error during fetch data:', err);
      handleFetchWithTokenRefresh(err, cookies, setCookie, fetchDataByID, "Error during fetch data");
    }
  };

  useEffect(() => {
    if (IGId !== 0) {
      fetchDataByID();
    }
  },[IGId]);

  const setFormikValues = () => {
    if (GalleryInspirationDataById) {
      setHouseSecId(Number(GalleryInspirationDataById?.InspirationGalleryFindOneById?.fr_house_section?.id))
      formik.setValues({
        file_image: GalleryInspirationDataById?.InspirationGalleryFindOneById?.file_image_url?.thumb || "",
        housesec_id: String(GalleryInspirationDataById?.InspirationGalleryFindOneById?.fr_house_section?.id) || "",
        cover: GalleryInspirationDataById?.InspirationGalleryFindOneById?.cover || "",
        housesec_name: GalleryInspirationDataById?.InspirationGalleryFindOneById?.fr_house_section?.title || "",
        id: GalleryInspirationDataById?.InspirationGalleryFindOneById?.id || 0,
        is_cover: GalleryInspirationDataById?.InspirationGalleryFindOneById?.cover ? true : false
      });
    }
  }

  useEffect(() => {
    setFormikValues();
  }, [GalleryInspirationDataById]);

  const emptyRows =
    page > 0 ? Math.max(0, (1 + page) * rowsPerPage - (GalleryInspirationData?.InspirationGalleryFind?.total || 0)) : 0;

  const handleChangePage = (
    event: React.MouseEvent<HTMLButtonElement> | null,
    newPage: number
  ) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (
    event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  // Modal
  
  const handleClickOpen = (Title:string) => {
    setTitle(Title);
    setOpen(true);
    formik.resetForm();  
    setChanges("Add");  
    setBtnName("Create");
  };

  const handleEditOpen = (Title:string, Id:number) => {
    setTitle(Title);
    setIGId(Id);
    setOpen(true); 
    if(formik.values.housesec_id === ''){
      setFormikValues();
    }
    setChanges("Edit"); 
    setBtnName("Update");
  };
  const handleClose = () => {
    setOpen(false);
    setIGId(0);
    formik.resetForm();
  };

  const handleDelClickOpen = (Id:number, ref_id:number) => {
    setDelId(Id); 
    setRefId(ref_id); 
    setDelOpen(true);
  };
  const handleDelClose = () => {
    setDelOpen(false);
    setIGId(0);
  };

  const handleViewClickOpen = (Id:number) => {
    setViewOpen(true);
    setIGId(Id);
    if(formik.values.housesec_id === ''){
      setFormikValues();
    }
  };

  const handleViewClose = () => {
    setViewOpen(false);
    setIGId(0);
  };

  const handleDelSubmit = async() => {
    try {		
      const GalleryInspirationUploadData = await InspirationGalleryService.InspirationGalleryUploadDelete(refId.toString(), delId);
      if(GalleryInspirationUploadData && GalleryInspirationUploadData.InspirationGalleryUploadDelete?.[0]?.affected == 1){
        setGalleryInspirationData((prevData) => {
          if (!prevData || !prevData.InspirationGalleryFind) {
              return prevData;
          }
          const filteredRows = (prevData.InspirationGalleryFind.rows || []).filter(item => item.id !== delId);
          const total = ((prevData.InspirationGalleryFind.total-1) || 0);
          const pages = Math.ceil(total / rowsPerPage); 
          setIGId(0);

          if(prevData?.InspirationGalleryFind?.pages !== pages){
            setIsPagination(true);
          }

          return {
              ...prevData,
              InspirationGalleryFind: {
                  ...prevData.InspirationGalleryFind,
                  rows: filteredRows,
                  total: total,
                  pages: pages
              },
          }; 
       });
        if( GalleryInspirationUploadData.InspirationGalleryUploadDelete?.[0]?.snapshot?.error.length > 0){
            const errorMsg =  GalleryInspirationUploadData.InspirationGalleryUploadDelete?.[0]?.snapshot?.error[0]
            toast.error(errorMsg, {
              position: "bottom-left",
              autoClose: 2000,
            });
          }else{
            toast.error('Entry Deleted Successfully !!', {
              position: "bottom-left",
              autoClose: 2000,
          });
        }
        setPage(0);
        setDelOpen(false);
      }
    } catch (err:any) {
      console.error('Error during delete data:', err);
      handleFetchWithTokenRefresh(err, cookies, setCookie, handleDelSubmit, "Error during delete data");
    }
  };

  const HomeSectionChange = async(event: SelectChangeEvent<string>) => {
    formik.setFieldValue('housesec_id', event.target.value); 
  };

    useEffect(() => {
      // Initialize Fancybox
      Fancybox.bind("[data-fancybox='gallery']", {
        Carousel: {
          infinite: false,
        },
      });
  
      // Cleanup on component unmount
      return () => {
        Fancybox.destroy();
      };
    }, []);

  return (
    <>
      <Card
        sx={{
          boxShadow: "none",
          borderRadius: "7px",
          mb: "25px",
          padding: { xs: "18px", sm: "20px", lg: "25px" },
        }}
        className="rmui-card"
      >
        <Box
          sx={{
            display: { xs: "block", sm: "flex" },
            alignItems: "center",
            justifyContent: "space-between",
            mb: "25px",
            float:"right"
          }}
        >
          <Button
            onClick={() => handleClickOpen("Add New Inspiration")}
            variant="outlined"
            sx={{
              textTransform: "capitalize",
              borderRadius: "7px",
              fontWeight: "500",
              fontSize: "13px",
              padding: "6px 13px",
            }}
            color="primary"
            title="Add"
          >
            <AddIcon sx={{ position: "relative", top: "-1px" }} /> Add New
          </Button>
        </Box>

        {/* Table */}
        <Box
          sx={{
            marginLeft: "-25px",
            marginRight: "-25px",
          }}
        >
          <TableContainer
            component={Paper}
            sx={{
              boxShadow: "none",
              borderRadius: "0",
            }}
            className="rmui-table"
          >
            <Table sx={{ minWidth: 1000 }} aria-label="Offer Strength Table">
              <TableHead className="bg-primary-50">
                <TableRow>
                 

                  <TableCell
                    sx={{
                      fontWeight: "500",
                      padding: "10px 20px",
                      fontSize: "14px",
                      width:"30%"
                    }}
                    className="text-black border-bottom"
                  >
                    Image
                  </TableCell>
                  <TableCell
                    sx={{
                      fontWeight: "500",
                      padding: "10px 24px",
                      fontSize: "14px",
                      width:"30%"
                    }}
                    className="text-black border-bottom"
                  >
                     <IconButton
                          aria-label="sort"
                          color="primary"
                          sx={{ padding: "5px" }}
                          onClick={handleSort}
                        >
                          {sortOrder === 'ASC' ? (
                            <ArrowUpward sx={{ fontSize: '16px' }} />
                          ) : (
                            <ArrowDownward sx={{ fontSize: '16px' }} />
                          )}
                        </IconButton>
                        Gallery Category
                  </TableCell>

                  <TableCell
                    sx={{
                      fontWeight: "500",
                      padding: "10px 20px",
                      fontSize: "14px",
                      width:"30%"
                    }}
                    className="text-black border-bottom"
                  >
                    Category Cover Photo
                  </TableCell>

                  <TableCell
                    sx={{
                      fontWeight: "500",
                      padding: "10px 20px",
                      fontSize: "14px",
                      width:"10%",
                      textAlign:"center"
                    }}
                    className="text-black border-bottom"
                  >
                    Action
                  </TableCell>
                </TableRow>
              </TableHead>

              <TableBody>
                {GalleryInspirationData?.InspirationGalleryFind?.rows && GalleryInspirationData.InspirationGalleryFind.rows.length > 0 ? (
                GalleryInspirationData.InspirationGalleryFind.rows.map((row,i) => (
                    <TableRow key={row.id}>
                      <TableCell
                        sx={{
                          padding: "15px 20px",
                          fontSize: "14px",
                        }}
                        className="border-bottom"
                      >
                      {/*   <a
                        key={row.id}
                        href={row.file_image_url?.thumb || ""}
                        data-fancybox="gallery"
                        data-caption={"image" +"-"+(i+1)}
                        > */}
                        {row.file_image_url?.thumb && (
                          <Image
                            src={row?.file_image_url?.thumb}
                            alt="gallery"
                            width={60}
                            height={60}
                            style={{
                              borderRadius: "7px",
                            }}
                          />
                        )}
                      {/*   </a> */}
                      </TableCell>

                      <TableCell
                        sx={{
                          padding: "5px 13px",
                          fontSize: "14px",
                          width: "65px",
                        }}
                        className="border-bottom"
                      >
                      {row?.fr_house_section?.title}
                      </TableCell>

                      {/* <TableCell
                        sx={{
                          padding: "15px 20px",
                          fontSize: "14px",
                        }}
                        className="border-bottom"
                      >
                       {(() => {
                          if(row?.cover){
                            const date = new Date(row?.cover);
                            const formattedDate = date.toLocaleDateString('en-GB', {
                              day: '2-digit',   
                              month: 'long',   
                              year: 'numeric',  
                            }); 
                            return formattedDate; 
                          }
                        })()}
                      </TableCell> */}

                    <TableCell
                      sx={{
                        padding: "15px 20px",
                        fontSize: "14px",
                      }}
                      className="border-bottom"
                    >
                      {row?.cover ? "Yes" : ""}
                    </TableCell>

                      <TableCell
                        sx={{
                          padding: "15px 20px",
                        }}
                        className="border-bottom"
                      >
                        <Box
                          sx={{
                            display: "flex",
                            alignItems: "center",
                            float:"right"
                          }}
                        >
                          <IconButton
                          aria-label="view"
                          color="primary"
                          title="View"
                          sx={{ padding: "5px" }}
                          onClick={() => handleViewClickOpen(row.id)}
                          >
                          <i
                              className="material-symbols-outlined"
                              style={{ fontSize: "16px" }}
                          >
                              visibility
                          </i>
                          </IconButton>


                          <IconButton
                          aria-label="edit"
                          color="secondary"
                          title="Edit"
                          sx={{ padding: "5px" }}
                          onClick={() => handleEditOpen("Edit Inspiration", row.id)}
                          >
                          <i
                              className="material-symbols-outlined"
                              style={{ fontSize: "16px" }}
                          >
                              edit
                          </i>
                          </IconButton>
                          

                          <IconButton
                            aria-label="delete"
                            color="error"
                            title="Delete"
                            sx={{ padding: "5px" }}
                            onClick={() => handleDelClickOpen(row.id, row.housesec_id)}
                          >
                            <i
                              className="material-symbols-outlined"
                              style={{ fontSize: "16px" }}
                            >
                              delete
                            </i>
                          </IconButton>
                        </Box>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={8} align="center">
                      No data available.
                    </TableCell>
                  </TableRow>
                )}
                {emptyRows > 0 && (
                  <TableRow style={{ height: 53 * emptyRows }}>
                    <TableCell colSpan={8} />
                  </TableRow>
                )}
              </TableBody>

              <TableFooter>
                <TableRow>
                  <TablePagination
                    rowsPerPageOptions={[
                      5,
                      10,
                      25,
                      { label: "All", value: -1 },
                    ]}
                    colSpan={8}
                    count={GalleryInspirationData?.InspirationGalleryFind?.total || 0}
                    rowsPerPage={rowsPerPage}
                    page={page}
                    slotProps={{
                      select: {
                        inputProps: {
                          "aria-label": "rows per page",
                        },
                        native: true,
                      },
                    }}
                    onPageChange={handleChangePage}
                    onRowsPerPageChange={handleChangeRowsPerPage}
                    ActionsComponent={TablePaginationActions}
                    sx={{
                      border: "none",
                    }}
                  />
                </TableRow>
              </TableFooter>
            </Table>
          </TableContainer>
        </Box>
      </Card>

      {/* Modal */}
      <BootstrapDialog
        onClose={handleClose}
        aria-labelledby="customized-dialog-title"
        open={open}
        className="rmu-modal"
        PaperProps={{
            sx: { width: { xs: '100%', sm: '100%', md: '100%' }, maxWidth: '500px' }
          }}
      >
        <Box>
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              background: "#f6f7f9",
              padding: { xs: "15px 20px", md: "25px" },
            }}
            className="rmu-modal-header"
          >
            <Typography
              id="modal-modal-title"
              variant="h6"
              sx={{
                fontWeight: "600",
                fontSize: { xs: "16px", md: "18px" },
              }}
              className="text-black"
            >
              {title}
            </Typography>

            <IconButton aria-label="remove" size="small" onClick={handleClose}>
              <ClearIcon />
            </IconButton>
          </Box>

          <Box className="rmu-modal-content">
            <Box component="form" onSubmit={formik.handleSubmit}>
              <Box
                sx={{
                  padding: "25px",
                  borderRadius: "8px",
                }}
                className="bg-white"
              >
             
                <Box mb={2}>
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                      }}
                      className="text-black"
                    >
                      Gallery Category
                    </Typography>
                    
                    <FormControl fullWidth>
                        <InputLabel id="housesec_id">Gallery Category</InputLabel>
                        {HomeSectionsData?.HouseSectionFind?.rows && (
                          <Select
                            labelId="homesection-label"
                            id="housesec_id"
                            value={String(formik.values.housesec_id) || ""}
                            label="Gallery Category"
                            name="housesec_id"
                            placeholder="Gallery Category"
                            onChange={HomeSectionChange}
                            onBlur={formik.handleBlur}
                          >
                          {HomeSectionsData.HouseSectionFind.rows.map((row) => (
                              <MenuItem key={row.id} value={row.id}> 
                                  {row.title} 
                              </MenuItem>
                          ))}
                          
                        </Select>
                        )}
                        {formik.touched.housesec_id && formik.errors.housesec_id && (
                            <FormHelperText sx={{ color: "red" }}>{formik.errors.housesec_id}</FormHelperText>
                        )}
                    </FormControl>
                </Box>

                <Box mb={2} display="flex" justifyContent="space-between">
                  <Box flex={1} mr={1}>
                    <Typography
                          component="h5"
                          sx={{
                            fontWeight: "500",
                            fontSize: "14px",
                            mb: "12px",
                          }}
                          className="text-black"
                        >
                          Image
                        </Typography>

                        <input
                            name="file_image"
                            type="file"
                            onChange={fileHandleChange}
                            onBlur={formik.handleBlur}
                            ref={fileImageInputRef}
                            style={{
                              display: 'block',
                              width: '100%',
                              padding: '12px',
                              margin: '10px 0',
                              border: '1px solid #D5D9E2',
                              borderRadius: '7px',
                              backgroundColor: 'white',
                            }}
                          />
                          {formik.touched.file_image && formik.errors.file_image && (
                            <FormHelperText sx={{ color: "red" }}>{formik.errors.file_image}</FormHelperText>
                          )}

                          {(formik.values.file_image && typeof formik.values.file_image==='string') && (
                            
                            <Image
                              src={formik.values?.file_image }
                              alt="gallery"
                              width={60}
                              height={60}
                              style={{
                                borderRadius: "7px",
                              }}
                            />
                          )}
                  </Box>
                </Box>
                
                <Box mb={2} display="flex" alignItems="center" >
                  <Typography
                    component="h5"
                    sx={{
                      fontWeight: "500",
                      fontSize: "14px",
                      mb: "0", 
                    }}
                    className="text-black"
                  >
                     <Checkbox
                    name="is_cover"
                    id="is_cover"
                    checked={formik.values.is_cover}
                    onChange={formik.handleChange}
                    inputProps={{ "aria-label": "controlled" }}
                  />
                    Category Cover Photo ?
                  </Typography>
                 
                </Box>


                    {/* <LocalizationProvider dateAdapter={AdapterDayjs}>
                      <DatePicker name="cover"
                        value={
                          (() => {
                            const parsedDate = dayjs(formik.values.cover);
                            const isValid = parsedDate.isValid();
                            return isValid ? parsedDate : null; 
                          })()
                        }
                        onChange={handleDateChange}  
                        sx={{
                          width: "100%",
                          "& fieldset": {
                            border: "1px solid #D5D9E2",
                            borderRadius: "7px",
                          },
                        }}
                      />
                    </LocalizationProvider> */}
        
                <Box mt={1} display="flex" justifyContent="flex-end" gap="10px">
                    <Box
                      sx={{
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "end",
                        gap: "10px",
                      }}
                    >
                      <Button
                        onClick={handleClose}
                        variant="outlined"
                        color="error"
                        sx={{
                          textTransform: "capitalize",
                          borderRadius: "8px",
                          fontWeight: "500",
                          fontSize: "13px",
                          padding: "11px 30px",
                        }}
                      >
                        Cancel
                      </Button>

                      <Button
                        type="submit"
                        variant="contained"
                        sx={{
                          textTransform: "capitalize",
                          borderRadius: "8px",
                          fontWeight: "500",
                          fontSize: "13px",
                          padding: "11px 30px",
                          color: "#fff !important",
                        }}
                      >
                        <AddIcon
                          sx={{
                            position: "relative",
                            top: "-2px",
                          }}
                          className="mr-5px"
                        />{" "}
                        {btnName}
                      </Button>
                    </Box>
                </Box>
              </Box>
            </Box>
          </Box>
        </Box>
      </BootstrapDialog>

      {/*View */ }
      <BootstrapDialog
        onClose={handleViewClose}
        aria-labelledby="customized-dialog-title"
        open={viewOpen}
        className="rmu-modal"
        PaperProps={{
          sx: { width: { xs: '100%', sm: '100%', md: '100%' }, maxWidth: '500px' }
        }}
>
        <Box>
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              background: "#f6f7f9",
              padding: { xs: "15px 20px", md: "25px" },
            }}
            className="rmu-modal-header"
          >
            <Typography
              id="modal-modal-title"
              variant="h6"
              sx={{
                fontWeight: "600",
                fontSize: { xs: "16px", md: "18px" },
              }}
              className="text-black"
            >
              View Inspiration
            </Typography>

            <IconButton aria-label="remove" size="small" onClick={handleViewClose}>
              <ClearIcon />
            </IconButton>
          </Box>

          <Box className="rmu-modal-content">
            <Box component="form">
              <Box
                sx={{
                  paddingLeft: "50px",
                  paddingRight: "50px",
                  paddingTop: "25px",
                  borderRadius: "8px",
                  backgroundColor: "white",
                }}
              >
                {/* Gallery Category */}
                <Box mb={2} display="flex" justifyContent="start">
                  <Typography
                    component="h5"
                    sx={{
                      fontWeight: "500",
                      fontSize: "14px",
                      mb: "12px",
                      whiteSpace: "nowrap",
                    }}
                    className="text-black"
                  >
                    Gallery Category:
                  </Typography>
                  <Typography
                    sx={{
                      fontSize: "14px",
                      color: "#555",
                      ml: "10px", 
                    }}
                  >
                    {formik.values.housesec_name}
                  </Typography>
                </Box>

                {/* Image */}
                <Box mb={2} display="flex" justifyContent="start">
                  <Typography
                    component="h5"
                    sx={{
                      fontWeight: "500",
                      fontSize: "14px",
                      mb: "12px",
                      maxWidth: "25%",
                      whiteSpace: "nowrap", 
                    }}
                    className="text-black"
                  >
                    Image:
                  </Typography>
                  <Typography
                    sx={{
                      fontSize: "14px",
                      color: "#555",
                      ml: "10px", 
                    }}
                  >
                    {formik.values?.file_image && (
                      <Image
                        src={formik.values?.file_image}
                        alt="gallery"
                        width={60}
                        height={60}
                        style={{
                          borderRadius: "7px",
                          marginLeft: 20,
                        }}
                      />
                    )}
                  </Typography>
                </Box>

                {/* Category Cover Photo */}
                <Box mb={2} display="flex" justifyContent="start">
                  <Typography
                    component="h5"
                    sx={{
                      fontWeight: "500",
                      fontSize: "14px",
                      mb: "12px",
                      whiteSpace: "nowrap", // Prevent label from wrapping
                    }}
                    className="text-black"
                  >
                    Category Cover Photo:
                  </Typography>
                  <Typography
                    sx={{
                      fontSize: "14px",
                      color: "#555",
                      ml: "10px", // Add space between colon and value
                    }}
                  >
                    {formik.values.cover ? "Yes" : ""}
                  </Typography>
                </Box>
              </Box>
            </Box>
          </Box>
        </Box>
      </BootstrapDialog>


       {/* Delete Modal */}
      <BootstrapDialog
        onClose={handleDelClose}
        aria-labelledby="customized-dialog-title"
        open={delOpen}
        className="rmu-modal"
      >
        <Box>
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              background: "#f6f7f9",
              padding: { xs: "15px 20px", md: "5px" },
            }}
            className="rmu-modal-header"
          >
            <DialogTitle sx={{ m: 0, p: 2 }} id="customized-dialog-title">
              Delete Confirmation
            </DialogTitle>
            <IconButton aria-label="remove" size="small" onClick={handleDelClose}>
              <ClearIcon />
            </IconButton>
          </Box>

           <DialogContent dividers>
              <Typography gutterBottom>
                Are you sure want to delete this entry ?
              </Typography>
              
            </DialogContent>
            
            <DialogActions>
                <Button variant="outlined"
                          color="error" 
                          onClick={handleDelSubmit}>Delete</Button>
                <Button variant="outlined"
                          onClick={handleDelClose}>Cancel</Button>
            </DialogActions> 
            
         
        </Box>
      </BootstrapDialog> 
      <ToastContainer/>
    </>
  );
};

export default withAuth(Inspiration, routes.inspiration.auth, RoleEnum.ADMIN);