import React, { useState, useEffect } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faEdit,
  faTrashAlt,
  faCogs,
  faArrowLeft,
  faFileExcel,
  faGrip,
  faGripHorizontal,
  faPlus,
  faGripVertical,
  faPlay,
} from "@fortawesome/free-solid-svg-icons";
import {
  Button,
  Form,
  Row,
  Col,
  InputGroup,
  FormControl,
  Modal,
  Dropdown,
} from "react-bootstrap";
import { Table } from "reactstrap";

import * as XLSX from "xlsx";
import "bootstrap/dist/css/bootstrap.min.css";
import "../../Dashboard/CSS/CSS/CommonStyle.css";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import Spinner from "../../../UIComponants/Spinner";
import { useNavigate } from "react-router-dom";
import { BsJournals } from "react-icons/bs";
import { FaSearch, FaTimes } from "react-icons/fa";
import { Pagination, PaginationItem, PaginationLink } from "reactstrap";
import ReportSqlBuilderApi from "APIServices/ReportSQLBuilderAPI";
import { addSQLReport } from "APIServices/AddReportSQLBuilderAPI";
import { UpdateReportSQLBuilder } from "APIServices/UpdateReportSQLBuilderAPI";
import { deleteReportSQL } from "APIServices/DeleteReportSQLAPI";
import ConfirmModal from "../../common/ConfirmModal";
import ReportBuilderService from "../../../APIServices/ReportBuilderService";


function UserDetailsView() {
  const [userDetails, setUserDetails] = useState([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [viewMode, setViewMode] = useState("table");
  const [loading, setLoading] = useState(true);
  const [recordsPerPage, setRecordsPerPage] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);
  const navigate = useNavigate();
  const [visibleColumns, setVisibleColumns] = useState({
    reportName: true,
    description: true,
    action: true,
    status: true,
  });
  const [showModal, setShowModal] = useState(false);
  const [showAddModal, setShowAddModal] = useState(false);
  const [selectedReport, setSelectedReport] = useState(null);
  const [editData, setEditData] = useState({
    reportName: "",
    description: "",
    active: false,
  });
  const [reportBuilderView, setReportBuilderView] = useState(null);



  const [newData, setNewData] = useState({
    reportName: "",
    description: "",
    active: false,
    isSql: true,
    Rpt_builder2_lines: [{ model: "" }],
  });

  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [deleteItem, setDeleteItem] = useState({ index: null, id: null });
  const [showReportConfigModal, setShowReportConfigModal] = useState(false);
  const [reportConfigData, setReportConfigData] = useState({
    conn_name: "",
    date_param_req: "",
    std_param_html: "",
    adhoc_param_html: "",
    column_str: "",
    sql_str: "",
    id: null
  });

  // Add state for database connections
  const [databaseConnections, setDatabaseConnections] = useState([]);

  // Extract fetchUserDetails into reusable function
  const fetchUserDetails = async () => {
    try {
      setLoading(true);
      const data = await ReportSqlBuilderApi.fetchUserDetails();
      
      setUserDetails(data);
      console.log('Data fetched successfully!', data);
      toast.success('Data fetched successfully!');
    } catch (error) {
      console.error('Error fetching user details:', error);
      toast.error('Failed to fetch user details.');
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    setTimeout(() => {
      setLoading(false);
    }, 3000);
  }, []);

  const handlePlayClick = () => {
    if (selectedReport) {
      goToRunner(selectedReport);
    } else {
      toast.error("No report selected to run.");
    }
  };

  const toggleColumn = (column) => {
    setVisibleColumns((prev) => ({
      ...prev,
      [column]: !prev[column],
    }));
  };
  const handleRecordsPerPageChange = (value) => {
    setRecordsPerPage(value);
    setCurrentPage(1);
  };

  const handleInputChange = (event) => {
    const { name, value, checked, type } = event.target;
    const inputValue = type === "checkbox" ? checked : value;

    if (showModal) {
      setEditData((prev) => ({ ...prev, [name]: inputValue }));
    } else if (showAddModal) {
      setNewData((prev) => ({ ...prev, [name]: inputValue }));
    }
  };

  const handleSubmit = async () => {
    try {
      // Call the API to update the report
      const updatedReport = await UpdateReportSQLBuilder(editData.id, editData);
      console.log("Update Report", updatedReport);
      toast.success("Report Updated successfully..")

      // Update the local state with the updated details
      const updatedDetails = userDetails.map((detail) =>
        detail.id === editData.id ? { ...detail, ...editData } : detail
      );

      setUserDetails(updatedDetails);
      setShowModal(false);
    } catch (error) {
      console.error("Error updating the report: ", error);
      toast.error("Failed to update report");
    }
  };

  const slicedUsers = userDetails
    .filter(
      (item) =>
        item.reportName &&
        item.reportName.toLowerCase().includes(searchQuery.toLowerCase())
    )
    .slice((currentPage - 1) * recordsPerPage, currentPage * recordsPerPage);
  const totalPages = Math.ceil(userDetails.length / recordsPerPage);
  const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
  };
  const handleSearch = (query) => {
    setSearchQuery(query);
  };

  const exportToExcel = () => {
    const worksheet = XLSX.utils.json_to_sheet([]);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "UserDetails");
    XLSX.writeFile(workbook, "UserDetails.xlsx");
  };

  const handleGoTo = (data) => {
    console.log("id: ", data.id);
    


    const hasReportData = data.rpt_builder2_lines?.some(line => line.model && line.model.trim() !== "");
    // Check if the report has configuration data
    if (hasReportData) {
      
        
        // If we reach here, the model has valid data, so open the modal
        fetchReportConfiguration(data.id, data);
    
    } else {
      // If there's no model data, navigate to reportQuery
      console.log("No model data, navigating to report query page");
      navigate("/admin/reportquery", { state: { id: data.id, reportData: data } });
    }
  };

  const handleRowClick = (report) => {
    // Fetch report configuration details
    fetchReportConfiguration(report.id, report);
  };

  const fetchDatabaseConnections = async () => {
    try {
      setLoading(true);
      const response = await ReportBuilderService.getDatabase();
      console.log("Database connections fetched: ", response);
      
      if (response && response.data) {
        setDatabaseConnections(response.data);
      } else {
        setDatabaseConnections([]);
      }
    } catch (error) {
      console.error("Error fetching database connections: ", error);
      toast.error("Failed to load database connections");
      setDatabaseConnections([]);
    } finally {
      setLoading(false);
    }
  };

  const fetchReportConfiguration = async (reportId, report) => {
    try {
      setLoading(true);
      // Fetch report configuration details
      console.log("calling get report by id: ",reportId," ",report )
      console.log("child id: ",report.rpt_builder2_lines[0].id)
      const response = await ReportBuilderService.getrbLineDetailsById(report.rpt_builder2_lines[0].id);
      console.log("Report configuration fetched: ", response);
      
      // Also fetch database connections for the dropdown
      await fetchDatabaseConnections();
      
      if (response && response.data) {
        // Parse the model data which contains all the configuration
        let configData = {};
        try {
          // If there's Rpt_builder2_lines data, use it
          if (report.Rpt_builder2_lines && report.Rpt_builder2_lines.length > 0) {
            const modelData = JSON.parse(report.Rpt_builder2_lines[0].model);
            configData = {
              conn_name: modelData.conn_name || "",
              date_param_req: modelData.date_param_req || "",
              std_param_html: modelData.std_param_html || "",
              adhoc_param_html: modelData.adhoc_param_html || "",
              column_str: modelData.column_str || "",
              sql_str: modelData.sql_str || "",
              id: report.rpt_builder2_lines[0].id
            };
            console.log("config data1: ",configData)
          } else {
            // Default empty values if data not available
            configData = {
              conn_name: "",
              date_param_req: "",
              std_param_html: "",
              adhoc_param_html: "",
              column_str: "",
              sql_str: "",
              id: report.rpt_builder2_lines[0].id
            };

            console.log("config data1: ",configData)
          }
        } catch (error) {
          console.error("Error parsing report configuration: ", error);
          toast.error("Failed to parse report configuration");
          configData = {
            conn_name: "",
            date_param_req: "",
            std_param_html: "",
            adhoc_param_html: "",
            column_str: "",
            sql_str: "",
            id: report.rpt_builder2_lines[0].id
          };
          console.log("config data2: ",configData)
        }
        
        setReportConfigData(configData);
        setShowReportConfigModal(true);
      } else {
        toast.error("No configuration data found for this report");
      }
    } catch (error) {
      console.error("Error fetching report configuration: ", error);
      toast.error("Failed to load report configuration");
    } finally {
      setLoading(false);
    }
  };

  const handleReportConfigClose = () => {
    setShowReportConfigModal(false);
  };

  const handleReportConfigChange = (e) => {
    const { name, value } = e.target;
    setReportConfigData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleReportConfigUpdate = async () => {
    try {
      setLoading(true);
      
      // Create the report data object
      const reportData = {
        conn_name: reportConfigData.conn_name,
        // folderName: "null", // Default folder name or fetch from somewhere
        sql_str: reportConfigData.sql_str,
        date_param_req: reportConfigData.date_param_req,
        column_str: reportConfigData.column_str,
        adhoc_param_html: reportConfigData.adhoc_param_html,
        std_param_html: reportConfigData.std_param_html,
      };

      const saveReportData = {
        header_id: reportConfigData.id,
        model: JSON.stringify(reportData),
      };
      console.log("report updating data: ",saveReportData)
      console.log("report id: ",reportConfigData.id)
      // Call the API to update the report configuration
      const response = await ReportBuilderService.updaterbLineData(saveReportData, reportConfigData.id);
      
      console.log("Report configuration updated: ", response);
      toast.success("Report configuration updated successfully");
      
      // Close the modal
      setShowReportConfigModal(false);
      
      // Refresh the report list to show updated data
      fetchUserDetails();
    } catch (error) {
      console.error("Error updating report configuration: ", error);
      toast.error("Failed to update report configuration");
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    const { id } = deleteItem;
    
    if (!id) {
      console.error("ID is undefined. Cannot delete.");
      toast.error("Invalid ID. Deletion failed.");
      return;
    }
    
    try {
      const deletedReport = await deleteReportSQL(id);
      console.log("Report deleted: ", deletedReport);
      toast.success("Report deleted successfully");
      
      // Update state by filtering out the deleted record by ID
      setUserDetails(userDetails.filter(item => item.id !== id));
    } catch (error) {
      console.error("Error in deleting report:", error.response || error.message);
      toast.error("Failed to delete report");
    }
  };

  const confirmDelete = (e, index, id, reportName) => {
    e.stopPropagation(); // Prevent row click event
    setDeleteItem({ index, id, reportName });
    setShowConfirmModal(true);
  };

  const handleEdit = (detail) => {
    console.log(detail); // Debugging line
    setEditData(detail);
    setShowModal(true);
  };

  const handleBack = () => {
    setReportBuilderView(null);
    setViewMode("cards");
  };

  const handleClose = () => {
    setShowModal(false);
  };

  const handleAddClose = () => {
    setShowAddModal(false);
  };

  const handleAddSubmit = async () => {
    try {
      console.log(newData)
      // Call the addSQLReport API and pass the newData as formData
      const addedReport = await addSQLReport(newData);

      // Update the state with the added report details from the API response
      setUserDetails((prevUserDetails) => [...prevUserDetails, addedReport]);

      // Reset the form fields
      setNewData({ 
        reportName: "", 
        description: "", 
        active: false,
        isSql: true
      });

      // Close the modal and show success toast
      setShowAddModal(false);
      toast.success("User report added successfully!");

      console.log("User report added successfully: ", addedReport);
    } catch (error) {
      // Handle any errors during the API call
      toast.error("Failed to add the user report. Please try again.");
      console.error("Error adding user report: ", error);
    }
  };


  const goToRunner = (report) => {
    console.log("Running report:", report);
    if (!report || typeof report.isSql === "undefined") {
      console.error("Invalid report object:", report);
      return; // Exit if report is not valid
    }

    console.log("Navigating to report runner page");
    //  navigate("/admin/report-runner");
    if (report.isSql) {
      navigate(`/admin/report-runner/${report.id}`);
    } else {
      navigate(`/admin/report-runner2/${report.id}`);
    }

    // if (report.isSql) {
    //   navigate(`report-runner/${report.id}`);
    // } else {
    //   navigate(`report-runner2/${report.id}`);
    // }
  };
  const renderTable = () => (
    <div className="table-responsive">
      <Table
        striped
        responsive
        hover
        className=" align-middle table-flush shadow-sm"
        
      >
        <thead className="custom_header ">
          <tr>
            <th className="text-center">Go To</th>
            <th className="text-center">Report Name</th>
            <th className="text-center">Description</th>
            <th className="text-center">Status</th>
            <th className="text-center">Actions</th>
            
          </tr>
        </thead>
        <tbody className="tbody">
          {slicedUsers.length === 0 ? (
            <tr>
              <td colSpan={5} className="text-center">
                No records found.
              </td>
            </tr>
          ) : (
            slicedUsers.filter((detail) => detail.isSql).map((detail, index) => (
              <tr
                key={index}
                className="table-row"
                style={{ cursor: "pointer" }}
                onClick={() => handleRowClick(detail)}
              >
                <td className="text-center">
                  <FontAwesomeIcon
                    icon={faCogs}
                    onClick={(e) => {
                      e.stopPropagation(); // Prevent row click event
                      handleGoTo(detail);
                    }}
                    style={{
                      cursor: "pointer",
                      fontSize: "1.2rem",
                      color: "#0E6591",
                    }}
                  />
                </td>
                <td>{detail.reportName}</td>
                <td>{detail.description || "No description available"}</td>
                <td
                  style={{
                    fontWeight: detail.active ? "bold" : "normal",
                    color: detail.active ? "green" : "red",
                    backgroundColor: detail.active
                      ? "rgba(0, 128, 0, 0.1)"
                      : "rgba(255, 0, 0, 0.1)",
                    padding: "2px 4px",
                    borderRadius: "4px",
                    textAlign: "center",
                  }}
                >
                  {detail.active ? "Active" : "Inactive"}
                </td>
                <td className="text-center">
                  <FontAwesomeIcon
                    icon={faEdit}
                    onClick={(e) => {
                      e.stopPropagation(); // Prevent row click event
                      handleEdit(detail);
                    }}
                    style={{
                      cursor: "pointer",
                      fontSize: "1rem",
                      color: "green",
                      marginRight: "15px",
                    }}
                  />
                  <FontAwesomeIcon
                    icon={faTrashAlt}
                    onClick={(e) => {
                      e.stopPropagation();
                      confirmDelete(e, index, detail.id, detail.reportName);
                    }}
                    style={{
                      cursor: "pointer",
                      fontSize: "1rem",
                      color: "#dc3545",
                    }}
                  />
                </td>
                
              </tr>
            ))
          )}
        </tbody>
      </Table>
    </div>
  );

  return (
    <div>
      {loading ? (
        <Spinner />
      ) : (
        <div className="user-details-wrapper">
          <div className="title_name">
            <h2>Report Builder (SQL)</h2>
          </div>

          <Row className="align-items-center my-3">
            <Col
              xs={12}
              md={8}
              lg={6}
              className="d-flex justify-content-center"
            >
              <InputGroup className="search-bar">
                <InputGroup.Text
                  style={{
                    backgroundColor: "#0E6591",
                    color: "#fff",
                  }}
                >
                  <FaSearch />
                </InputGroup.Text>
                <FormControl
                  placeholder="Search"
                  value={searchQuery}
                  onChange={(e) => handleSearch(e.target.value)}
                />
              </InputGroup>
            </Col>

            <Col xs={12} md={4} lg={6} className="d-flex justify-content-end">
            
              <Button variant="primary" size="sm" className="px-4 py-1 rounded-3 shadow-sm text-sm " onClick={() => navigate('/admin/report-runner')}>
                <FontAwesomeIcon icon={faGripVertical} /> Report Runner
              </Button>
              <Button variant="primary" size="sm" className="px-4 py-1 rounded-3 shadow-sm text-sm " onClick={() => setShowAddModal(true)}>
                <FontAwesomeIcon icon={faPlus}/> Add
              </Button>
          
            </Col>
          </Row>

          {renderTable()}

          {/* Manage Columns & Records Per Page */}
          <Row className="mt-4">
            <Col md={6} className="d-flex justify-content-start">
              <Dropdown>
                <Dropdown.Toggle
                  variant="outline-primary"
                  className="custom_manage_column_button"
                >
                  Manage Columns
                </Dropdown.Toggle>
                <Dropdown.Menu>
                  {Object.keys(visibleColumns).map((column) => (
                    <Dropdown.Item
                      key={column}
                      onClick={() => toggleColumn(column)}
                    >
                      <Form.Check
                        type="checkbox"
                        label={
                          column.charAt(0).toUpperCase() +
                          column.slice(1).toLowerCase()
                        }
                        checked={visibleColumns[column]}
                        readOnly
                        className="custom-checkbox"
                      />
                    </Dropdown.Item>
                  ))}
                </Dropdown.Menu>
              </Dropdown>
            </Col>

            <Col md={6} className="d-flex justify-content-end">
              <Dropdown>
                <Dropdown.Toggle
                  variant="outline-primary"
                  className="custom_manage_column_button px-4 py-2 border-2 rounded-3 shadow-sm"
                  id="dropdown-custom-components"
                >
                  <BsJournals />
                </Dropdown.Toggle>
                <Dropdown.Menu
                  className="border-0 rounded-3 shadow-lg"
                  align="end"
                >
                  {[1, 5, 10, 20, 50].map((number) => (
                    <Dropdown.Item
                      key={number}
                      onClick={() => handleRecordsPerPageChange(number)}
                      className="text-dark d-flex justify-content-between align-items-center"
                    >
                      <span>{number}</span>
                      <i
                        className="fa fa-check-circle"
                        style={{
                          display:
                            recordsPerPage === number ? "inline" : "none",
                        }}
                      />
                    </Dropdown.Item>
                  ))}
                </Dropdown.Menu>
              </Dropdown>
            </Col>
          </Row>

          <Pagination className="pagination">
            <PaginationItem disabled={currentPage === 1}>
              <PaginationLink
                previous
                onClick={() => handlePageChange(currentPage - 1)}
              />
            </PaginationItem>
            {[...Array(totalPages).keys()].map((pageNumber) => (
              <PaginationItem
                key={pageNumber + 1}
                active={currentPage === pageNumber + 1}
              >
                <PaginationLink
                  onClick={() => handlePageChange(pageNumber + 1)}
                >
                  {pageNumber + 1}
                </PaginationLink>
              </PaginationItem>
            ))}{" "}
            <PaginationItem disabled={currentPage === totalPages}>
              <PaginationLink
                next
                onClick={() => handlePageChange(currentPage + 1)}
              />
            </PaginationItem>
          </Pagination>

          {/* Edit form model */}
          <Modal show={showModal} onHide={handleClose} centered>
            <Modal.Header>
              <Modal.Title style={{ color: "#0E6591" }}>
                Edit User Detail
              </Modal.Title>
              {/* Custom Close Icon */}
              <div
                onClick={handleClose}
                style={{
                  cursor: "pointer",
                  color: "#0E6591",
                  fontSize: "1.5rem",
                  position: "absolute",
                  right: "15px", // Adjust position
                  top: "15px", // Adjust position
                }}
                aria-label="Close"
              >
                <FaTimes /> {/* FontAwesome close icon */}
              </div>
            </Modal.Header>
            <Modal.Body>
              <Form>
                <Form.Group controlId="formGroupName">
                  <Form.Label>Report Name</Form.Label>
                  <Form.Control
                    type="text"
                    name="reportName"
                    value={editData.reportName || ""}
                    onChange={(e) =>
                      setEditData({ ...editData, reportName: e.target.value })
                    }
                  />
                </Form.Group>
                <Form.Group controlId="formGroupDescription">
                  <Form.Label>Description</Form.Label>
                  <Form.Control
                    type="text"
                    value={editData.description}
                    className="custom-hover-border"
                    onChange={(e) =>
                      setEditData({ ...editData, description: e.target.value })
                    }
                  />
                </Form.Group>
                <Form.Group controlId="formGroupActive">
                  <Form.Check
                    type="checkbox"
                    label="Active"
                    checked={editData.active}
                    onChange={(e) =>
                      setEditData({ ...editData, active: e.target.checked })
                    }
                  />
                </Form.Group>
              </Form>
            </Modal.Body>
            <Modal.Footer>
              <Button
                variant="primary"
                onClick={handleSubmit}
                className="custom_button"
              >
                Save Changes
              </Button>
            </Modal.Footer>
          </Modal>

          {/* Add form model */}
          <Modal show={showAddModal} onHide={handleAddClose} centered>
            <Modal.Header>
              <Modal.Title style={{ color: "#0E6591" }}>
                Add New User Detail
              </Modal.Title>
              {/* Custom Close Icon */}
              <div
                onClick={handleAddClose} // Call the close function on click
                style={{
                  cursor: "pointer",
                  color: "#0E6591",
                  fontSize: "1.5rem",
                  position: "absolute",
                  right: "15px", // Adjust position
                  top: "15px", // Adjust position
                }}
                aria-label="Close"
              >
                <FaTimes /> {/* FontAwesome close icon */}
              </div>
            </Modal.Header>
            <Modal.Body>
              <Form>
                <Form.Group controlId="formGroupAddName" className="mb-3">
                  <Form.Label className="fw-bold">Report Name</Form.Label>
                  <Form.Control
                    type="text"
                    placeholder="Enter report name"
                    value={newData.reportName}
                    onChange={(e) =>
                      setNewData({ ...newData, reportName: e.target.value })
                    }
                    className="custom-hover-border shadow-sm"
                    required
                  />
                </Form.Group>

                <Form.Group
                  controlId="formGroupAddDescription"
                  className="mb-3"
                >
                  <Form.Label className="fw-bold">Description</Form.Label>
                  <Form.Control
                    type="text"
                    placeholder="Enter description"
                    value={newData.description}
                    onChange={(e) =>
                      setNewData({ ...newData, description: e.target.value })
                    }
                    className="custom-hover-border shadow-sm"
                    required
                  />
                </Form.Group>

                <Form.Group controlId="formGroupAddActive" className="mb-3">
                  <Form.Check
                    type="checkbox"
                    label="Active"
                    checked={newData.active}
                    onChange={(e) =>
                      setNewData({ ...newData, active: e.target.checked })
                    }
                    className="custom-checkbox shadow-sm"
                  />
                </Form.Group>
              </Form>
            </Modal.Body>
            <Modal.Footer className="justify-content-between">
              <Button
                variant="primary"
                onClick={handleAddClose}
                className="custom_button px-4"
              >
                Cancel
              </Button>
              <Button
                variant="primary"
                onClick={handleAddSubmit}
                className="custom_button px-4"
              >
                Add User Detail
              </Button>
            </Modal.Footer>
          </Modal>
        </div>
      )}
      
      {/* Confirmation Modal */}
      <ConfirmModal
        show={showConfirmModal}
        onHide={() => setShowConfirmModal(false)}
        onConfirm={handleDelete}
        title="Confirm Deletion"
        message={`Are you sure you want to delete "${deleteItem.reportName || 'this report'}"? This action cannot be undone.`}
        confirmLabel="Delete"
        cancelLabel="Cancel"
        variant="danger"
      />

      {/* Report Configuration Modal */}
      <Modal show={showReportConfigModal} onHide={handleReportConfigClose} size="lg" centered>
        <Modal.Header>
          <Modal.Title style={{ color: "#59a5d8" }}>
            Report Configuration
          </Modal.Title>
          <div
            onClick={handleReportConfigClose}
            style={{
              cursor: "pointer",
              color: "#59a5d8",
              fontSize: "1.5rem",
              position: "absolute",
              right: "15px",
              top: "15px",
            }}
            aria-label="Close"
          >
            <FaTimes />
          </div>
        </Modal.Header>
        <Modal.Body>
          <Form>
            <Row>
              <Col md={6}>
                <Form.Group controlId="formConnectionName" className="mb-3">
                  <Form.Label className="fw-bold">Connection Name</Form.Label>
                  <Form.Select
                    name="conn_name"
                    value={reportConfigData.conn_name}
                    onChange={handleReportConfigChange}
                    className="custom-hover-border shadow-sm"
                  >
                    <option value="">Select Database Connection</option>
                    {databaseConnections.map((db, index) => (
                      <option key={index} value={db.name}>
                        {db.name}
                      </option>
                    ))}
                  </Form.Select>
                  {loading && <div className="text-muted small mt-1">Loading connections...</div>}
                </Form.Group>
              </Col>
              <Col md={6}>
                <Form.Group controlId="formDateParamReq" className="mb-3">
                  <Form.Label className="fw-bold">Date Parameter Required</Form.Label>
                  <Form.Select
                    name="date_param_req"
                    value={reportConfigData.date_param_req}
                    onChange={handleReportConfigChange}
                    className="custom-hover-border shadow-sm"
                  >
                    <option value="">Select Option</option>
                    <option value="Yes">Yes</option>
                    <option value="No">No</option>
                  </Form.Select>
                </Form.Group>
              </Col>
            </Row>
            
            <Form.Group controlId="formSqlStr" className="mb-3">
              <Form.Label className="fw-bold">SQL String</Form.Label>
              <Form.Control
                as="textarea"
                rows={5}
                name="sql_str"
                value={reportConfigData.sql_str}
                onChange={handleReportConfigChange}
                className="custom-hover-border shadow-sm"
                style={{ fontFamily: "monospace" }}
              />
            </Form.Group>
            
            <Form.Group controlId="formColumnStr" className="mb-3">
              <Form.Label className="fw-bold">Column String (html)</Form.Label>
              <Form.Control
                as="textarea"
                rows={3}
                name="column_str"
                value={reportConfigData.column_str}
                onChange={handleReportConfigChange}
                className="custom-hover-border shadow-sm"
              />
            </Form.Group>
            
            <Row>
              <Col md={6}>
                <Form.Group controlId="formStdParamHtml" className="mb-3">
                  <Form.Label className="fw-bold">Standard Parameter String (html)</Form.Label>
                  <Form.Control
                    as="textarea"
                    rows={3}
                    name="std_param_html"
                    value={reportConfigData.std_param_html}
                    onChange={handleReportConfigChange}
                    className="custom-hover-border shadow-sm"
                  />
                </Form.Group>
              </Col>
              <Col md={6}>
                <Form.Group controlId="formAdhocParamHtml" className="mb-3">
                  <Form.Label className="fw-bold">Adhoc Parameter String (html)</Form.Label>
                  <Form.Control
                    as="textarea"
                    rows={3}
                    name="adhoc_param_html"
                    value={reportConfigData.adhoc_param_html}
                    onChange={handleReportConfigChange}
                    className="custom-hover-border shadow-sm"
                  />
                </Form.Group>
              </Col>
            </Row>
          </Form>
        </Modal.Body>
        <Modal.Footer>
          <Button
            variant="secondary"
            onClick={handleReportConfigClose}
            className="px-4"
          >
            Cancel
          </Button>
          <Button
            variant="primary"
            onClick={handleReportConfigUpdate}
            className="custom_button px-4"
            style={{ backgroundColor: "#59a5d8" }}
          >
            Update Configuration
          </Button>
        </Modal.Footer>
      </Modal>
    </div>
  );
}

export default UserDetailsView;
