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

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

 support: [{ 

 
    description: ""
 

 
    name: ""
 

 }]

    age: "",

    age2: "",

    addition: "",

    subtration: "",





  });
  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({
    name: "",

 support: [{ 

 
    description: ""
 

 
    name: ""
 

 }]

    age: "",

    age2: "",

    addition: "",

    subtration: "",





      });
      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 addNewField = () => {
    setNewEntity((prev) => ({
      ...prev,
      support: [...prev.support, { 

 
description: ""
 

 
name: ""
 
 
}],
    }));
  };









  const handlesChange = (e, index = null) => {
    const { name, value } = e.target;
  
    if (index !== null) {
      const updated = [...newEntity.support];
      updated[index] = { ...updated[index], [name]: value };
      setNewEntity({ ...newEntity, support: updated });
    } else {
      setNewEntity({ ...newEntity, [name]: value });
    }
  };
// For handling changes in the edit entity form
const handlesEditChange = (e, index = null) => {
  const { name, value } = e.target;

  if (index !== null) {
    const updated = [...editEntity.support];
    updated[index] = { ...updated[index], [name]: value };
    setEditEntity({ ...editEntity, support: updated });
  } else {
    setEditEntity({ ...editEntity, [name]: value });
  }
};







const calculate = (

 
age,
 

 
age2,
 

) => {
let arr = [];
let operation = "Addition";
// Loop through the list and push numbers

 
const _age = parseFloat(age) || 0;
arr.push(_age);
 

 
const _age2 = parseFloat(age2) || 0;
arr.push(_age2);
 

let addition;
// Perform the operation based on the operation variable
switch (operation) {
  case "Addition":
    addition = arr.reduce((acc, curr) => acc + curr, 0);
    break;
  case "Subtraction":
    addition = arr.reduce((acc, curr) => acc - curr);
    break;
  case "Multiplication":
    addition = arr.reduce((acc, curr) => acc * curr, 1);
    break;
  case "Division":
    addition = arr.reduce((acc, curr) => acc / curr);
    break;
   case "Concatination":
      default:
       
       addition = [
 
 
 age, 
  

 
 age2, 
  

 ].join(''); 
       break;
   
}
  return addition;
};


 useEffect(() => {
    const addnValue = calculate(

 
newEntity.age, 
 

 
newEntity.age2, 
 

);
    setNewEntity((prevState) => ({ ...prevState, addition: addnValue }));
  }, [

 
newEntity.age,
 

 
newEntity.age2,
 

]);

  useEffect(() => {
    if (editEntity) {
      const addnValue = calculate(

 
editEntity.age, 
 

 
editEntity.age2, 
 

);
      setEditEntity((prevState) => ({ ...prevState, addition: addnValue }));
    }
  }, [

 
editEntity?.age, 
 

 
editEntity?.age2, 
 

]);



const calculate = (

 
age,
 

 
age2,
 

) => {
let arr = [];
let operation = "Multiplication";
// Loop through the list and push numbers

 
const _age = parseFloat(age) || 0;
arr.push(_age);
 

 
const _age2 = parseFloat(age2) || 0;
arr.push(_age2);
 

let subtration;
// Perform the operation based on the operation variable
switch (operation) {
  case "Addition":
    subtration = arr.reduce((acc, curr) => acc + curr, 0);
    break;
  case "Subtraction":
    subtration = arr.reduce((acc, curr) => acc - curr);
    break;
  case "Multiplication":
    subtration = arr.reduce((acc, curr) => acc * curr, 1);
    break;
  case "Division":
    subtration = arr.reduce((acc, curr) => acc / curr);
    break;
   case "Concatination":
      default:
       
       subtration = [
 
 
 age, 
  

 
 age2, 
  

 ].join(''); 
       break;
   
}
  return subtration;
};


 useEffect(() => {
    const addnValue = calculate(

 
newEntity.age, 
 

 
newEntity.age2, 
 

);
    setNewEntity((prevState) => ({ ...prevState, subtration: addnValue }));
  }, [

 
newEntity.age,
 

 
newEntity.age2,
 

]);

  useEffect(() => {
    if (editEntity) {
      const addnValue = calculate(

 
editEntity.age, 
 

 
editEntity.age2, 
 

);
      setEditEntity((prevState) => ({ ...prevState, subtration: addnValue }));
    }
  }, [

 
editEntity?.age, 
 

 
editEntity?.age2, 
 

]);







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



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



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



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



 
String(entity.age).includes(searchQuery) ||
 

 
String(entity.age2).includes(searchQuery) ||
 
        
       


 
String(entity.age).includes(searchQuery) ||
 

 
String(entity.age2).includes(searchQuery) ||
 
        
       


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



      entity.value_list_field2.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>name</th>

  <th>support</th>

  <th>age</th>

  <th>age2</th>

  <th>addition</th>

  <th>subtration</th>





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

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



 
<td>{entity.support.map(p => p.description).join(", ")}</td>
 

 
<td>{entity.support.map(p => p.name).join(", ")}</td>
 



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



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



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



              <td>{entity.subtration}</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={showValulistModal}
        onHide={() => setShowValulistModal(false)}
        size="lg"
        centered
      >
        <Modal.Header closeButton>
          <Modal.Title>Added Entities</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          {data.length > 0 ? (
            <Table striped bordered hover responsive>
              <thead>
                <tr>
     
 
                  <th>age</th>
      

               
                </tr>
              </thead>
              <tbody>
                {data.map((entity, index) => (
                  <tr key={index}>
           
 
                    <td>{entity.age}</td>
                    

                  </tr>
                ))}
              </tbody>
            </Table>
          ) : (
            <p>No data available.</p>
          )}
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={(V) => setShowValulistModal(false)}>
            Close
          </Button>
        </Modal.Footer>
      </Modal>



      <Modal
        show={showValulistModal}
        onHide={() => setShowValulistModal(false)}
        size="lg"
        centered
      >
        <Modal.Header closeButton>
          <Modal.Title>Added Entities</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          {data.length > 0 ? (
            <Table striped bordered hover responsive>
              <thead>
                <tr>
     
 
                  <th>name</th>
      

 
                  <th>age2</th>
      

 
                  <th>age</th>
      

               
                </tr>
              </thead>
              <tbody>
                {data.map((entity, index) => (
                  <tr key={index}>
           
 
                    <td>{entity.name}</td>
                    

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

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

                  </tr>
                ))}
              </tbody>
            </Table>
          ) : (
            <p>No data available.</p>
          )}
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={(V) => setShowValulistModal(false)}>
            Close
          </Button>
        </Modal.Footer>
      </Modal>

       <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>
<label htmlFor="name" className="form-label">Name</label>
       
        <div className="col-md-9">
          <input
            type="text"
            className="form-control"
            id="name"
            name="name"
            value={editEntity.name}
            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>

 {editEntity.support.map((p, index) => (
              <Form.Group className="mb-3" key={index}>
                <Form.Label>support</Form.Label>
              
 
                <Form.Control
                  type="text"
                  name="description"
                  value={p.description}
                  onChange={(e) => handlesEditChange(e, index)}
                />
              </Form.Group>
            ))}
            <Button variant="secondary" onClick={addEditField}>
              Add Another
            </Button>
     

 
                <Form.Control
                  type="text"
                  name="name"
                  value={p.name}
                  onChange={(e) => handlesEditChange(e, index)}
                />
              </Form.Group>
            ))}
            <Button variant="secondary" onClick={addEditField}>
              Add Another
            </Button>
     


<Form.Group className="mb-3">
          <Form.Label>age</Form.Label>
          <Form.Control
            type="number"
            name="age"
            value={editEntity.age}
            onChange={handleEditChange}
            placeholder="Enter a age"
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>age2</Form.Label>
          <Form.Control
            type="number"
            name="age2"
            value={editEntity.age2}
            onChange={handleEditChange}
            placeholder="Enter a age2"
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>addition</Form.Label>

            </Form.Group>

<Form.Group className="mb-3">
              <Form.Label>result</Form.Label>
              <Form.Control
                type="text"
                name="addition"
                value={editEntity.addition}
                readOnly
              />
            </Form.Group>

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

            </Form.Group>

<Form.Group className="mb-3">
              <Form.Label>result</Form.Label>
              <Form.Control
                type="text"
                name="subtration"
                value={editEntity.subtration}
                readOnly
              />
            </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>
<label htmlFor="name" className="form-label">name</label>
         
        <div className="col-md-9">
          <input
            type="text"
            className="form-control"
            id="name"
            name="name"
            value={newEntity.name}
            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>

 {newEntity.support.map((p, index) => (
              <Form.Group className="mb-3" key={index}>
                <Form.Label>support</Form.Label>
              
 
                <Form.Control
                  type="text"
                  name="description"
                  value={p.description}
                  onChange={(e) => handlesChange(e, index)}
                />
              </Form.Group>
            ))}
            <Button variant="secondary" onClick={addNewField}>
              Add Another
            </Button>
     

 
                <Form.Control
                  type="text"
                  name="name"
                  value={p.name}
                  onChange={(e) => handlesChange(e, index)}
                />
              </Form.Group>
            ))}
            <Button variant="secondary" onClick={addNewField}>
              Add Another
            </Button>
     

         


<div className="form-group">
          <label htmlFor="age">age</label>
          <input
            type="number"
            className="form-control"
            id="age"
            name="age"
            value={newEntity.age}
            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>

<div className="form-group">
          <label htmlFor="age2">age2</label>
          <input
            type="number"
            className="form-control"
            id="age2"
            name="age2"
            value={newEntity.age2}
            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>addition</Form.Label>

            </Form.Group>

<Form.Group className="mb-3">
              <Form.Label>Result</Form.Label>
              <Form.Control
                type="text"
                name="addition"
                value={newEntity.addition}
                readOnly
              />
            </Form.Group>

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

            </Form.Group>

<Form.Group className="mb-3">
              <Form.Label>Result</Form.Label>
              <Form.Control
                type="text"
                name="subtration"
                value={newEntity.subtration}
                readOnly
              />
            </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>












 <td> 
            <Button variant="info" className="ms-3" onClick={() => setShowValulistModal(true)}>
        V
      </Button>
                </td>

 <td> 
            <Button variant="info" className="ms-3" onClick={() => setShowValulistModal(true)}>
        V
      </Button>
                </td>

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