"use client";

import React, { useState, useEffect,useRef } from "react";
import {
  Card,
  Box,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableFooter,
  TablePagination,
  TableRow,
  Paper,
  IconButton,
  TableHead,
  Button,
  TextField,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormHelperText,
  MenuItem,
  FormControl,
  InputLabel,
  ListItemText,
  Checkbox,
  OutlinedInput,
  
} from "@mui/material";
import AddIcon from "@mui/icons-material/Add";
import ClearIcon from "@mui/icons-material/Clear";
import FloorPlanService, {FloorplanOPData, FloorplanIdOPData} from "@/service/FloorPlanService";
import { ToastContainer, toast} from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { FloorPlanFormValues, FloorPlanValidationSchema, FloorPlanTouchFields  } 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 Textarea from "../../Fields/TextArea";
import Select, { SelectChangeEvent } from "@mui/material/Select";
import Image from 'next/image';
import RoomTypeService, {RoomTypeOPData} from "@/service/RoomTypesService";
import FeaturesService, {FeaturesOPData} from "@/service/FeaturesService";
import ArchitectureStyleService, {ArchitectureStyleOPData} from "@/service/ArchitectureStyleService";
import FloorPlanRoomTypeService,{FloorPlanRoomTypeCreateOPData,FloorPlanRoomTypeDeleteOPData} from "@/service/FloorPlanRoomTypeService";
import FloorPlanFeaturesService,{FloorPlanFeaturesCreateOPData,FloorPlanFeaturesDeleteOPData} from "@/service/FloorPlanFeaturesService";
import FloorPlanArchitectureStyleService,{FloorPlanArchitectureStyleCreateOPData,FloorPlanArchitectureStyleDelOPData} from "@/service/FloorPlanArchitectureStyleService";
import FloorPlanAttachmentService,{FloorPlanAttachmentCreateOPData,PFloorPlanAttachmentsUploadOPData,FloorPlanAttachmentsUploadIPData} from "@/service/FloorPlanAttachmentService";
import { ArrowUpward, ArrowDownward  } from '@mui/icons-material';
import { useRouter } from 'next/navigation';
import SearchIcon from '@mui/icons-material/Search';
import InputAdornment from '@mui/material/InputAdornment';
import { wrap } from "module";

const FloorPlan: React.FC = () => {
  
  const [page, setPage] = React.useState(1);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [FloorPlanData, setFloorPlanData] = useState<FloorplanOPData | undefined>(undefined); 
  const [FloorPlanDataById, setFloorPlanDataById] = useState<FloorplanIdOPData | undefined>(undefined);
  const [open, setOpen] = useState(false);
  const [delOpen, setDelOpen] = useState(false);
  const [viewOpen, setViewOpen] = useState(false);
  const [imgViewOpen, setImgViewOpen] = useState(false);
  const [title, setTitle] = useState("Add New ");
  const [delId, setDelId] = useState(0);
  const [RTId, setRTId] = useState(0);
  const [ASId, setASId] = useState(0);
  const [changes, setChanges] = useState("");
  const [btnName, setBtnName] = useState("Create");
  const [cookies, setCookie, removeCookie] = useCookies();
  const [isPagination, setIsPagination] = useState(false);
  const [roomType, setRoomType] = React.useState<number[]>([]);
  const [roomTypeData, setRoomTypeData] = useState<RoomTypeOPData | undefined>(undefined); 
  const [feature, setFeature] = React.useState<number[]>([]);
  const [featuresData, setFeaturesData] = useState<FeaturesOPData | undefined>(undefined); 
  const [architectureStyle, setArchitectureStyle] = useState<number[]>([]);
  const [architectureStyleData, setArchitectureStyleData] = useState<ArchitectureStyleOPData | undefined>(undefined); 
  const filepfdInputRef = useRef<HTMLInputElement | null>(null);
  const [sortOrder, setSortOrder] = useState<'DESC' | 'ASC'>('DESC');
  const [sortField, setSortField] = useState<string>("title");
  const router = useRouter();
  const [quickSearch, setQuickSearch] = React.useState<string>("");

  const ITEM_HEIGHT = 48;
  const ITEM_PADDING_TOP = 8;
  const MenuProps = {
    PaperProps: {
      style: {
        maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
        width: 250,
      },
    },
  };

  const fetchData = async () => {
    try {	
      let start
      console.log(page);
      
      if(page >= 1 && quickSearch){
        console.log("===================S");
        
      start = 0;
      setRowsPerPage(10)
      }	else{
        start = (page)*rowsPerPage;
      }
      //const start = (page)*rowsPerPage;
      
      const FloorPlanData = await FloorPlanService.getFloorplan(rowsPerPage, start, quickSearch,sortOrder,sortField);
       if(FloorPlanData != undefined && FloorPlanData != null && FloorPlanData?.FloorPlanFind){
        setFloorPlanData(FloorPlanData);
      } 
    } catch (err:any) {
      console.error('Error during fetch data:', err);
      handleFetchWithTokenRefresh(err, cookies, setCookie, fetchData, "Error during fetch data");
    }
  };

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

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

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

  useEffect(() => {
    fetchRoomType();
    fetchFeatures();
    fetchArchitectureStyle();
  },[]);

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

  const fetchRoomType = async () => {
    const roomTypes = await RoomTypeService.getRoomTypes();
    if(roomTypes && roomTypes?.RoomTypeFind){
      setRoomTypeData(roomTypes);
    }
  }

  const fetchFeatures = async () => {
    const features = await FeaturesService.getAllFeatures();
    if(features && features?.FeaturesFind){
      setFeaturesData(features);
    }
  }

  const fetchArchitectureStyle = async () => {
    const architectureStyle = await ArchitectureStyleService.getAllArchitectureStyle();
    if(architectureStyle && architectureStyle?.ArchitectureStyleFind){
      setArchitectureStyleData(architectureStyle);
    }
  }

  const handleInputChange = () => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { value } = e.target;
    setQuickSearch(value);
  };

  const formik = useFormik<FloorPlanFormValues>({
    initialValues: {
      title:"",
      short_desc:"",
      number:"",
      bed : "" ,
      bath : "",
      sqft : "",
      garage : "",
      garage_type:"",
      dimensions: "",
      front_porch : "",
      back_porch : "",
      room_type_id : "",
      feature_id : "",
      architecture_style_id : "",
      room_type_name : "",
      feature_name:"",
      architecture_style_name:"",
      file_image:"",
      file_pdf:"",
    },
    validationSchema: FloorPlanValidationSchema,
    onSubmit: async(values) => {
      
      handleSubmit(values);
    },
  });

  const addFloorplans = async(values:any)=>{
    try {
    const floorplanData = {
      bed:parseFloat(values.bed),
      bath:parseFloat(values.bath),
      garage:values.garage,
      garage_type:parseFloat(values.garage_type),
      title:values.title,
      short_desc:values.short_desc,
      sqft:parseFloat(values.sqft),
      dimensions:values.dimensions,
      front_porch:values.front_porch,
      back_porch:values.back_porch,
      number:values.number,
    };
    
  const FloorPlansData = await FloorPlanService.createFloorplan(floorplanData);
  
 
  if(FloorPlansData?.FloorPlanCreate && FloorPlansData?.FloorPlanCreate?.[0]?.id > 0){
    const floorplanID = FloorPlansData?.FloorPlanCreate?.[0]?.id || 0;
   
    if (values.room_type_id && values.room_type_id.length > 0) {
      for (const roomId of values.room_type_id) {
        const objRoomType = {
          floorplan_id: floorplanID.toString(),
          roomtype_id: roomId.toString(),
        };
        const FloorPlansRoomTypeData  = await FloorPlanRoomTypeService.createFloorPlanRoomType(objRoomType);
        const roomTypePlanData = FloorPlansRoomTypeData?.FloorPlanRoomTypeCreate || [];
      }
    } else {
      //console.log("No room types to process.");
    }

    if (values.feature_id && values.feature_id.length > 0) {
      for (const featureId of values.feature_id) {
        const featureType = {
          floorplan_id: floorplanID.toString(),
          feature_id: featureId.toString(),
        };
        const FloorPlansFeatureData = await FloorPlanFeaturesService.createFloorPlanFeatures(featureType);
        const featurePlanData = FloorPlansFeatureData?.FloorPlanFeaturesCreate || [];
      }
    } else {
     //console.log("No room types to process.");
    }

    if (values.architecture_style_id && values.architecture_style_id.length > 0) {  
      for (const archstyleId of values.architecture_style_id) {
        const archstyleType = {
          floorplan_id: floorplanID.toString(),
          archstyle_id: archstyleId.toString(),
        };
        const  FloorPlanArchitectureStyleData = await FloorPlanArchitectureStyleService.createFloorPlanArchitectureStyle(archstyleType);
        const architeStylePlanData = FloorPlanArchitectureStyleData?.FloorPlanArchitectureStyleCreate || [];
      }
    } else {
     //console.log("No room types to process.");
    }    
    
    const attachmentPDF: File[] = [];
    if (values.file_pdf) {
      attachmentPDF.push(values.file_pdf);
    
    const fpAttachmentPDFUpload = {
      attachmentPDF,
      input:{
        ref_id : `${floorplanID}`,
        file_field : "FILE_PDF"
      }
    }
   
    const FloorPlansAttachmentUploadPDF = await FloorPlanAttachmentService.UploadFloorPlanAttachmentPDF(fpAttachmentPDFUpload);
  }
    const PrevFloorPlanData = await FloorPlanService.getFloorplanById(floorplanID);
      setFloorPlanData((prevData) => {
        if (!prevData || !prevData.FloorPlanFind) {
          return prevData;
        }
        const newRow = PrevFloorPlanData?.FloorPlanFindOneById;
        if (!newRow) {
          return prevData; 
        }
        
        const existingRows = prevData?.FloorPlanFind?.rows || [];
        const total = prevData?.FloorPlanFind?.total  || 0;   
        const pages = Math.ceil(total / rowsPerPage);  
        return {
          ...prevData,
          FloorPlanFind: {
            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(FloorPlanTouchFields);   
        
      if (Object.keys(errors).length === 0) { 
        try {
          
          if (changes === 'Add') {
            //successMsg = "Inserted data successfully !!";
            addFloorplans(values);
           
           
          } else if (changes === 'Edit') {
              ;
              const upadateFloorPlan = {
                back_porch:values.back_porch,
                bath:parseInt(values.bath),
                bed:parseInt(values.bed),
                dimensions:values.dimensions,
                front_porch:values.front_porch,
                garage:values.garage,
                garage_type:parseInt(values.garage_type),
                number:values.number,
                short_desc:values.short_desc,
                sqft:parseInt(values.sqft),
                title:values.title,
                id:parseInt(values.id),
                
                }
                  
              const floorPlanInsData = await FloorPlanService.updateFloorplan(upadateFloorPlan);
        
              if(floorPlanInsData?.FloorPlanUpdate && floorPlanInsData?.FloorPlanUpdate.affected > 0){
                const getFloorplanbyIDs = await FloorPlanService.getFloorplanById(values.id);
                const defaultRoomTypeIds =
                getFloorplanbyIDs?.FloorPlanFindOneById?.fr_floor_plan_roomtypes?.map((item) => item?.fr_roomtype?.id) || [];
                if(defaultRoomTypeIds.length > 0){
                  const FloorPlanRoomTypeData = await FloorPlanRoomTypeService.deleteFloorPlanRoomType(values.id);
                }
                const defaultFeaturesIds =
                getFloorplanbyIDs?.FloorPlanFindOneById?.fr_floor_plan_features?.map((item) => item?.fr_feature?.id) || [];
                if(defaultFeaturesIds.length > 0){
                  const FloorPlanFeatureData = await FloorPlanFeaturesService.deleteFloorPlanFeatures(values.id);
                }
                const defaultArchitectureIds =
                getFloorplanbyIDs?.FloorPlanFindOneById?.fr_floor_plan_architecture_styles?.map((item) => item?.fr_architecture_style?.id) || [];
                if(defaultArchitectureIds.length > 0){
                  const FloorPlanArchiteureStyleData = await FloorPlanArchitectureStyleService.deleteFloorPlanArchitectureStyle(values.id);
                }

                if (values.room_type_id && values.room_type_id.length > 0) {
                  for (const roomId of values.room_type_id) {
                    const objRoomType = {
                      floorplan_id: values.id.toString(),
                      roomtype_id: roomId.toString(),
                    };
                   const FloorPlansRoomTypeData  = await FloorPlanRoomTypeService.createFloorPlanRoomType(objRoomType);
                   
                  }

                } else {
                  ////console.log("No room types to process.");
                }

                if (values.feature_id && values.feature_id.length > 0) {
                  
                  for (const featureId of values.feature_id) {
                    //const FloorPlanFeatureData = await FloorPlanFeaturesService.deleteFloorPlanFeatures(values.id);
                    const featureType = {
                      floorplan_id: values.id.toString(),
                      feature_id: featureId.toString(),
                    };
                   
                    const FloorPlansFeatureData = await FloorPlanFeaturesService.createFloorPlanFeatures(featureType);
                  }
                } else {
                  ////console.log("No room types to process.");
                }
            
                if (values.architecture_style_id && values.architecture_style_id.length > 0) {  
                  //const FloorPlanArchiteureStyleData = await FloorPlanArchitectureStyleService.deleteFloorPlanArchitectureStyle(values.id);
                  for (const archstyleId of values.architecture_style_id) {
                    const archstyleType = {
                      floorplan_id: values.id.toString(),
                      archstyle_id: archstyleId.toString(),
                    };
                   
                    const  FloorPlanArchitectureStyleData = await FloorPlanArchitectureStyleService.createFloorPlanArchitectureStyle(archstyleType);
                  }
                } else {
                }  
                
                const attachmentPDF: File[] = [];
                if (values.file_pdf && values.file_pdf instanceof File) {
                  attachmentPDF.push(values.file_pdf);
             
              
                if (attachmentPDF.length > 0) {
                  const fpAttachmentPDFUpload = {
                      attachmentPDF,
                      input: { ref_id: `${values.id}`, file_field: "FILE_PDF" },
                  };
                  await FloorPlanAttachmentService.UploadFloorPlanAttachmentPDF(fpAttachmentPDFUpload);
                }
              }  
                const oldFloorPlanData = await FloorPlanService.getFloorplanById(parseInt(values.id)); 
                setFloorPlanData((prevData) => {
                  if (!prevData || !prevData.FloorPlanFind) {
                    return prevData;
                  }
                  const newRow = oldFloorPlanData?.FloorPlanFindOneById;
                  if (!newRow) {
                    return prevData; 
                  }
                 
                  const existingRows = prevData?.FloorPlanFind?.rows || [];
                  const total = prevData?.FloorPlanFind?.total  || 0;   
                  const pages = Math.ceil(total / rowsPerPage); 

                    const updatedRows = existingRows.map(row =>
                    row.id === newRow.id ? newRow : row
                  );
                  
                  // If newRow was not replaced, prepend it
                  const isNewRowAdded = !existingRows.some(row => row.id === newRow.id);
                  if (isNewRowAdded) {
                    updatedRows.unshift(newRow);
                  }
                
                  const updatedTotal = isNewRowAdded ? total + 1 : total;    
                            
                  return {
                    ...prevData,
                    FloorPlanFind: {
                      rows: updatedRows,
                      total: updatedTotal,
                      pages: pages
                    },
                  }; 
                });
               
             
            }
          setOpen(false);
          setRTId(0);
         
          setRoomType([]);
          setFeature([]);
          setArchitectureStyle([])
          const successMsg = "Updated data successfully !!"
                toast.success(successMsg, {
                    position: "bottom-left",
                    autoClose: 2000,
                });
              }
        }catch (error:any) {
          
        /*   toast.error(error, {
            position: "bottom-left",
            autoClose: 2000,
        }); */
          handleFetchWithTokenRefresh(error, cookies, setCookie, handleSubmit, error, values);
        }  
      }
      
  }

  const fetchDataByID = async () => {
    try {		
      const FloorPlanDataById = await FloorPlanService.getFloorplanById(ASId);
      if(FloorPlanDataById != undefined && FloorPlanDataById != null && FloorPlanDataById?.FloorPlanFindOneById){
        setFloorPlanDataById(FloorPlanDataById);
      }
    } catch (err:any) {
      console.error('Error during fetch data:', err);
      handleFetchWithTokenRefresh(err, cookies, setCookie, fetchDataByID, "Error during fetch data");
    }
  };

  const setFormikValues = () => {
    
    if (FloorPlanDataById) {
      const defaultRoomTypeIds =
      FloorPlanDataById?.FloorPlanFindOneById?.fr_floor_plan_roomtypes?.map((item) => item?.fr_roomtype?.id) || [];
      const defaultFeaturesIds =
      FloorPlanDataById?.FloorPlanFindOneById?.fr_floor_plan_features?.map((item) => item?.fr_feature?.id) || [];
      const defaultArchitectureIds =
      FloorPlanDataById?.FloorPlanFindOneById?.fr_floor_plan_architecture_styles?.map((item) => item?.fr_architecture_style?.id) || [];

      setRoomType(defaultRoomTypeIds);
      setFeature(defaultFeaturesIds);
      setArchitectureStyle(defaultArchitectureIds);

      formik.setValues({
        title: FloorPlanDataById?.FloorPlanFindOneById?.title || "",
        id: FloorPlanDataById?.FloorPlanFindOneById?.id || 0,
        short_desc: FloorPlanDataById?.FloorPlanFindOneById?.short_desc || "",
        number: FloorPlanDataById?.FloorPlanFindOneById?.number || "",
        bed: FloorPlanDataById?.FloorPlanFindOneById?.bed || 0,
        bath: FloorPlanDataById?.FloorPlanFindOneById?.bath || 0,
        sqft: FloorPlanDataById?.FloorPlanFindOneById?.sqft || 0,
        garage: FloorPlanDataById?.FloorPlanFindOneById?.garage || "",
        dimensions: FloorPlanDataById?.FloorPlanFindOneById?.dimensions || "",
        front_porch: FloorPlanDataById?.FloorPlanFindOneById?.front_porch || "",
        back_porch: FloorPlanDataById?.FloorPlanFindOneById?.back_porch || "",
        room_type_id: defaultRoomTypeIds,
        room_type_name:FloorPlanDataById?.FloorPlanFindOneById?.fr_floor_plan_roomtypes?.[0]?.fr_roomtype?.title || "",
        feature_id: defaultFeaturesIds,
        feature_name:FloorPlanDataById?.FloorPlanFindOneById?.fr_floor_plan_features?.[0]?.fr_feature?.title || "",
        architecture_style_id: defaultArchitectureIds,
        architecture_style_name:FloorPlanDataById?.FloorPlanFindOneById?.fr_floor_plan_architecture_styles?.[0]?.fr_architecture_style?.title || "",
        file_image: FloorPlanDataById?.FloorPlanFindOneById?.fr_floor_plan_attachments?.[0]?.file_attachment_url?.direct|| "",
        file_pdf:  FloorPlanDataById?.FloorPlanFindOneById?.file_pdf_url?.direct || "",
        garage_type: FloorPlanDataById?.FloorPlanFindOneById?.garage_type || 0,
      });
    }
  }

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

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

  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(1);
  };

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

  const handleEditOpen = (Title:string, Id:number) => {
    setTitle(Title);
    setASId(Id);
    setRTId(Id);
    setOpen(true); 
    if(formik.values.title === ''){
      setFormikValues();
    }
    setChanges("Edit"); 
    setBtnName("Update");
  };

  const handleClose = () => {
    setOpen(false);
    setASId(0);
    setRoomType([])
    setFeature([]);
    setArchitectureStyle([])
    formik.resetForm();
  };

  const handleDelClickOpen = (Id:number) => {
    setDelId(Id);
    setDelOpen(true);
  };

  const handleDelClose = () => {
    setDelOpen(false);
    setASId(0);
  };

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

  const handleViewGalleryClose = () => {
    setImgViewOpen(false);
    setASId(0);
  };

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

  const handleError = (err:string, operation:string) => {
    if (typeof err === 'string' && err.includes('No record found or process intrupped for given criteria')) {
        console.log(err);
    } else {
        toast.error(`Error during ${operation}`, {
            position: "bottom-left",
            autoClose: 5000,
        });
        handleFetchWithTokenRefresh(err, cookies, setCookie, handleDelSubmit, "Error during delete data");
    }
  }

  const handleDelSubmit = async() => {
    try{
      const FloorPlanRoomTypeData = await FloorPlanRoomTypeService.deleteFloorPlanRoomType(delId);
    }catch(err:any){
        handleError(err, 'error during delete Floorplan Rooms');
    }

    try{
      const FloorPlanFeatureData = await FloorPlanFeaturesService.deleteFloorPlanFeatures(delId);
    }catch(err:any){
        handleError(err, 'error during delete Floorplan Features');
    }

    try{
      const FloorPlanArchiteureStyleData = await FloorPlanArchitectureStyleService.deleteFloorPlanArchitectureStyle(delId);
    }catch(err:any){
        handleError(err, 'error during delete Floorplan Architectural Style');
    }
      
    try {	
      const FloorPlanDelData = await FloorPlanService.deleteFloorplan(delId);

      /*if(FloorPlanDelData && FloorPlanDelData.FloorPlanDelete?.affected == 1
         && FloorPlanRoomTypeData?.FloorPlanRoomTypeDelete?.affected
         && FloorPlanFeatureData?.FloorPlanFeaturesDelete?.affected
         && FloorPlanArchiteureStyleData?.FloorPlanArchitectureStyleDelete?.affected){*/
        
        setFloorPlanData((prevData) => {
          if (!prevData || !prevData.FloorPlanFind) {
              return prevData;
          }
          const filteredRows = (prevData.FloorPlanFind.rows || []).filter(item => item.id !== delId);
          const total = ((prevData.FloorPlanFind.total-1) || 0);
          const pages = Math.ceil(total / rowsPerPage); 

          setASId(0);
          if(prevData?.FloorPlanFind?.pages !== pages){
            setIsPagination(true);
          }
          return {
              ...prevData,
              FloorPlanFind: {
                  ...prevData.FloorPlanFind,
                  rows: filteredRows,
                  total: total,
                  pages: pages
              },
          };
        });
        /*if(FloorPlanDelData && FloorPlanDelData?.FloorPlanDelete?.snapshot?.error.length > 0){
          const errorMsg =  FloorPlanDelData && FloorPlanDelData?.FloorPlanDelete?.snapshot?.error[0]
          toast.error(errorMsg, {
            position: "bottom-left",
            autoClose: 2000,
          });
        }else{*/
          toast.success('Entry Deleted Successfully !!', {
            position: "bottom-left",
            autoClose: 2000,
        });
      //}
        setPage(1);
        setDelOpen(false);
      //}
      
    } 
    catch (err:any) {
      console.error('Error during delete data:', err);
      //handleFetchWithTokenRefresh(err, cookies, setCookie, handleDelSubmit, "Error during delete data");
      handleError(err, 'error during delete Floorplan Portfolio');
    }

  };

  const handleRoomTypeChange = async (event: SelectChangeEvent<typeof roomType>) => {
   const { target: { value } } = event;

    const roomTypeVal= Array.isArray(value)
    ? value.map((item) => Number(item)).filter((item) => item !== undefined && !isNaN(item))
    : [Number(value)].filter((item) =>  item !== undefined && !isNaN(item))

    setRoomType( roomTypeVal);
    formik.setFieldValue('room_type_id', roomTypeVal);
  };
  
  const handlefeatureChange = async(event: SelectChangeEvent<typeof feature>) => {
    const { target: { value }} = event;

    const featureVal =   Array.isArray(value) 
    ? value.map((item) => Number(item)).filter((item) => item !== undefined && !isNaN(item))
    : [Number(value)].filter((item) =>  item !== undefined && !isNaN(item))
    setFeature(
      featureVal
    );
    formik.setFieldValue('feature_id',featureVal); 
  };

  const handleArchitectureStyleChange = async(event: SelectChangeEvent<typeof architectureStyle>) => {
    const {  target: { value },} = event;
    
    const architectureStyleVal =  Array.isArray(value) 
    ? value.map((item) => Number(item)).filter((item) => item !== undefined && !isNaN(item))
    : [Number(value)].filter((item) =>  item !== undefined && !isNaN(item))

    setArchitectureStyle(
      architectureStyleVal
    );
    formik.setFieldValue('architecture_style_id', architectureStyleVal); 
  };

  const fileHandleChangePDF = (event: React.ChangeEvent<HTMLInputElement>) => {
    formik.handleChange;
    const file = event.currentTarget.files?.[0] || null;
    if (file) {
      formik.setFieldValue('file_pdf', file); 
    } else {
      formik.setFieldValue('file_pdf', null); 
    }
  };
  
  
  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",
                float:"left"
              }}
            >
            <TextField
                  variant="outlined"
                  placeholder="Search"
                  name="floorPlan"
                  fullWidth
                  //onBlur={(e) => handleInputChange()(e)}
                  onBlur={(e) => handleInputChange()(e)}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <SearchIcon />
                      </InputAdornment>
                    ),
                  }}
                  sx={{
                    flexGrow: 1,
                    borderRadius: '50px', 
                    padding: '5px 15px', 
                    '& .MuiOutlinedInput-root': {
                      borderRadius: '50px', 
                    },
                    '& input': {
                      padding: '10px 10px', 
                    },
                  }}
                />
            </Box>
            <Box
              sx={{
                display: { xs: "block", sm: "flex" },
                alignItems: "center",
                justifyContent: "space-between",
                mb: "25px",
                float:"right"
              }}
            >
              <Button
                onClick={() => handleClickOpen("Add New Floor Plan Portfolio")}
                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>

            <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",
                        }}
                        className="text-black border-bottom"
                       
                      >
                         <IconButton
                          aria-label="sort"
                          color="primary"
                          sx={{ padding: "5px" }}
                          onClick={()=>handleSort("title")}
                        >
                          {sortOrder === 'ASC' ? (
                            <ArrowUpward sx={{ fontSize: '16px' }} />
                          ) : (
                            <ArrowDownward sx={{ fontSize: '16px' }} />
                          )}
                        </IconButton>
                        Name
                      </TableCell>

                      <TableCell
                        sx={{
                          fontWeight: "500",
                          padding: "10px 20px",
                          fontSize: "14px",
                        }}
                        className="text-black border-bottom"
                      >
                        Description
                      </TableCell>

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

                      <TableCell
                        sx={{
                          fontWeight: "500",
                          padding: "10px 20px",
                          fontSize: "14px",
                        }}
                        className="text-black border-bottom"
                      >
                       Details
                      </TableCell>

                      <TableCell
                        sx={{
                          fontWeight: "500",
                          padding: "10px 20px",
                          fontSize: "14px",
                        }}
                        className="text-black border-bottom"
                      >
                        Dimensions
                      </TableCell>

                      <TableCell
                        sx={{
                          fontWeight: "500",
                          padding: "10px 20px",
                          fontSize: "14px",
                        }}
                        className="text-black border-bottom"
                      >
                        Front Porch
                      </TableCell>

                      <TableCell
                        sx={{
                          fontWeight: "500",
                          padding: "10px 20px",
                          fontSize: "14px",
                        }}
                        className="text-black border-bottom"
                      >
                        Back Porch
                      </TableCell>

                      <TableCell
                        sx={{
                          fontWeight: "500",
                          padding: "10px 20px",
                          fontSize: "14px",
                        }}
                        className="text-black border-bottom"
                      >
                        Room Type
                      </TableCell>

                      <TableCell
                        sx={{
                          fontWeight: "500",
                          padding: "10px 20px",
                          fontSize: "14px",
                        }}
                        className="text-black border-bottom"
                      >
                        Features
                      </TableCell>

                      <TableCell
                        sx={{
                          fontWeight: "500",
                          padding: "10px 20px",
                          fontSize: "14px",
                        }}
                        className="text-black border-bottom"
                      >
                        Architectural Style
                      </TableCell>

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

                  <TableBody>
                    {FloorPlanData?.FloorPlanFind?.rows && FloorPlanData.FloorPlanFind.rows.length > 0 ? (
                    FloorPlanData.FloorPlanFind.rows.map((row) => (
                        <TableRow key={row.id}>
                          <TableCell
                            sx={{
                              padding: "5px 13px",
                              fontSize: "14px",
                              width: "65px",
                            }}
                            className="border-bottom"
                          >
                             {row?.title?.length > 20 
                          ? `${row?.title.substring(0, 50)}...` 
                          : row?.title}
                          </TableCell>

                          <TableCell
                            sx={{
                              padding: "15px 20px",
                              fontSize: "14px",
                            }}
                            className="border-bottom"
                          >
                           {row?.short_desc?.length > 50 
                          ? `${row?.short_desc.substring(0, 50)}...` 
                          : row?.short_desc}
                          </TableCell>

                          <TableCell
                            sx={{
                              padding: "15px 20px",
                              fontSize: "14px",
                            }}
                            className="border-bottom"
                          >
                            {row.number}
                          </TableCell>
                          <TableCell sx={{ padding: "15px 20px", fontSize: "14px" }}>
                          {`Bed: ${row.bed || 'N/A'} Bath: ${row.bath || 'N/A'}`}<br/>
                          {`Sqft: ${row.sqft || 'N/A'} Garage: ${row.garage || 'N/A'} Garage Type: ${row.garage_type || 'N/A'}`}
                          
                          </TableCell>
                          
                        

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

                          <TableCell
                            sx={{
                              padding: "15px 20px",
                              fontSize: "14px",
                            }}
                            className="border-bottom"
                          >
                          {row?.front_porch?.length > 50 
                          ? `${row?.front_porch.substring(0, 50)}...` 
                          : row?.front_porch}
                            
                          </TableCell>

                          <TableCell
                            sx={{
                              padding: "15px 20px",
                              fontSize: "14px",
                            }}
                            className="border-bottom"
                          >
                            {row?.back_porch?.length > 50 
                          ? `${row?.back_porch.substring(0, 50)}...` 
                          : row?.back_porch}
                          </TableCell>

                          <TableCell
                            sx={{
                              padding: "15px 20px",
                              fontSize: "14px",
                            }}
                            className="border-bottom"
                          >
                            {row?.fr_floor_plan_roomtypes?.map((arval, j, arr) => (
                            <span key={j}>
                              {arval.fr_roomtype.title}
                              {j < arr.length - 1 && ', '} 
                            </span>
                          ))}
                              
                          {/* {(row?.fr_floor_plan_roomtypes || []).map((arval, j) => (
                            <span key={j} >
                              {arval.fr_roomtype.title}
                              {j < (row.fr_floor_plan_roomtypes || []).length - 1 && ','} 
                            </span>
                          ))} */}
                          </TableCell>
                          <TableCell
                            sx={{
                              padding: "15px 20px",
                              fontSize: "14px",
                            }}
                            className="border-bottom"
                          >
                            
                           {row?.fr_floor_plan_features?.map((arval, j, arr) => (
                            <span key={j}>
                              {arval?.fr_feature?.title}
                              {j < arr.length - 1 && ', '} {/* Comma after every item except the last one */}
                            </span>
                          ))}
                           
                          </TableCell>

                          <TableCell
                            sx={{
                              padding: "15px 20px",
                              fontSize: "14px",
                            }}
                            className="border-bottom"
                          >
                          {row?.fr_floor_plan_architecture_styles?.map((arval, j, arr) => (
                            <span key={j}>
                              {arval.fr_architecture_style.title}
                              {j < arr.length - 1 && ', '} {/* Comma after every item except the last one */}
                            </span>
                          ))}
 
                          </TableCell>

                         
                         <TableCell
                            sx={{
                              padding: "15px 20px",
                              fontSize: "14px",
                            }}
                            className="border-bottom"
                          >
                            {/* {row?.file_pdf_url?.direct ?
                              <PictureAsPdfIcon sx={{ color: "red", fontSize: 20 }} />:null} */}
                            {row?.file_pdf_url?.direct && (
                              <IconButton
                                aria-label="pdf"
                                title="PDF"
                                sx={{ padding: "5px" ,color:"red"}}
                                href={row?.file_pdf_url?.direct}
                                target="_blank"
                                rel="noopener noreferrer"
                              >
                                <i className="material-symbols-outlined" style={{ fontSize: "16px" }}>
                                  picture_as_pdf
                                </i>
                              </IconButton>
                              )}
                          </TableCell>

                          <TableCell
                            sx={{
                              padding: "15px 20px",
                            }}
                            className="border-bottom"
                          >
                            <Box
                              sx={{
                                display: "flex",
                                alignItems: "center",
                                float:"right"
                              }}
                            >
                              <IconButton
                              aria-label="gallery"
                              color="secondary"
                              title="Gallery"
                              sx={{ padding: "5px" }}
                              onClick={() => router.push(`/admin/floor-plan/gallery/${row.id}`,{ scroll: false })}
                            >
                              <i
                                className="material-symbols-outlined"
                                style={{ fontSize: "16px" }}
                              >
                                photo_library
                              </i>
                            </IconButton>
                              <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 Floor Plan Portfolio", row.id)}
                              >
                              <i
                                  className="material-symbols-outlined"
                                  style={{ fontSize: "16px" }}
                              >
                                  edit
                              </i>
                              </IconButton>
                              

                              <IconButton
                                aria-label="delete"
                                color="error"
                                sx={{ padding: "5px" }}
                                title="Delete"
                                onClick={() => handleDelClickOpen(row.id)}
                              >
                                <i
                                  className="material-symbols-outlined"
                                  style={{ fontSize: "16px" }}
                                >
                                  delete
                                </i>
                              </IconButton>
                            </Box>
                          </TableCell>
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell colSpan={16} 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={16}
                        count={FloorPlanData?.FloorPlanFind?.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>

          <BootstrapDialog
            onClose={handleClose}
            aria-labelledby="customized-dialog-title"
            open={open}
            className="rmu-modal"
            PaperProps={{
                sx: { width: { xs: '100%', sm: '100%', md: '100%' }, maxWidth: '60%' }
              }}
          >
            <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
                      display="flex"
                      justifyContent="space-between"
                      alignItems="flex-start"
                      gap={2}  
                    >
                  
                      <Box mb={2} flex={1}>
                          <Typography
                            component="h5"
                            sx={{
                              fontWeight: "500",
                              fontSize: "14px",
                              mb: "12px",
                            }}
                            className="text-black"
                          >
                           Plan Name <span style={{ color: 'red' }}>*</span>  
                          </Typography>

                          <TextField
                            autoComplete="Plan Name"
                            name="title"
                            fullWidth
                            id="title"
                            label="Plan Name"
                            value = {formik.values.title}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            error={Boolean(formik.touched.title && formik.errors.title)}
                            helperText={formik.touched.title && formik.errors.title}
                          />
                      </Box>

                      <Box mb={2} flex={1}>
                          <Typography
                            component="h5"
                            sx={{
                              fontWeight: "500",
                              fontSize: "14px",
                              mb: "12px",
                            }}
                            className="text-black"
                          >
                            Plan Number <span style={{ color: 'red' }}>*</span>
                          </Typography>

                          <TextField
                            autoComplete="number"
                            name="number"
                            fullWidth
                            id="number"
                            label="Plan Number"
                            value = {formik.values.number}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            error={Boolean(formik.touched.number && formik.errors.number)}
                            helperText={formik.touched.number && formik.errors.number}
                          />
                      </Box>

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

                        <FormControl fullWidth>
                          <InputLabel id="demo-multiple-checkbox-label">Rooms</InputLabel>
                        
                          {Array.isArray(roomTypeData?.RoomTypeFind?.rows) && roomTypeData.RoomTypeFind.rows.length > 0 ? (
                            <Select
                              labelId="demo-multiple-checkbox-label"
                              id="demo-multiple-checkbox"
                              multiple
                              value={roomType}
                              onChange={handleRoomTypeChange}
                              input={<OutlinedInput label="Rooms" />}
                              renderValue={(selected) => {
                                const selectedTitles = selected.map((id) => {
                                  const selectedRoom = roomTypeData?.RoomTypeFind?.rows?.find((room) => room.id === id);
                                  return selectedRoom ? selectedRoom.title : '';
                                });
                                // Limit display to a fixed number and show "..." if truncated
                                return selectedTitles.length > 2
                                  ? `${selectedTitles.slice(0, 2).join(", ")}...`
                                  : selectedTitles.join(", ");
                              }}
                              
                              MenuProps={MenuProps}
                              sx={{
                                "& fieldset": {
                                  border: "1px solid #D5D9E2",
                                  borderRadius: "7px",
                                },
                                width: "100%", // Optional: control the width
                                overflow: "hidden", // Prevent content overflow
                                textOverflow: "ellipsis", // Ellipsis for long text
                                whiteSpace: "nowrap", // Prevent wrapping
                              }}
                            >
                              {roomTypeData.RoomTypeFind.rows.map((room) => (
                                <MenuItem key={room.id} value={room.id}>
                                  <Checkbox checked={roomType.includes(room.id)} />
                                  <ListItemText primary={room.title} />
                                </MenuItem>
                              ))}
                            </Select>
                          ) : (
                            <FormHelperText sx={{ color: "red" }}>No Room Types available</FormHelperText>
                          )}

                          {formik.touched.room_type_id && formik.errors.room_type_id && (
                            <FormHelperText sx={{ color: "red" }}>{formik.errors.room_type_id}</FormHelperText>
                          )}
                        </FormControl>
                        
                      </Box>
                    </Box>

                    <Box
                      display="flex"
                      justifyContent="space-between"
                      alignItems="flex-start"
                      gap={2}  
                    >
                      <Box mb={2} flex={1}>
                          <Typography
                            component="h5"
                            sx={{
                              fontWeight: "500",
                              fontSize: "14px",
                              mb: "12px",
                            }}
                            className="text-black"
                          >
                            Features
                          </Typography>
                            <FormControl fullWidth>
                            <InputLabel id="demo-multiple-checkbox-label">Feature</InputLabel>
                            {featuresData?.FeaturesFind?.rows && (
                            <Select
                              labelId="demo-multiple-checkbox-label"
                              id="demo-multiple-checkbox"
                              multiple
                              value={feature}
                              onChange={handlefeatureChange}
                              input={<OutlinedInput label="Feature" />}
                              renderValue={(selected) => {
                                const selectedTitles = selected.map((id) => {
                                  const selectedFeature = featuresData?.FeaturesFind?.rows?.find((feature) => feature.id === id);
                                  return selectedFeature ? selectedFeature.title : '';
                                });
                        
                                // Limit displayed values to avoid increasing input width
                                return selectedTitles.length > 2
                                  ? `${selectedTitles.slice(0, 2).join(", ")}...`
                                  : selectedTitles.join(", ");
                              }}
                              MenuProps={MenuProps}
                              sx={{
                                "& fieldset": {
                                  border: "1px solid #D5D9E2",
                                  borderRadius: "7px",
                                },
                              }}
                            >
                              {featuresData.FeaturesFind.rows.map((name) => (
                                <MenuItem key={name.id} value={name.id}>
                                 <Checkbox checked={feature.indexOf(name.id) > -1} />
                                  <ListItemText primary={name.title} />
                                </MenuItem>
                              ))}
                            </Select>
                            )}

                            {formik.touched.feature_id && formik.errors.feature_id && (
                              <FormHelperText sx={{ color: "red" }}>{formik.errors.feature_id}</FormHelperText>
                            )}
                            </FormControl>
                      </Box>

                      <Box mb={2} flex={1}>
                          <Typography
                            component="h5"
                            sx={{
                              fontWeight: "500",
                              fontSize: "14px",
                              mb: "12px",
                            }}
                            className="text-black"
                          >
                           Architectural Style
                          </Typography>

                            <FormControl fullWidth>
                            <InputLabel id="demo-multiple-checkbox-label">Architectural Style</InputLabel>
                            {architectureStyleData?.ArchitectureStyleFind?.rows && (
                            <Select
                              labelId="demo-multiple-checkbox-label"
                              id="demo-multiple-checkbox"
                              multiple
                              value={architectureStyle}
                              onChange={handleArchitectureStyleChange}
                              input={<OutlinedInput label="Architectural Style" />}
                              renderValue={(selected) => {
                                const selectedTitles = selected.map((id) => {
                                  const selectedStyle = architectureStyleData?.ArchitectureStyleFind?.rows?.find(
                                    (style) => style.id === id
                                  );
                                  return selectedStyle ? selectedStyle.title : '';
                                });
                        
                                // Limit displayed values to avoid increasing input width
                                return selectedTitles.length > 2
                                  ? `${selectedTitles.slice(0, 2).join(", ")}...`
                                  : selectedTitles.join(", ");
                              }}
                              MenuProps={MenuProps}
                              sx={{
                                "& fieldset": {
                                  border: "1px solid #D5D9E2",
                                  borderRadius: "7px",
                                },
                              }}
                            >
                              {architectureStyleData.ArchitectureStyleFind.rows.map((name) => (
                                <MenuItem key={name.id} value={name.id}>
                                  <Checkbox checked={architectureStyle.indexOf(name.id) > -1} />
                                  <ListItemText primary={name.title} />
                                </MenuItem>
                              ))}
                            </Select>
                            )}

                            {formik.touched.architecture_style_id && formik.errors.architecture_style_id && (
                              <FormHelperText sx={{ color: "red" }}>{formik.errors.architecture_style_id}</FormHelperText>
                            )}
                            </FormControl>
                      </Box>

                      <Box mb={2} flex={1}>
                        <Typography
                          component="h5"
                          sx={{
                            fontWeight: "500",
                            fontSize: "14px",
                            mb: "12px",
                          }}
                          className="text-black"
                        >
                          Square Feet <span style={{ color: 'red' }}>*</span>
                        </Typography>

                        <TextField
                          autoComplete="sqft"
                          name="sqft"
                          fullWidth
                          id="sqft"
                          label="Square Feet"
                          value = {formik.values.sqft}
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          error={Boolean(formik.touched.sqft && formik.errors.sqft)}
                          helperText={formik.touched.sqft && formik.errors.sqft}
                        />
                      </Box>
                    </Box>
                    <Box
                      display="flex"
                      justifyContent="space-between"
                      alignItems="flex-start"
                      gap={2}  
                    >
                      <Box mb={2} flex={1}>
                        <Typography
                          component="h5"
                          sx={{
                            fontWeight: "500",
                            fontSize: "14px",
                            mb: "12px",
                          }}
                          className="text-black"
                        >
                          Bed <span style={{ color: 'red' }}>*</span>
                        </Typography>

                        <TextField
                          autoComplete="bed"
                          name="bed"
                          fullWidth
                          id="bed"
                          label="Bed"
                          value = {formik.values.bed}
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          error={Boolean(formik.touched.bed && formik.errors.bed)}
                          helperText={formik.touched.bed && formik.errors.bed}
                        />
                      </Box>

                      <Box mb={2} flex={1}>
                        <Typography
                          component="h5"
                          sx={{
                            fontWeight: "500",
                            fontSize: "14px",
                            mb: "12px",
                          }}
                          className="text-black"
                        >
                          Bath <span style={{ color: 'red' }}>*</span>
                        </Typography>

                        <TextField
                          autoComplete="bath"
                          name="bath"
                          fullWidth
                          id="bath"
                          label="Bath"
                          value ={formik.values.bath}
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          error={Boolean(formik.touched.bath && formik.errors.bath)}
                          helperText={formik.touched.bath && formik.errors.bath}
                        />
                      </Box>
                      <Box mb={2} flex={1}>
                          <Typography
                            component="h5"
                            sx={{
                              fontWeight: "500",
                              fontSize: "14px",
                              mb: "12px",
                            }}
                            className="text-black"
                          >
                            Dimensions
                          </Typography>

                          <TextField
                            autoComplete="dimensions"
                            name="dimensions"
                            fullWidth
                            id="dimensions"
                            label="Dimensions"
                            value = {formik.values.dimensions}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            error={Boolean(formik.touched.dimensions && formik.errors.dimensions)}
                            helperText={formik.touched.dimensions && formik.errors.dimensions}
                          />
                      </Box>
                    </Box>
                    <Box
                      display="flex"
                      justifyContent="space-between"
                      alignItems="flex-start"
                      gap={2}  
                    >

                      <Box mb={2} flex={1}>
                        <Typography
                          component="h5"
                          sx={{
                            fontWeight: "500",
                            fontSize: "14px",
                            mb: "12px",
                          }}
                          className="text-black"
                        >
                          Garage Type<span style={{ color: 'red' }}>*</span>
                        </Typography>

                        <TextField
                          autoComplete="garage_type"
                          name="garage_type"
                          fullWidth
                          id="garage_type"
                          label="Garage Type"
                          value ={formik.values.garage_type}
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          error={Boolean(formik.touched.garage_type && formik.errors.garage_type)}
                          helperText={formik.touched.garage_type && formik.errors.garage_type}
                        />
                      </Box>

                      <Box mb={2} flex={1}>
                          <Typography
                            component="h5"
                            sx={{
                              fontWeight: "500",
                              fontSize: "14px",
                              mb: "12px",
                            }}
                            className="text-black"
                          >
                            Front Porch 
                          </Typography>

                          <TextField
                            autoComplete="front_porch"
                            name="front_porch"
                            fullWidth
                            id="front_porch"
                            label="Front Porch"
                            value = {formik.values.front_porch}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            error={Boolean(formik.touched.front_porch && formik.errors.front_porch)}
                            helperText={formik.touched.front_porch && formik.errors.front_porch}
                          />
                      </Box>

                      <Box mb={2} flex={1}>
                          <Typography
                            component="h5"
                            sx={{
                              fontWeight: "500",
                              fontSize: "14px",
                              mb: "12px",
                            }}
                            className="text-black"
                          >
                            Back Porch
                          </Typography>

                          <TextField
                            autoComplete="back_porch"
                            name="back_porch"
                            fullWidth
                            id="back_porch"
                            label="Back Porch"
                            value = {formik.values.back_porch}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            error={Boolean(formik.touched.back_porch && formik.errors.back_porch)}
                            helperText={formik.touched.back_porch && formik.errors.back_porch}
                          />
                      </Box>

                    </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"
                  >
                    PDF
                  </Typography>

                  <input
                      id="file_pdf"
                      name="file_pdf"
                      type="file"
                      onChange={fileHandleChangePDF}
                      onBlur={formik.handleBlur}
                      ref={filepfdInputRef}
                      style={{
                        display: 'block',
                        width: '100%',
                        padding: '14px',
                        margin: '10px 0',
                        border: '1px solid #D3D3D3',
                        borderRadius: '4px',
                        backgroundColor: 'white',
                      }}
                    />
                    {/*  {formik.touched.file_pdf && formik.errors.file_pdf && (
                      <FormHelperText sx={{ color: "red" }}>{formik.errors.file_pdf}</FormHelperText>
                    )} */}
                    {formik.values.file_pdf && typeof formik.values.file_pdf === 'string' && (
                      <IconButton
                      aria-label="pdf"
                      color="secondary"
                      sx={{ padding: "5px",color:'red' }}
                      href={formik.values.file_pdf}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      <i className="material-symbols-outlined" style={{ fontSize: "16px" }}>
                        picture_as_pdf
                      </i>
                    </IconButton>
                      )}
                        {/* <PictureAsPdfIcon sx={{ color: "red", fontSize: 20 }} /> */}
                    </Box>

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

                        <TextField
                          autoComplete="garage"
                          name="garage"
                          fullWidth
                          id="garage"
                          label="Garage"
                          value ={formik.values.garage}
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          error={Boolean(formik.touched.garage && formik.errors.garage)}
                          helperText={formik.touched.garage && formik.errors.garage}
                        />
                      </Box>
                  </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"
                              >
                                Short Description
                              </Typography>

                              <Textarea
                                aria-label="minimum height"
                                minRows={4}
                                autoComplete="short_desc"
                                name="short_desc"
                                id="short_desc"
                                placeholder="Short Description"
                                onChange={formik.handleChange}
                                onBlur={formik.handleBlur}
                                value = {formik.values.short_desc}
                              />
                              {formik.touched.short_desc && formik.errors.short_desc && (
                                  <FormHelperText sx={{ color: "red" }}>{formik.errors.short_desc}</FormHelperText>
                                )}
                        </Box>
                    </Box>
                    

                    <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>

          <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 Floor Plan Portfolio
                </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",
                    }}
                  >
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                      Plan Name:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {formik.values.title}
                    </Typography>
                  </Box>
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                      Description :
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {formik.values.short_desc}
                    </Typography>
                  </Box> 
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                     Number:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {formik.values.number}
                    </Typography>
                  </Box> 
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                     Bed:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {formik.values.bed}
                    </Typography>
                  </Box> 
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                     Bath:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {formik.values.bath}
                    </Typography>
                  </Box>
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                      Sqft:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {formik.values.sqft}
                    </Typography>
                  </Box> 
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                      Garage:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {formik.values.garage}
                    </Typography>
                  </Box>   
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                      Garage Type:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {formik.values.garage_type}
                    </Typography>
                  </Box> 
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                     Dimensions:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                      
                    >
                      {formik.values.dimensions}
                    </Typography>
                  </Box> 
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                     Front Porch:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {formik.values.front_porch}
                    </Typography>
                  </Box> 
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                     Back Porch:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                     {formik.values.back_porch}
                    </Typography>
                  </Box> 
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                      Room Type:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {formik.values.room_type_name }
                    </Typography>
                  </Box> 
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                     Features:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {formik.values.feature_name}
                      
                    </Typography>
                  </Box> 
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                     Architectural Style:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {formik.values.architecture_style_name}
                    
                    </Typography>
                  </Box> 
           
                  <Box mb={2} display="flex" justifyContent="space-between" >
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                     PDF:
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {formik.values.file_pdf && (
                        <IconButton
                          aria-label="pdf"
                          color="secondary"
                          sx={{ padding: "5px",color:'red' }}
                          href={formik.values.file_pdf}
                          target="_blank"
                          rel="noopener noreferrer"
                        >
                          <i className="material-symbols-outlined" style={{ fontSize: "16px" }}>
                            picture_as_pdf
                          </i>
                        </IconButton>
                        )}  
                    </Typography>
                  </Box> 
                  </Box>
                </Box>
              </Box>
            </Box>
          </BootstrapDialog> 

          <BootstrapDialog
            onClose={handleViewGalleryClose}
            aria-labelledby="customized-dialog-title"
            open={imgViewOpen}
            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"
                >
                  Gallery
                </Typography>

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

              <Box className="rmu-modal-content">
                <Box component="form">
                  <Box
                    sx={{
                      paddingLeft: "50px",
                      paddingRight: "50px",
                      paddingTop:"25px",
                      borderRadius: "8px",
                      backgroundColor: "white",
                    }}
                  >
                        <Button
                            //onClick={() => handleClickOpen("Add New Floor Plan Portfolio")}
                            variant="outlined"
                            sx={{
                              textTransform: "capitalize",
                              borderRadius: "7px",
                              fontWeight: "500",
                              fontSize: "13px",
                              padding: "6px 13px",
                              marginBottom:"10px"
                            }}
                            color="primary"
                            title="Add"
                          >
                <AddIcon sx={{ position: "relative", top: "-1px" }} /> Add Image
              </Button>
                  <Box mb={2} display="flex" justifyContent="space-between" >
                   
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                     {(formik.values.file_image && typeof formik.values.file_image==='string') && (
                                  
                                  <Image
                                    src={formik.values?.file_image || " "}
                                    alt="gallerviewimg"
                                    width={80}
                                    height={80}
                                    style={{
                                      borderRadius: "7px",
                                    }}
                                  />
                                )}
                    
                    </Typography>
                            <Box
                              sx={{
                                display: "flex",
                                alignItems: "center",
                                float:"right"
                              }}>
                             
                             
                              <IconButton
                                aria-label="edit"
                                color="secondary"
                                sx={{ padding: "5px" }} >
                              <i
                                className="material-symbols-outlined"
                                style={{ fontSize: "16px" }} >
                              edit
                              </i>
                              </IconButton>
                              

                              <IconButton
                                aria-label="delete"
                                color="error"
                                sx={{ padding: "5px" }}
                                //onClick={() => handleDelClickOpen(row.id)}
                              >
                                <i
                                  className="material-symbols-outlined"
                                  style={{ fontSize: "16px" }}
                                >
                                  delete
                                </i>
                              </IconButton>
                      </Box>
                         
                  </Box> 
                  
                  </Box>
                  
                </Box>
              </Box>
            </Box>
          </BootstrapDialog> 

          <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(FloorPlan, routes.floorplan.auth, RoleEnum.ADMIN);