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}Adv3/Adv3`;
const REACT_APP_API_TOKEN = localStorage.getItem("authToken")

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




    dynamic: "",

    country: "",

    state: "",

    stmlit: "",

    stmmlt2: "",

 dy2: "",
 dy2name: "",

 dy1: "",
 dy1name: "",

    dymlti1: "",

    dymlt2: "",

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
















  setNewEntity({
    ...newEntity,
    dy2: 1,  
  });




  setNewEntity({
    ...newEntity,
    dy1: 1,  
  });






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






















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




    dynamic: "",

    country: "",

    state: "",

    stmlit: "",

    stmmlt2: "",

 dy2: "",
 dy2name: "",

 dy1: "",
 dy1name: "",

    dymlti1: "",

    dymlt2: "",

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










({
      
      stmlit: entity.stmlit.split(", ")   // Convert to an array for editing
    });

({
      
      stmmlt2: entity.stmmlt2.split(", ")   // Convert to an array for editing
    });










    setShowEditModal(true);
  };

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

const [mydatas, setmyDatas] = useState([]);
const mydata = async () => {
    let url = `${process.env.REACT_APP_API_URL}/Listtest`;
    const response = await axios.get(url, {
        headers: { Authorization: `Bearer ${REACT_APP_API_TOKEN}` },
    });
    const fetchedData = response.data;
      setmyDatas(fetchedData); 
   
    console.log(fetchedData);
  
}
  useEffect(() => {
    mydata();
  }, []);




 const filterColumns = (item) => {
    return Object.keys(item).filter(key => !excludedColumns.includes(key));
  };
  const excludedColumns = [
    'createdAt', 'createdBy', 'updatedBy', 'updatedAt', 
    'accountId', 'extn1', 'extn2', 'extn3', 'extn4', 'extn5', 
    'extn6', 'extn7', 'extn8', 'extn9', 'extn10', 'extn11', 
    'extn12', 'extn13', 'extn14', 'extn15', 'id'
  ];

const [mydatas, setmyDatas] = useState([]);
const mydata = async () => {
    let url = `${process.env.REACT_APP_API_URL}/Listtest`;
    const response = await axios.get(url, {
        headers: { Authorization: `Bearer ${REACT_APP_API_TOKEN}` },
    });
    const fetchedData = response.data;
      setmyDatas(fetchedData); 
   
    console.log(fetchedData);
  
}
  useEffect(() => {
    mydata();
  }, []);




 const filterColumns = (item) => {
    return Object.keys(item).filter(key => !excludedColumns.includes(key));
  };
  const excludedColumns = [
    'createdAt', 'createdBy', 'updatedBy', 'updatedAt', 
    'accountId', 'extn1', 'extn2', 'extn3', 'extn4', 'extn5', 
    'extn6', 'extn7', 'extn8', 'extn9', 'extn10', 'extn11', 
    'extn12', 'extn13', 'extn14', 'extn15', 'id'
  ];



  const Options = [
       
           
      "bharat",
      

           
      "nepal",
      

   ];

  const Options = [
       
           
      "maharastra",
      

           
      "bihar",
      

   ];

  const Options = [
       
           
      "bihar",
      

           
      "sikkim",
      

   ];


const handleMultiAdd = async () => {


    try {
      const token = getToken();
      const entityToAdd = {
        countrys: newEntity.stmlit, 
      };
      await axios.post(API_URL,entityToAdd, {
        headers: { Authorization: `Bearer ${token}` },
        }, {

      
      });
      fetchData();
      setNewEntity({
    stmlit: "",

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

const handleMultiUpdate = async () => {
    try {
      const token = getToken();
      const entityToUpdate = {
        stmlit: editEntity.stmlit, 
      };
      await axios.put(`${API_URL}/${editEntity.id}`, entityToUpdate, {
        headers: { Authorization: `Bearer ${token}` },
      });
      fetchData();
      setShowEditModal(false);
      toast.success("Successfully updated!");
    } catch (error) {
      console.error("Error updating data:", error);
      toast.error("Error updating entity. Please try again.");
    }
  };

  const Options = [
       
           
      "p2",
      

           
      "p3",
      

           
      "ap",
      

   ];


const handleMultiAdd = async () => {


    try {
      const token = getToken();
      const entityToAdd = {
        countrys: newEntity.stmmlt2, 
      };
      await axios.post(API_URL,entityToAdd, {
        headers: { Authorization: `Bearer ${token}` },
        }, {

      
      });
      fetchData();
      setNewEntity({
    stmmlt2: "",

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

const handleMultiUpdate = async () => {
    try {
      const token = getToken();
      const entityToUpdate = {
        stmmlt2: editEntity.stmmlt2, 
      };
      await axios.put(`${API_URL}/${editEntity.id}`, entityToUpdate, {
        headers: { Authorization: `Bearer ${token}` },
      });
      fetchData();
      setShowEditModal(false);
      toast.success("Successfully updated!");
    } catch (error) {
      console.error("Error updating data:", error);
      toast.error("Error updating entity. Please try again.");
    }
  };


 

const fetch_name = async () => {
try {
    const token = getToken();
    const url = `${process.env.REACT_APP_API_URL}/Listtest_ListFilter1/Listtest_ListFilter1`;
    const response = await axios.get(url, {
        headers: { Authorization: `Bearer ${token}` },
    });
    const data = response.data;
 const countries = data.map((country) => ({
    label: country.name,  
      value: country.id,  
    }));
    setOptions(countries);
    console.log(data);
  } catch (error) {
    console.error("Error fetching namesan data:", error);
  }
};
 useEffect(() => {
  fetch_name();
  fetchData();
}, []);
 



 

const fetch_name = async () => {
try {
    const token = getToken();
    const url = `${process.env.REACT_APP_API_URL}/Listtest_ListFilter1/Listtest_ListFilter1`;
    const response = await axios.get(url, {
        headers: { Authorization: `Bearer ${token}` },
    });
    const data = response.data;
 const countries = data.map((country) => ({
    label: country.name,  
      value: country.id,  
    }));
    setOptions(countries);
    console.log(data);
  } catch (error) {
    console.error("Error fetching namesan data:", error);
  }
};
 useEffect(() => {
  fetch_name();
  fetchData();
}, []);
 



const Options = [

 
  { value: "name", label: "Name" },
 

];



const Options = [

 
  { value: "name", label: "Name" },
 

];



   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.datagrid_field.toLowerCase().includes(searchQuery.toLowerCase()) ||



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



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



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



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



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



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



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



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



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



      entity.dymlt2.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>dynamic</th>

  <th>country</th>

  <th>state</th>

  <th>stmlit</th>

  <th>stmmlt2</th>

  <th>dy2</th>

  <th>dy1</th>

  <th>dymlti1</th>

  <th>dymlt2</th>

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

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



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



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



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



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



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



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



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


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


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



              <td>{entity.dymlt2}</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>
  <div>
      <h2>Data Grid</h2>
      {mydatas.length > 0 ? (
           <table border="1" style={{ borderCollapse: 'collapse', width: '100%' }}>
          <thead>
            <tr>
              {/* Generate table headers dynamically, excluding certain columns */}
              {filterColumns(mydatas[0]).map((key, index) => (
                <th key={index} style={{ border: '2px solid #fff', padding: '8px', textAlign: 'left' }}>{key}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {/* Generate table rows dynamically, excluding certain columns */}
            {mydatas.map((item, index) => (
             <tr key={index}>
             {filterColumns(item).map((key, i) => (
               <td key={i} style={{ border: '1px solid #fff', padding: '8px' }}>{item[key]}</td>
             ))}
              </tr>
            ))}
          </tbody>
        </table>
      ) : (
        <p>Loading data...</p> 
      )}
    </div>

  <div>
      <h2>Data Grid</h2>
      {mydatas.length > 0 ? (
           <table border="1" style={{ borderCollapse: 'collapse', width: '100%' }}>
          <thead>
            <tr>
              {/* Generate table headers dynamically, excluding certain columns */}
              {filterColumns(mydatas[0]).map((key, index) => (
                <th key={index} style={{ border: '2px solid #fff', padding: '8px', textAlign: 'left' }}>{key}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {/* Generate table rows dynamically, excluding certain columns */}
            {mydatas.map((item, index) => (
             <tr key={index}>
             {filterColumns(item).map((key, i) => (
               <td key={i} style={{ border: '1px solid #fff', padding: '8px' }}>{item[key]}</td>
             ))}
              </tr>
            ))}
          </tbody>
        </table>
      ) : (
        <p>Loading data...</p> 
      )}
    </div>

<label htmlFor="dynamic" className="form-label">Dynamic</label>
       
        <div className="col-md-9">
          <input
            type="text"
            className="form-control"
            id="dynamic"
            name="dynamic"
            value={editEntity.dynamic}
            onChange={handleEditChange}
            required
            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';
            }}
          />
        </div>

   <Form.Group className="mb-3">
              <Form.Label>country</Form.Label>
              <Form.Control
                as="select"
                name="country"
                value={editEntity.country}
                onChange={handleEditChange}
                className="bg-secondary text-light"
              >
                <option value="">Select country</option>
                {Options.map((option) => (
                  <option key={option} value={option}>
                    {option}
                  </option>
                ))}
              </Form.Control>
            </Form.Group>

   <Form.Group className="mb-3">
              <Form.Label>state</Form.Label>
              <Form.Control
                as="select"
                name="state"
                value={editEntity.state}
                onChange={handleEditChange}
                className="bg-secondary text-light"
              >
                <option value="">Select state</option>
                {Options.map((option) => (
                  <option key={option} value={option}>
                    {option}
                  </option>
                ))}
              </Form.Control>
            </Form.Group>

 <Form.Group className="mb-3">
              <Form.Label>stmlit</Form.Label>
              <Form.Control
                  as="select"
                  multiple
                  value={editEntity.stmlit.split(", ")} 
                  onChange={(e) => {
                    const selectedCountries = Array.from(e.target.selectedOptions, option => option.value);
                    setEditEntity({ ...editEntity, stmlit: selectedCountries.join(", ") }); // Join back to string
                  }}
                  className="bg-secondary text-light"
                >
                  {Options.map((option) => (
                    <option key={option} value={option}>
                      {option}
                    </option>
                  ))}
                </Form.Control>
            </Form.Group>


 <Form.Group className="mb-3">
              <Form.Label>stmmlt2</Form.Label>
              <Form.Control
                  as="select"
                  multiple
                  value={editEntity.stmmlt2.split(", ")} 
                  onChange={(e) => {
                    const selectedCountries = Array.from(e.target.selectedOptions, option => option.value);
                    setEditEntity({ ...editEntity, stmmlt2: selectedCountries.join(", ") }); // Join back to string
                  }}
                  className="bg-secondary text-light"
                >
                  {Options.map((option) => (
                    <option key={option} value={option}>
                      {option}
                    </option>
                  ))}
                </Form.Control>
            </Form.Group>


<Form.Group className="mb-3">
 <Form.Label>dy2</Form.Label>
 <Select
                options={options}  // Options from the fetch
                value={options.find(option => option.label === editEntity.dy2name) || null} 
                onChange={(selectedOption) => {
                  if (selectedOption) {
                    setEditEntity({
                      ...editEntity,
                      dynamicfldsname: selectedOption.label,  
                    });
                  }
                }}
                isSearchable={false}
                placeholder="Select an option"
              />
            </Form.Group>


<Form.Group className="mb-3">
 <Form.Label>dy1</Form.Label>
 <Select
                options={options}  // Options from the fetch
                value={options.find(option => option.label === editEntity.dy1name) || null} 
                onChange={(selectedOption) => {
                  if (selectedOption) {
                    setEditEntity({
                      ...editEntity,
                      dynamicfldsname: selectedOption.label,  
                    });
                  }
                }}
                isSearchable={false}
                placeholder="Select an option"
              />
            </Form.Group>


 <Form.Group className="mb-3">
 <Form.Label>dymlti1 </Form.Label>
          <Select
            isMulti
            options={Options}
            value={editEntity.dymlti1.split(",").map((value) => ({
              value: value,
              label: Options.find((opt) => opt.value === value)?.label || value,
            }))}
            onChange={(selectedOptions) => {
              const selectedValues = selectedOptions.map((opt) => opt.value).join(",");
              setEditEntity({ ...editEntity, dymlti1: selectedValues });
            }}
            className="bg-secondary text-dark"
          />
        </Form.Group>

 <Form.Group className="mb-3">
 <Form.Label>dymlt2 </Form.Label>
          <Select
            isMulti
            options={Options}
            value={editEntity.dymlt2.split(",").map((value) => ({
              value: value,
              label: Options.find((opt) => opt.value === value)?.label || value,
            }))}
            onChange={(selectedOptions) => {
              const selectedValues = selectedOptions.map((opt) => opt.value).join(",");
              setEditEntity({ ...editEntity, dymlt2: selectedValues });
            }}
            className="bg-secondary text-dark"
          />
        </Form.Group>

    
      </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>
  <div>
      <h2>Data Grid</h2>
      {mydatas.length > 0 ? (
           <table border="1" style={{ borderCollapse: 'collapse', width: '100%' }}>
          <thead>
            <tr>
              {/* Generate table headers dynamically, excluding certain columns */}
              {filterColumns(mydatas[0]).map((key, index) => (
                <th key={index} style={{ border: '2px solid #fff', padding: '8px', textAlign: 'left' }}>{key}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {/* Generate table rows dynamically, excluding certain columns */}
            {mydatas.map((item, index) => (
             <tr key={index}>
             {filterColumns(item).map((key, i) => (
               <td key={i} style={{ border: '1px solid #fff', padding: '8px' }}>{item[key]}</td>
             ))}
              </tr>
            ))}
          </tbody>
        </table>
      ) : (
        <p>Loading data...</p> 
      )}
    </div>

  <div>
      <h2>Data Grid</h2>
      {mydatas.length > 0 ? (
           <table border="1" style={{ borderCollapse: 'collapse', width: '100%' }}>
          <thead>
            <tr>
              {/* Generate table headers dynamically, excluding certain columns */}
              {filterColumns(mydatas[0]).map((key, index) => (
                <th key={index} style={{ border: '2px solid #fff', padding: '8px', textAlign: 'left' }}>{key}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {/* Generate table rows dynamically, excluding certain columns */}
            {mydatas.map((item, index) => (
             <tr key={index}>
             {filterColumns(item).map((key, i) => (
               <td key={i} style={{ border: '1px solid #fff', padding: '8px' }}>{item[key]}</td>
             ))}
              </tr>
            ))}
          </tbody>
        </table>
      ) : (
        <p>Loading data...</p> 
      )}
    </div>

<label htmlFor="dynamic" className="form-label">dynamic</label>
         
        <div className="col-md-9">
          <input
            type="text"
            className="form-control"
            id="dynamic"
            name="dynamic"
            value={newEntity.dynamic}
            onChange={handleChange}
            required
            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';
            }}
          />
        </div>

   <Form.Group className="mb-3">
              <Form.Label>country</Form.Label>
              <Form.Control
                as="select"
                name="country"
                value={newEntity.country}
                onChange={handleChange}
                className="bg-secondary text-light"
              >
                <option value="">Select country</option>
                {Options.map((option) => (
                  <option key={option} value={option}>
                    {option}
                  </option>
                ))}
              </Form.Control>
            </Form.Group>

   <Form.Group className="mb-3">
              <Form.Label>state</Form.Label>
              <Form.Control
                as="select"
                name="state"
                value={newEntity.state}
                onChange={handleChange}
                className="bg-secondary text-light"
              >
                <option value="">Select state</option>
                {Options.map((option) => (
                  <option key={option} value={option}>
                    {option}
                  </option>
                ))}
              </Form.Control>
            </Form.Group>

<Form.Group className="mb-3">
              <Form.Label>stmlit</Form.Label>
              <Form.Control
                as="select"
                multiple
                value={newEntity.stmlit.split(", ")} // Split string into array for multiple selection
                onChange={(e) => {
                  const selectedCountries = Array.from(e.target.selectedOptions, option => option.value);
                  setNewEntity({ stmlit: selectedCountries.join(", ") }); // Join back to string
                }}
                className="bg-secondary text-light"
              >
                {Options.map((option) => (
                  <option key={option} value={option}>
                    {option}
                  </option>
                ))}
              </Form.Control>
            </Form.Group>


<Form.Group className="mb-3">
              <Form.Label>stmmlt2</Form.Label>
              <Form.Control
                as="select"
                multiple
                value={newEntity.stmmlt2.split(", ")} // Split string into array for multiple selection
                onChange={(e) => {
                  const selectedCountries = Array.from(e.target.selectedOptions, option => option.value);
                  setNewEntity({ stmmlt2: selectedCountries.join(", ") }); // Join back to string
                }}
                className="bg-secondary text-light"
              >
                {Options.map((option) => (
                  <option key={option} value={option}>
                    {option}
                  </option>
                ))}
              </Form.Control>
            </Form.Group>


  <Form.Group className="mb-3">
  <Form.Label>dy2</Form.Label>
  <Select
                options={options}  // Options from the fetch
                value={options.find((option) => option.label === newEntity.dy2name) || null}  
                onChange={(selectedOption) => {
                  if (selectedOption) {
                    setNewEntity({
                      ...newEntity,
                      dynamicfldsname: selectedOption.label,
                    });
                  }
                }}
                isSearchable={false}
                placeholder="Select an option"
              />
            </Form.Group>

  <Form.Group className="mb-3">
  <Form.Label>dy1</Form.Label>
  <Select
                options={options}  // Options from the fetch
                value={options.find((option) => option.label === newEntity.dy1name) || null}  
                onChange={(selectedOption) => {
                  if (selectedOption) {
                    setNewEntity({
                      ...newEntity,
                      dynamicfldsname: selectedOption.label,
                    });
                  }
                }}
                isSearchable={false}
                placeholder="Select an option"
              />
            </Form.Group>

<Form.Group className="mb-3">
 <Form.Label>dymlti1</Form.Label>
        <Select
          isMulti
          options={Options}
          onChange={(selectedOptions) => {
            const selectedValues = selectedOptions.map((opt) => opt.value).join(",");
            setNewEntity({ ...newEntity, dymlti1: selectedValues });
          }}
          className="bg-secondary text-dark"
        />
      </Form.Group>

<Form.Group className="mb-3">
 <Form.Label>dymlt2</Form.Label>
        <Select
          isMulti
          options={Options}
          onChange={(selectedOptions) => {
            const selectedValues = selectedOptions.map((opt) => opt.value).join(",");
            setNewEntity({ ...newEntity, dymlt2: selectedValues });
          }}
          className="bg-secondary text-dark"
        />
      </Form.Group>

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

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





















}>
            Add Entity
          </Button>










  <Button variant="primary" onClick={handleMultiAdd}>
            Add Entity
          </Button>

  <Button variant="primary" onClick={handleMultiAdd}>
            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;
