import React, { useEffect, useState , useRef } from "react";
import QRCode from "qrcode.react";
import Barcode from "react-barcode";
import html2canvas from "html2canvas";
import Select from "react-select";
import ReCAPTCHA from "react-google-recaptcha";
import axios from "axios";
import { FaTrash } from "react-icons/fa";
import { Modal, Button, Form, Pagination,Container, Row, Col, Image , ProgressBar , } from "react-bootstrap";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { getToken } from '../../../../utils/tokenService';import Table from "react-bootstrap/Table";
const FILE_API_URL = `${process.env.REACT_APP_API_URL}FileUpload/Uploadeddocs`; 
const API_URL = `${process.env.REACT_APP_API_URL}Adv1/Adv1`;
const REACT_APP_API_TOKEN = localStorage.getItem("authToken")

const EntityTable = () => {
  const [data, setData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [newEntity, setNewEntity] = useState({
    ismale: "",

    idfemale: "",

    
 
    test1: false,
     


    
 
    t1: false,
     


fileupload_fieldname: "",
fileupload_fieldpath: "",

fileupload_field2name: "",
fileupload_field2path: "",

imageupload_fieldname: "",
imageupload_fieldpath: "",

imageupload_field2name: "",
imageupload_field2path: "",

audio_fieldname: "",
audio_fieldpath: "",

audio_field2name: "",
audio_field2path: "",

video_fieldname: "",
video_fieldpath: "",

video_field2name: "",
video_field2path: "",

  });
  const [editEntity, setEditEntity] = useState(null);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showAddModal, setShowAddModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deleteEntityId, setDeleteEntityId] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(5); // Adjust this value as needed
  const [searchQuery, setSearchQuery] = useState("");
  const [loading, setLoading] = useState(true);
  const [options, setOptions] = useState([]);
  const [filteredOptions, setFilteredOptions] = useState([]);
  const [error, setError] = useState(null);
 const [uploadProgress, setUploadProgress] = useState(0);
 const [showModal, setShowModal] = useState(false);
  const [showValulistModal, setShowValulistModal] = useState(false);
 const barcodeRef = useRef(null);
  const [serverData, setServerData] = useState([]);
  const recaptchaRef = useRef(null);
 const editBarcodeRef = useRef(null);
  useEffect(() => {
    fetchData();
























  }, []);

  useEffect(() => {
    handleSearch();
  }, [searchQuery, data]);
  const fetchData = async () => {
    try {
const token = getToken();
      const response = await axios.get(API_URL, {
        headers: { Authorization: `Bearer ${token}` },
      });
      setData(response.data);
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const handleDelete = async () => {
    try {
 const token = getToken();
      await axios.delete(`${API_URL}/${deleteEntityId}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      fetchData();
      toast.success("Successfully deleted!");
      setShowDeleteModal(false);
    } catch (error) {
      console.error("Error deleting data:", error);
    }
  };

  const handleAdd = async () => {
























    try {
 const token = getToken();
      await axios.post(API_URL, newEntity, {
























        headers: { Authorization: `Bearer ${token}` },
      });
      fetchData();
      setNewEntity({
    ismale: "",

    idfemale: "",

    
 
    test1: false,
     


    
 
    t1: false,
     


fileupload_fieldname: "",
fileupload_fieldpath: "",

fileupload_field2name: "",
fileupload_field2path: "",

imageupload_fieldname: "",
imageupload_fieldpath: "",

imageupload_field2name: "",
imageupload_field2path: "",

audio_fieldname: "",
audio_fieldpath: "",

audio_field2name: "",
audio_field2path: "",

video_fieldname: "",
video_fieldpath: "",

video_field2name: "",
video_field2path: "",

      });
      setShowAddModal(false);
      toast.success("Successfully added!");
    } catch (error) {
      console.error("Error adding data:", error);
    }
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setNewEntity({ ...newEntity, [name]: value });
  };

  const handleEditChange = (e) => {
    const { name, value } = e.target;
    setEditEntity({ ...editEntity, [name]: value });
  };

  const handleEdit = (entity) => {
    setEditEntity(entity);

























    setShowEditModal(true);
  };

  const formatCurrency = (value) => {
   if (value && !value.startsWith('₹')) {
    return `₹${value}`;
  }
  return value;
};






const handleCheckboxChange = (e) => {
  const { name, checked } = e.target;
  setNewEntity({ ...newEntity, [name]: checked });
};

const handleEditCheckboxChange = (e) => {
  const { name, checked } = e.target;
  setEditEntity({ ...editEntity, [name]: checked });
};



const handleCheckboxChange = (e) => {
  const { name, checked } = e.target;
  setNewEntity({ ...newEntity, [name]: checked });
};

const handleEditCheckboxChange = (e) => {
  const { name, checked } = e.target;
  setEditEntity({ ...editEntity, [name]: checked });
};



 const fileupload_fielduploadFile = async ( file, ref, Adv1) => {
    if (!file) {
      toast.error("Please select a file to upload.");
      return;
    }
  
    const formData = new FormData();
    formData.append("file", file); // Ensure the key matches the backend parameter name
    
  
    try {
      const response = await axios.post(
        `${FILE_API_URL}/${ref}/${Adv1}`, // Use path variables in the URL
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: `Bearer ${localStorage.getItem("authToken")}`,
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            setUploadProgress(percentCompleted);
          },
        }
      );
  
     console.log("File upload response:", response.data);

      const { uploadedfile_name, uploadedfile_path } = response.data;

      setNewEntity((prevState) => ({
        ...prevState,
        fileupload_fieldname: uploadedfile_name,
        fileupload_fieldpath: uploadedfile_path,
      }));
 
  

    toast.success("File uploaded successfully!");
    return { uploadedfile_name, uploadedfile_path };
    console.log("Response:", response.data);
  } catch (error) {
    console.error("File upload failed with error:", error);
    console.log("Error details:", error.response); 
    if (error.response && error.response.status === 405) {
      toast.error("Method Not Allowed. Please check the API endpoint and method.");
    } else {
      toast.error("File upload failed. Please try again.");
    }
  }
};

 const handleAddfileupload_field = async () => {
    try {
      const token = getToken();
      await axios.post(
        API_URL,
        {
          fileupload_fieldname: newEntity.fileupload_fieldname,
          fileupload_fieldpath: newEntity.fileupload_fieldpath,
        },
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );
      fetchData();
      setNewEntity({ fileupload_fieldname: "", fileupload_fieldpath: "" });
      setShowAddModal(false);
      toast.success("File uploaded and entity added successfully!");
    } catch (error) {
      console.error("Error adding entity:", error);
      toast.error("Failed to add entity!");
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    fileupload_fielduploadFile(file, "ref", "Adv1");
  };


 const fileupload_field2uploadFile = async ( file, ref, Adv1) => {
    if (!file) {
      toast.error("Please select a file to upload.");
      return;
    }
  
    const formData = new FormData();
    formData.append("file", file); // Ensure the key matches the backend parameter name
    
  
    try {
      const response = await axios.post(
        `${FILE_API_URL}/${ref}/${Adv1}`, // Use path variables in the URL
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: `Bearer ${localStorage.getItem("authToken")}`,
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            setUploadProgress(percentCompleted);
          },
        }
      );
  
     console.log("File upload response:", response.data);

      const { uploadedfile_name, uploadedfile_path } = response.data;

      setNewEntity((prevState) => ({
        ...prevState,
        fileupload_field2name: uploadedfile_name,
        fileupload_field2path: uploadedfile_path,
      }));
 
  

    toast.success("File uploaded successfully!");
    return { uploadedfile_name, uploadedfile_path };
    console.log("Response:", response.data);
  } catch (error) {
    console.error("File upload failed with error:", error);
    console.log("Error details:", error.response); 
    if (error.response && error.response.status === 405) {
      toast.error("Method Not Allowed. Please check the API endpoint and method.");
    } else {
      toast.error("File upload failed. Please try again.");
    }
  }
};

 const handleAddfileupload_field2 = async () => {
    try {
      const token = getToken();
      await axios.post(
        API_URL,
        {
          fileupload_field2name: newEntity.fileupload_field2name,
          fileupload_field2path: newEntity.fileupload_field2path,
        },
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );
      fetchData();
      setNewEntity({ fileupload_field2name: "", fileupload_field2path: "" });
      setShowAddModal(false);
      toast.success("File uploaded and entity added successfully!");
    } catch (error) {
      console.error("Error adding entity:", error);
      toast.error("Failed to add entity!");
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    fileupload_field2uploadFile(file, "ref", "Adv1");
  };


 const imageupload_fielduploadFile = async ( file, ref, Adv1) => {
    if (!file) {
      toast.error("Please select a file to upload.");
      return;
    }
  
    const formData = new FormData();
    formData.append("file", file); // Ensure the key matches the backend parameter name
    
  
    try {
      const response = await axios.post(
        `${FILE_API_URL}/${ref}/${Adv1}`, // Use path variables in the URL
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: `Bearer ${localStorage.getItem("authToken")}`,
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            setUploadProgress(percentCompleted);
          },
        }
      );
  
     console.log("File upload response:", response.data);

      const { uploadedfile_name, uploadedfile_path } = response.data;

      setNewEntity((prevState) => ({
        ...prevState,
        imageupload_fieldname: uploadedfile_name,
        imageupload_fieldpath: uploadedfile_path,
      }));
 
  

    toast.success("File uploaded successfully!");
    return { uploadedfile_name, uploadedfile_path };
    console.log("Response:", response.data);
  } catch (error) {
    console.error("File upload failed with error:", error);
    console.log("Error details:", error.response); 
    if (error.response && error.response.status === 405) {
      toast.error("Method Not Allowed. Please check the API endpoint and method.");
    } else {
      toast.error("File upload failed. Please try again.");
    }
  }
};

 const handleAddimageupload_field = async () => {
    try {
      const token = getToken();
      await axios.post(
        API_URL,
        {
          imageupload_fieldname: newEntity.imageupload_fieldname,
          imageupload_fieldpath: newEntity.imageupload_fieldpath,
        },
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );
      fetchData();
      setNewEntity({ imageupload_fieldname: "", imageupload_fieldpath: "" });
      setShowAddModal(false);
      toast.success("File uploaded and entity added successfully!");
    } catch (error) {
      console.error("Error adding entity:", error);
      toast.error("Failed to add entity!");
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    imageupload_fielduploadFile(file, "ref", "Adv1");
  };


 const imageupload_field2uploadFile = async ( file, ref, Adv1) => {
    if (!file) {
      toast.error("Please select a file to upload.");
      return;
    }
  
    const formData = new FormData();
    formData.append("file", file); // Ensure the key matches the backend parameter name
    
  
    try {
      const response = await axios.post(
        `${FILE_API_URL}/${ref}/${Adv1}`, // Use path variables in the URL
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: `Bearer ${localStorage.getItem("authToken")}`,
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            setUploadProgress(percentCompleted);
          },
        }
      );
  
     console.log("File upload response:", response.data);

      const { uploadedfile_name, uploadedfile_path } = response.data;

      setNewEntity((prevState) => ({
        ...prevState,
        imageupload_field2name: uploadedfile_name,
        imageupload_field2path: uploadedfile_path,
      }));
 
  

    toast.success("File uploaded successfully!");
    return { uploadedfile_name, uploadedfile_path };
    console.log("Response:", response.data);
  } catch (error) {
    console.error("File upload failed with error:", error);
    console.log("Error details:", error.response); 
    if (error.response && error.response.status === 405) {
      toast.error("Method Not Allowed. Please check the API endpoint and method.");
    } else {
      toast.error("File upload failed. Please try again.");
    }
  }
};

 const handleAddimageupload_field2 = async () => {
    try {
      const token = getToken();
      await axios.post(
        API_URL,
        {
          imageupload_field2name: newEntity.imageupload_field2name,
          imageupload_field2path: newEntity.imageupload_field2path,
        },
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );
      fetchData();
      setNewEntity({ imageupload_field2name: "", imageupload_field2path: "" });
      setShowAddModal(false);
      toast.success("File uploaded and entity added successfully!");
    } catch (error) {
      console.error("Error adding entity:", error);
      toast.error("Failed to add entity!");
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    imageupload_field2uploadFile(file, "ref", "Adv1");
  };


 const audio_fielduploadFile = async ( file, ref, Adv1) => {
    if (!file) {
      toast.error("Please select a file to upload.");
      return;
    }
  
    const formData = new FormData();
    formData.append("file", file); // Ensure the key matches the backend parameter name
    
  
    try {
      const response = await axios.post(
        `${FILE_API_URL}/${ref}/${Adv1}`, // Use path variables in the URL
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: `Bearer ${localStorage.getItem("authToken")}`,
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            setUploadProgress(percentCompleted);
          },
        }
      );
  
     console.log("File upload response:", response.data);

      const { uploadedfile_name, uploadedfile_path } = response.data;

      setNewEntity((prevState) => ({
        ...prevState,
        audio_fieldname: uploadedfile_name,
        audio_fieldpath: uploadedfile_path,
      }));
 
  

    toast.success("File uploaded successfully!");
    return { uploadedfile_name, uploadedfile_path };
    console.log("Response:", response.data);
  } catch (error) {
    console.error("File upload failed with error:", error);
    console.log("Error details:", error.response); 
    if (error.response && error.response.status === 405) {
      toast.error("Method Not Allowed. Please check the API endpoint and method.");
    } else {
      toast.error("File upload failed. Please try again.");
    }
  }
};

 const handleAddaudio_field = async () => {
    try {
      const token = getToken();
      await axios.post(
        API_URL,
        {
          audio_fieldname: newEntity.audio_fieldname,
          audio_fieldpath: newEntity.audio_fieldpath,
        },
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );
      fetchData();
      setNewEntity({ audio_fieldname: "", audio_fieldpath: "" });
      setShowAddModal(false);
      toast.success("File uploaded and entity added successfully!");
    } catch (error) {
      console.error("Error adding entity:", error);
      toast.error("Failed to add entity!");
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    audio_fielduploadFile(file, "ref", "Adv1");
  };


 const audio_field2uploadFile = async ( file, ref, Adv1) => {
    if (!file) {
      toast.error("Please select a file to upload.");
      return;
    }
  
    const formData = new FormData();
    formData.append("file", file); // Ensure the key matches the backend parameter name
    
  
    try {
      const response = await axios.post(
        `${FILE_API_URL}/${ref}/${Adv1}`, // Use path variables in the URL
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: `Bearer ${localStorage.getItem("authToken")}`,
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            setUploadProgress(percentCompleted);
          },
        }
      );
  
     console.log("File upload response:", response.data);

      const { uploadedfile_name, uploadedfile_path } = response.data;

      setNewEntity((prevState) => ({
        ...prevState,
        audio_field2name: uploadedfile_name,
        audio_field2path: uploadedfile_path,
      }));
 
  

    toast.success("File uploaded successfully!");
    return { uploadedfile_name, uploadedfile_path };
    console.log("Response:", response.data);
  } catch (error) {
    console.error("File upload failed with error:", error);
    console.log("Error details:", error.response); 
    if (error.response && error.response.status === 405) {
      toast.error("Method Not Allowed. Please check the API endpoint and method.");
    } else {
      toast.error("File upload failed. Please try again.");
    }
  }
};

 const handleAddaudio_field2 = async () => {
    try {
      const token = getToken();
      await axios.post(
        API_URL,
        {
          audio_field2name: newEntity.audio_field2name,
          audio_field2path: newEntity.audio_field2path,
        },
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );
      fetchData();
      setNewEntity({ audio_field2name: "", audio_field2path: "" });
      setShowAddModal(false);
      toast.success("File uploaded and entity added successfully!");
    } catch (error) {
      console.error("Error adding entity:", error);
      toast.error("Failed to add entity!");
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    audio_field2uploadFile(file, "ref", "Adv1");
  };


 const video_fielduploadFile = async ( file, ref, Adv1) => {
    if (!file) {
      toast.error("Please select a file to upload.");
      return;
    }
  
    const formData = new FormData();
    formData.append("file", file); // Ensure the key matches the backend parameter name
    
  
    try {
      const response = await axios.post(
        `${FILE_API_URL}/${ref}/${Adv1}`, // Use path variables in the URL
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: `Bearer ${localStorage.getItem("authToken")}`,
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            setUploadProgress(percentCompleted);
          },
        }
      );
  
     console.log("File upload response:", response.data);

      const { uploadedfile_name, uploadedfile_path } = response.data;

      setNewEntity((prevState) => ({
        ...prevState,
        video_fieldname: uploadedfile_name,
        video_fieldpath: uploadedfile_path,
      }));
 
  

    toast.success("File uploaded successfully!");
    return { uploadedfile_name, uploadedfile_path };
    console.log("Response:", response.data);
  } catch (error) {
    console.error("File upload failed with error:", error);
    console.log("Error details:", error.response); 
    if (error.response && error.response.status === 405) {
      toast.error("Method Not Allowed. Please check the API endpoint and method.");
    } else {
      toast.error("File upload failed. Please try again.");
    }
  }
};

 const handleAddvideo_field = async () => {
    try {
      const token = getToken();
      await axios.post(
        API_URL,
        {
          video_fieldname: newEntity.video_fieldname,
          video_fieldpath: newEntity.video_fieldpath,
        },
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );
      fetchData();
      setNewEntity({ video_fieldname: "", video_fieldpath: "" });
      setShowAddModal(false);
      toast.success("File uploaded and entity added successfully!");
    } catch (error) {
      console.error("Error adding entity:", error);
      toast.error("Failed to add entity!");
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    video_fielduploadFile(file, "ref", "Adv1");
  };


 const video_field2uploadFile = async ( file, ref, Adv1) => {
    if (!file) {
      toast.error("Please select a file to upload.");
      return;
    }
  
    const formData = new FormData();
    formData.append("file", file); // Ensure the key matches the backend parameter name
    
  
    try {
      const response = await axios.post(
        `${FILE_API_URL}/${ref}/${Adv1}`, // Use path variables in the URL
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: `Bearer ${localStorage.getItem("authToken")}`,
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            setUploadProgress(percentCompleted);
          },
        }
      );
  
     console.log("File upload response:", response.data);

      const { uploadedfile_name, uploadedfile_path } = response.data;

      setNewEntity((prevState) => ({
        ...prevState,
        video_field2name: uploadedfile_name,
        video_field2path: uploadedfile_path,
      }));
 
  

    toast.success("File uploaded successfully!");
    return { uploadedfile_name, uploadedfile_path };
    console.log("Response:", response.data);
  } catch (error) {
    console.error("File upload failed with error:", error);
    console.log("Error details:", error.response); 
    if (error.response && error.response.status === 405) {
      toast.error("Method Not Allowed. Please check the API endpoint and method.");
    } else {
      toast.error("File upload failed. Please try again.");
    }
  }
};

 const handleAddvideo_field2 = async () => {
    try {
      const token = getToken();
      await axios.post(
        API_URL,
        {
          video_field2name: newEntity.video_field2name,
          video_field2path: newEntity.video_field2path,
        },
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );
      fetchData();
      setNewEntity({ video_field2name: "", video_field2path: "" });
      setShowAddModal(false);
      toast.success("File uploaded and entity added successfully!");
    } catch (error) {
      console.error("Error adding entity:", error);
      toast.error("Failed to add entity!");
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    video_field2uploadFile(file, "ref", "Adv1");
  };


   const handleUpdate = async () => {
























    try {
const token = getToken();
      await axios.put(`${API_URL}/${editEntity.id}`, editEntity, {
























        headers: { Authorization: `Bearer ${token}` },
      });
      fetchData();
      setShowEditModal(false);
      toast.success("Successfully updated!");
    } catch (error) {
      console.error("Error updating data:", error);
    }
  };

  const handleSearch = () => {
    const filtered = data.filter(
      (entity) =>

      entity.ismale.toLowerCase().includes(searchQuery.toLowerCase()) ||



      entity.idfemale.toLowerCase().includes(searchQuery.toLowerCase()) ||



      entity.checkbox_field.toLowerCase().includes(searchQuery.toLowerCase()) ||



      entity.checkbox_field2.toLowerCase().includes(searchQuery.toLowerCase()) ||


entity.fileupload_fieldname &&        
entity.fileupload_fieldname.toLowerCase().includes(searchQuery.toLowerCase()) ||

entity.fileupload_field2name &&        
entity.fileupload_field2name.toLowerCase().includes(searchQuery.toLowerCase()) ||

entity.imageupload_fieldname &&        
entity.imageupload_fieldname.toLowerCase().includes(searchQuery.toLowerCase()) ||

entity.imageupload_field2name &&        
entity.imageupload_field2name.toLowerCase().includes(searchQuery.toLowerCase()) ||

entity.audio_fieldname &&        
entity.audio_fieldname.toLowerCase().includes(searchQuery.toLowerCase()) ||

entity.audio_field2name &&        
entity.audio_field2name.toLowerCase().includes(searchQuery.toLowerCase()) ||

entity.video_fieldname &&        
entity.video_fieldname.toLowerCase().includes(searchQuery.toLowerCase()) ||

entity.video_field2name &&        
entity.video_field2name.toLowerCase().includes(searchQuery.toLowerCase())     );
    setFilteredData(filtered);
  };

  const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  const generateBarcodeImage = async (ref) => {
    if (ref.current) {
      const canvas = await html2canvas(ref.current);
      const imgData = canvas.toDataURL("image/png");
      const link = document.createElement("a");
      link.href = imgData;
      link.download = "barcode.png";
      link.click();
    }
  };

  // Calculate items for current page
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredData.slice(indexOfFirstItem, indexOfLastItem);

  return (
    <div className="container mt-5">
      <ToastContainer />
      <h1 className="mb-4">Entity Table</h1>
      <div className="d-flex justify-content-between mb-3">
        <Button variant="primary" onClick={() => setShowAddModal(true)}>
          Add Entity
        </Button>
























 
        <Form.Control
          type="text"
          className="w-25"
          placeholder="Search..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
      </div>
      <Table striped bordered hover responsive variant="grey">
        <thead>
          <tr>
  <th>ismale</th>

  <th>idfemale</th>

    
 
<th>test1</th>
     


    
 
<th>t1</th>
     


 <th>fileupload_fieldname</th>
  <th>fileupload_fieldpath</th>

 <th>fileupload_field2name</th>
  <th>fileupload_field2path</th>

 <th>imageupload_fieldname</th>
  <th>imageupload_fieldpath</th>

 <th>imageupload_field2name</th>
  <th>imageupload_field2path</th>

 <th>audio_fieldname</th>
  <th>audio_fieldpath</th>

 <th>audio_field2name</th>
  <th>audio_field2path</th>

 <th>video_fieldname</th>
  <th>video_fieldpath</th>

 <th>video_field2name</th>
  <th>video_field2path</th>

<th>Action</th>
          </tr>
        </thead>
        <tbody >
          {currentItems.map((entity) => (
            <tr key={entity.id}>

              <td>{entity.ismale}</td>



              <td>{entity.idfemale}</td>


    
 
  <td>{entity.test1 ? "True" : "False"}</td>
     


    
 
  <td>{entity.t1 ? "True" : "False"}</td>
     


 <td>{entity.fileupload_fieldname}</td>

              <td>{entity.fileupload_fieldpath}</td>

 <td>{entity.fileupload_field2name}</td>

              <td>{entity.fileupload_field2path}</td>

 <td>{entity.imageupload_fieldname}</td>

              <td>{entity.imageupload_fieldpath}</td>

 <td>{entity.imageupload_field2name}</td>

              <td>{entity.imageupload_field2path}</td>

 <td>{entity.audio_fieldname}</td>

              <td>{entity.audio_fieldpath}</td>

 <td>{entity.audio_field2name}</td>

              <td>{entity.audio_field2path}</td>

 <td>{entity.video_fieldname}</td>

              <td>{entity.video_fieldpath}</td>

 <td>{entity.video_field2name}</td>

              <td>{entity.video_field2path}</td>

              <td>
                <Button
                  variant="warning"
                  size="sm"
                  className="me-2"
                  onClick={() => handleEdit(entity)}
                >
                  Update
                </Button>
























  	
                <Button
                  variant="danger"
                  size="sm"
                  onClick={() => {
                    setDeleteEntityId(entity.id);
                    setShowDeleteModal(true);
                  }}
                >
                  Delete
                </Button>
              </td>
            </tr>
          ))}
        </tbody>
      </Table>
      <Pagination className="d-flex justify-content-center mt-4">
        {Array.from(
          { length: Math.ceil(filteredData.length / itemsPerPage) },
          (_, index) => (
            <Pagination.Item
              key={index + 1}
              active={index + 1 === currentPage}
              onClick={() => handlePageChange(index + 1)}
            >
              {index + 1}
            </Pagination.Item>
          )
        )}
      </Pagination>
























       <Modal show={showEditModal} onHide={() => setShowEditModal(false)}>
        <Modal.Header closeButton>
          <Modal.Title>Edit Entity</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          {editEntity && (
            <Form>
<div className="form-group">
  <div className="container mt-4" style={{ width: '100%' }}>
    <div className="card p-4 shadow-sm rounded">
      <div className="row align-items-center">
        <div className="col-md-3">
        </div>
<Form.Group className="mb-3">
                <Form.Label>ismale</Form.Label>

 

                <Form.Check
                  type="radio"
                  label="no"
                  name="ismale"
                  value="no"
                  checked={editEntity.ismale === "no"}
                  onChange={handleEditChange}
          style={{
                  backgroundColor: '#f7f9fc',
                  border: '1px solid #ced4da',
                  borderRadius: '8px',
                  padding: '10px',
                  transition: 'border-color 0.3s ease, box-shadow 0.3s ease',
                }}
                onFocus={(e) => {
                  e.target.style.borderColor = '#007bff';
                  e.target.style.boxShadow = '0 0 8px rgba(0, 123, 255, 0.25)';
                }}
                onBlur={(e) => {
                  e.target.style.borderColor = '#ced4da';
                  e.target.style.boxShadow = 'none';
                }}

                />
 

 

                <Form.Check
                  type="radio"
                  label="yes"
                  name="ismale"
                  value="yes"
                  checked={editEntity.ismale === "yes"}
                  onChange={handleEditChange}
          style={{
                  backgroundColor: '#f7f9fc',
                  border: '1px solid #ced4da',
                  borderRadius: '8px',
                  padding: '10px',
                  transition: 'border-color 0.3s ease, box-shadow 0.3s ease',
                }}
                onFocus={(e) => {
                  e.target.style.borderColor = '#007bff';
                  e.target.style.boxShadow = '0 0 8px rgba(0, 123, 255, 0.25)';
                }}
                onBlur={(e) => {
                  e.target.style.borderColor = '#ced4da';
                  e.target.style.boxShadow = 'none';
                }}

                />
 

 </Form.Group>

<Form.Group className="mb-3">
                <Form.Label>idfemale</Form.Label>

 

                <Form.Check
                  type="radio"
                  label="no"
                  name="idfemale"
                  value="no"
                  checked={editEntity.idfemale === "no"}
                  onChange={handleEditChange}
          style={{
                  backgroundColor: '#f7f9fc',
                  border: '1px solid #ced4da',
                  borderRadius: '8px',
                  padding: '10px',
                  transition: 'border-color 0.3s ease, box-shadow 0.3s ease',
                }}
                onFocus={(e) => {
                  e.target.style.borderColor = '#007bff';
                  e.target.style.boxShadow = '0 0 8px rgba(0, 123, 255, 0.25)';
                }}
                onBlur={(e) => {
                  e.target.style.borderColor = '#ced4da';
                  e.target.style.boxShadow = 'none';
                }}

                />
 

 

                <Form.Check
                  type="radio"
                  label="yes"
                  name="idfemale"
                  value="yes"
                  checked={editEntity.idfemale === "yes"}
                  onChange={handleEditChange}
          style={{
                  backgroundColor: '#f7f9fc',
                  border: '1px solid #ced4da',
                  borderRadius: '8px',
                  padding: '10px',
                  transition: 'border-color 0.3s ease, box-shadow 0.3s ease',
                }}
                onFocus={(e) => {
                  e.target.style.borderColor = '#007bff';
                  e.target.style.boxShadow = '0 0 8px rgba(0, 123, 255, 0.25)';
                }}
                onBlur={(e) => {
                  e.target.style.borderColor = '#ced4da';
                  e.target.style.boxShadow = 'none';
                }}

                />
 

 </Form.Group>

<Form.Group className="mb-3">
                <Form.Label>checkbox Field</Form.Label>
  
 
  <Form.Check
    type="checkbox"
    label="test1"
    name="test1"
    checked={editEntity.test1}
    onChange={handleEditCheckboxChange}
  />
 

   

 </Form.Group>

<Form.Group className="mb-3">
                <Form.Label>checkbox Field2</Form.Label>
  
 
  <Form.Check
    type="checkbox"
    label="t1"
    name="t1"
    checked={editEntity.t1}
    onChange={handleEditCheckboxChange}
  />
 

   

 </Form.Group>

 <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>

 <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>

 <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="image/png, image/jpeg, image/jpg, image/gif, image/webp"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>

 <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="image/png, image/jpeg, image/jpg, image/gif, image/webp"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>


  <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="audio/mpeg, audio/wav, audio/ogg, audio/mp3, audio/aac"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>


  <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="audio/mpeg, audio/wav, audio/ogg, audio/mp3, audio/aac"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>


 
  <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="video/mp4, video/webm, video/ogg, video/x-matroska, video/avi"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>


 
  <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="video/mp4, video/webm, video/ogg, video/x-matroska, video/avi"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>

    
      </div>
    </div>
  </div>
</div>
          </Form>
          
          )}
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => setShowEditModal(false)}>
            Close
          </Button>
          <Button variant="primary" onClick={handleUpdate}>
            Save changes
          </Button>
        </Modal.Footer>
      </Modal>
      <Modal show={showAddModal} onHide={() => setShowAddModal(false)}>
        <Modal.Header closeButton>
          <Modal.Title>Add New Entity</Modal.Title>
        </Modal.Header>
        <Modal.Body>
        <Form>
      <div className="form-group">
  <div className="container mt-4" style={{ width: '100%' }}>
    <div className="card p-4 shadow-sm rounded">
      <div className="row align-items-center">
        <div className="col-md-3">
        </div>
<Form.Group className="mb-3">

              <Form.Label>ismale</Form.Label>

 
              <Form.Check
                type="radio"
                label="no"
                name="ismale"
                value="no"
                checked={newEntity.ismale === "no"}

                onChange={handleChange}
               style={{
                  backgroundColor: '#f7f9fc',
                  border: '1px solid #ced4da',
                  borderRadius: '8px',
                  padding: '10px',
                  transition: 'border-color 0.3s ease, box-shadow 0.3s ease',
                }}
                onFocus={(e) => {
                  e.target.style.borderColor = '#007bff';
                  e.target.style.boxShadow = '0 0 8px rgba(0, 123, 255, 0.25)';
                }}
                onBlur={(e) => {
                  e.target.style.borderColor = '#ced4da';
                  e.target.style.boxShadow = 'none';
                }}

              />  
 

 
              <Form.Check
                type="radio"
                label="yes"
                name="ismale"
                value="yes"
                checked={newEntity.ismale === "yes"}

                onChange={handleChange}
               style={{
                  backgroundColor: '#f7f9fc',
                  border: '1px solid #ced4da',
                  borderRadius: '8px',
                  padding: '10px',
                  transition: 'border-color 0.3s ease, box-shadow 0.3s ease',
                }}
                onFocus={(e) => {
                  e.target.style.borderColor = '#007bff';
                  e.target.style.boxShadow = '0 0 8px rgba(0, 123, 255, 0.25)';
                }}
                onBlur={(e) => {
                  e.target.style.borderColor = '#ced4da';
                  e.target.style.boxShadow = 'none';
                }}

              />  
 

            </Form.Group>


<Form.Group className="mb-3">

              <Form.Label>idfemale</Form.Label>

 
              <Form.Check
                type="radio"
                label="no"
                name="idfemale"
                value="no"
                checked={newEntity.idfemale === "no"}

                onChange={handleChange}
               style={{
                  backgroundColor: '#f7f9fc',
                  border: '1px solid #ced4da',
                  borderRadius: '8px',
                  padding: '10px',
                  transition: 'border-color 0.3s ease, box-shadow 0.3s ease',
                }}
                onFocus={(e) => {
                  e.target.style.borderColor = '#007bff';
                  e.target.style.boxShadow = '0 0 8px rgba(0, 123, 255, 0.25)';
                }}
                onBlur={(e) => {
                  e.target.style.borderColor = '#ced4da';
                  e.target.style.boxShadow = 'none';
                }}

              />  
 

 
              <Form.Check
                type="radio"
                label="yes"
                name="idfemale"
                value="yes"
                checked={newEntity.idfemale === "yes"}

                onChange={handleChange}
               style={{
                  backgroundColor: '#f7f9fc',
                  border: '1px solid #ced4da',
                  borderRadius: '8px',
                  padding: '10px',
                  transition: 'border-color 0.3s ease, box-shadow 0.3s ease',
                }}
                onFocus={(e) => {
                  e.target.style.borderColor = '#007bff';
                  e.target.style.boxShadow = '0 0 8px rgba(0, 123, 255, 0.25)';
                }}
                onBlur={(e) => {
                  e.target.style.borderColor = '#ced4da';
                  e.target.style.boxShadow = 'none';
                }}

              />  
 

            </Form.Group>


<Form.Group className="mb-3">
                <Form.Label>checkbox Field</Form.Label>
  
 

          <Form.Check
    type="checkbox"
    label="test1"
    name="test1"
    checked={newEntity.test1}
    onChange={handleCheckboxChange}
  />
   

 </Form.Group>

<Form.Group className="mb-3">
                <Form.Label>checkbox Field2</Form.Label>
  
 

          <Form.Check
    type="checkbox"
    label="t1"
    name="t1"
    checked={newEntity.t1}
    onChange={handleCheckboxChange}
  />
   

 </Form.Group>


 <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>


 <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>

 <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="image/png, image/jpeg, image/jpg, image/gif, image/webp"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>

 <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="image/png, image/jpeg, image/jpg, image/gif, image/webp"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>


  <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="audio/mpeg, audio/wav, audio/ogg, audio/mp3, audio/aac"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>


  <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="audio/mpeg, audio/wav, audio/ogg, audio/mp3, audio/aac"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>


 
  <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="video/mp4, video/webm, video/ogg, video/x-matroska, video/avi"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>


 
  <Form>
      <Form.Control 
        type="file" 
        label="Upload File" 
        onChange={handleFileChange} 
        accept="video/mp4, video/webm, video/ogg, video/x-matroska, video/avi"
      />
      {uploadProgress > 0 && (
        <ProgressBar now={uploadProgress} label={`${uploadProgress}%`} />
      )}
    </Form>

 </div>
    </div>
  </div>
</div>
</Form>

        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => setShowAddModal(false)}>
            Close
          </Button>
          <Button variant="primary" onClick={handleAdd







fileupload_field

fileupload_field2

imageupload_field

imageupload_field2

audio_field

audio_field2

video_field

video_field2

}>
            Add Entity
          </Button>
























        </Modal.Footer>
      </Modal>
      <Modal show={showDeleteModal} onHide={() => setShowDeleteModal(false)}>
        <Modal.Header closeButton>
          <Modal.Title>Confirm Delete</Modal.Title>
        </Modal.Header>
        <Modal.Body>Are you sure you want to delete this entity?</Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => setShowDeleteModal(false)}>
            Cancel
          </Button>
          <Button variant="danger" onClick={handleDelete}>
            Delete
          </Button>
        </Modal.Footer>
      </Modal>
    </div>
  );
};

export default EntityTable;
