// Report Builder Query Component - SQL Worksheet interface for database operations

import React, { useEffect, useState, useRef } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import ReportBuilderService from "../../../APIServices/ReportBuilderService";
import {
  Container,
  Row,
  Col,
  Button,
  Input,
  FormGroup,
  Label,
  TabContent,
  TabPane,
  Nav,
  NavItem,
  NavLink,
  Table,
  Modal,
  ModalBody,
  ModalHeader,
  ModalFooter,
  Pagination,
  PaginationItem,
  PaginationLink,
  Spinner,
  Form,
  Alert
} from "reactstrap";
import classnames from "classnames";
import { toast } from "react-toastify";
import Multiselect from 'multiselect-react-dropdown';

/**
 * ReportQuery Component
 * Provides a UI for building SQL queries, managing database connections,
 * and generating reports.
 */
const ReportQuery = ({
  loading,
  errortb,
  onTableNameClick,
  colname1,
  errorcl,
  colname,
  queryData,
  selectQuery,
  onCreate,
  rowSelected,
  deleteHandler,
}) => {
  // ================= STATE MANAGEMENT =================
  
  // Data lists and selections
  const [allColumnList, setAllColumnList] = useState([]); // List of all columns from selected tables
  const [tableList, setTableList] = useState([]); // List of tables in selected database
  const [selectedTableQuery, setSelectedTableQuery] = useState(""); // Query with selected tables
  const [selectedDatabase, setSelectedDatabase] = useState(""); // Currently selected database connection string
  const [data, setData] = useState([]); // Generic data list used for various purposes
  const [filteredData, setFilteredData] = useState([]); // Filtered data for display
  const [databaseList, setDatabaseList] = useState([]); // List of database connections
  const [databaseConnections, setDatabaseConnections] = useState([]); // List of database connections with details
  const [collist, setCollist] = useState([]); // List of columns for a specific table
  const [filteredCollist, setFilteredCollist] = useState(collist); // Filtered columns for display
  
  // Selected items and query building
  const [selectedTable, setSelectedTable] = useState([]); // Selected tables
  const [selectedCol, setSelectedCol] = useState([]); // Selected columns
  const [selectedCondition, setSelectedCondition] = useState([]); // Selected WHERE conditions
  const [selectedParameter, setSelectedParameter] = useState([]); // Selected parameters
  const [selectedQuery, setSelectedQuery] = useState(""); // Current SQL query
  const [columnAliases, setColumnAliases] = useState({}); // Aliases for columns
  
  // Database connection and report parameters
  const [databaseName, setDatabaseName] = useState(""); // Name of the selected database
  const [dataParameter, setDataParameter] = useState("null"); // Data parameters required for the report
  const [folderName, setFolderName] = useState("null"); // Folder for storing the report
  
  // UI state management
  const [isOpen, setIsOpen] = useState(false); // Generic modal state
  const [isQueryModalOpen, setIsQueryModalOpen] = useState(false); // Query selection modal
  const [isColumnModalOpen, setIsColumnModalOpen] = useState(false); // Column selection modal
  const [isModalOpen, setIsModalOpen] = useState(false); // Database selection modal
  const [isConditionModalOpen, setIsConditionModalOpen] = useState(false); // Condition modal
  const [activeTab, setActiveTab] = useState(0); // Active tab index
  const [tabs, setTabs] = useState(["Tab 1"]); // List of tabs
  const [msg, setMsg] = useState(""); // Message to display to the user
  const [sqlQuery, setSqlQuery] = useState(""); // SQL query editor text
  
  // Table and condition data
  const [conditionData, setConditionData] = useState([]); // Condition data for WHERE clause
  const [columnData, setColumnData] = useState([]); // Column data for SELECT clause
  
  // Search and filter
  const [searchDatabase, setSearchDatabase] = useState(""); // Search term for databases
  const [searchTable, setSearchTable] = useState(""); // Search term for tables
  const [searchCol, setSearchCol] = useState(""); // Search term for columns
  const [searchQuery, setSearchQuery] = useState(""); // Search term for queries
  const [searchcol, setSearchcol] = useState(""); // Another search term for columns (can be consolidated)
  
  // Pagination
  const [currentPage, setCurrentPage] = useState(1); // Current page for pagination
  const [pageSize, setPageSize] = useState(10); // Items per page
  
  // Data form management
  const [formData, setFormData] = useState({
    name: "",
    conn_string: "",
    username: "",
    password: "",
    driver_class_name: "",
    description: "",
    active: null,
    type: ""
  }); // Form data for database connections
  
  // Query execution state
  const [queryResults, setQueryResults] = useState([]); // Results of executed query
  const [queryColumns, setQueryColumns] = useState([]); // Column names from query results
  const [isQueryResultVisible, setIsQueryResultVisible] = useState(false); // Whether to show query results
  const [queryResultsLoading, setQueryResultsLoading] = useState(false); // Loading state for query execution
  const [queryResultError, setQueryResultError] = useState(null); // Error from query execution
  
  // Column visibility for database table
  const [visibleColumns, setVisibleColumns] = useState([
    "No",
    "Database Name",
    "Description",
    "Active",
    "Type",
    "Action",
  ]); // Visible columns in the database selection table
  
  // Dropdown options for conditions
  const [andorOptions] = useState(["AND", "OR"]); // Options for AND/OR in conditions
  const [conditionOptions] = useState([
    "Equals",
    "Not Equals",
    "Contains",
    "Starts With",
  ]); // Condition types

  // Modal state for database operations
  const [isNewDatabaseModalOpen, setIsNewDatabaseModalOpen] = useState(false); // Add new database modal
  const [isEditDatabaseModalOpen, setIsEditDatabaseModalOpen] = useState(false); // Edit database modal
  const [editingDatabase, setEditingDatabase] = useState(null); // Database being edited

  // Refs for dropdowns
  const tableDropdownRef = useRef(null);
  const columnDropdownRef = useRef(null);
  const conditionDropdownRef = useRef(null);
  const parameterDropdownRef = useRef(null);
  
  // Navigation
  const navigate = useNavigate();
  const location = useLocation();
  const [id, setId] = useState(null); // Report ID for save/update operations
  const [reportId, setReportId] = useState(null); // Report ID for save/update operations
  // Get ID from location state when component mounts
  useEffect(() => {
    if (location.state && location.state.id) {
      setId(location.state.id);
      console.log("Report ID received:", location.state.id);
      
      // You could also load the report data here if needed
      if (location.state.reportData) {
        console.log("Report data received:", location.state.reportData);
        setReportId(location.state.reportData.Rpt_builder2_lines[0].id);
        console.log("reportId(child id) ",location.state.reportData.Rpt_builder2_lines[0].id)
        // Initialize form with the received data if needed
      }
    }
  }, [location]);

  // Reset filtered collist when collist changes
  useEffect(() => {
    setFilteredCollist(collist);
  }, [collist]);

  // Apply derived/computed values from filtered data
  const filteredQueryData = Array.isArray(queryData)
    ? queryData.filter((item) =>
      item.sql_query.toLowerCase().includes(searchQuery.toLowerCase())
    )
    : [];

  const totalQueryDataPages = Math.ceil(filteredQueryData.length / pageSize);

  const currentQueryData = filteredQueryData.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );

  const filteredTableList = Array.isArray(tableList)
    ? tableList.filter((item) =>
      item.toLowerCase().includes((searchTable || "").toLowerCase())
    )
    : [];

  const filteredList = Array.isArray(tableList)
    ? tableList.filter((table) =>
      table.toLowerCase().includes((searchTable || "").toLowerCase())
    )
    : [];

  const totalPages = Math.ceil(filteredList.length / pageSize);
  const totalPagesOfTableList = Math.ceil(filteredTableList.length / pageSize);
  const currentData = filteredTableList.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );

  const paginatedList = filteredList.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );

  const filteredDatabaseData = databaseList.filter((db) =>
    db.name?.toLowerCase().includes(searchDatabase.toLowerCase())
  );

  const paginatedData = filteredData.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );

  // ================= UTILITY FUNCTIONS =================
  
  /**
   * Extract the column name part after the dot (e.g., "a.id" becomes "id")
   * @param {string} columnName - Full column name with table alias
   * @returns {string} - Column name without table alias
   */
  const getColumnNamePart = (columnName) => {
    if (columnName.includes('.')) {
      return columnName.split('.')[1];
    }
    return columnName;
  };

  /**
   * Update column alias in state when user changes it
   * @param {string} column - Column name
   * @param {string} newAlias - New alias for the column
   */
  const handleAliasChange = (column, newAlias) => {
    setColumnAliases(prev => ({
      ...prev,
      [column]: newAlias
    }));
  };

  /**
   * Generate single-letter aliases for tables (a, b, c, etc.)
   * @param {number} index - Index of the table in the selected tables array
   * @returns {string} - Single letter alias
   */
  const generateAlias = (index) => {
    return String.fromCharCode(97 + (index % 26)); // Generates a, b, c, d, etc.
  };

  /**
   * Handle parameter selection
   * @param {string} state - Parameter to toggle selection
   */
  const handleSelect = (state) => {
    setSelectedParameter((prev) =>
      prev.includes(state) ? prev.filter((item) => item !== state) : [...prev, state]
    );
  };

  // ================= EVENT HANDLERS =================

  /**
   * Handle input changes for condition modal
   * @param {number} index - Index of the condition row
   * @param {string} field - Field name to update
   * @param {string} value - New value for the field
   */
  const handleInputChange = (index, field, value) => {
    const updatedData = [...conditionData];
    updatedData[index][field] = value;
    setConditionData(updatedData);
    setColumnData(updatedData);
  };

  /**
   * Open the database selection modal and fetch database connections
   */
  const handleSwitch = async () => {
    try {
      const response = await ReportBuilderService.getDatabase();
      console.log("Fetched Database Data: ", response.data);

      if (response && response.data) {
        setDatabaseList(response.data);
        setDatabaseConnections(response.data);
        // Set filtered data for rendering in the modal
        setData(response.data);
        setFilteredData(response.data);
      } else {
        setDatabaseConnections(response || []);
        setData(response || []);
        setFilteredData(response || []);
      }

      // Open the modal after data is loaded
      setIsModalOpen(true);
      toast.success("Database connections fetched successfully.");
    } catch (error) {
      console.error("Error fetching database data:", error);
      setDatabaseConnections([]);
      setData([]);
      setFilteredData([]);
      setIsModalOpen(true); // Still open modal to show empty state
      toast.error("Failed to fetch database connections.");
    }
  };

  /**
   * Toggle column visibility in database table
   * @param {string} col - Column name to toggle
   */
  const toggleColumnVisibility = (col) => {
    setVisibleColumns((prev) =>
      prev.includes(col) ? prev.filter((c) => c !== col) : [...prev, col]
    );
  };

  /**
   * Handle database selection and fetch tables for the selected database
   * @param {Object} db - Selected database object
   */
  const handleDatabaseSelect = (db) => {
    setIsModalOpen(false);
    console.log("Selected database:", db);
    // Clear previous data
    setSelectedTable([]);
    setSelectedCol([]);
    setTableList([]);
    setDatabaseName(db.name);
    setSelectedDatabase(db.conn_string.split(":3306/")[1]);
    fetchTableList(db.name);
  };

  /**
   * Fetch table list for the selected database
   * @param {string} dbname - Database name
   */
  const fetchTableList = async (dbname) => {
    try {
      console.log("calling get table list:", dbname);
      const response = await ReportBuilderService.getTableListn(dbname);
      if (response && response.data) {
        setTableList(response.data);
        console.log("Fetched Table List:", response.data);
        toast.success("Table list fetched successfully.");
      } else {
        setTableList(response || []);
        console.log("Fetched Table List:", response);
        toast.success("Table list fetched successfully.");
      }
    } catch (error) {
      console.error("Error fetching table list:", error);
      toast.error("Failed to fetch table list.");
      setTableList([]);
    }
  };

  /**
   * Add a new condition row to the condition table
   */
  const addRow = () => {
    setConditionData([
      ...conditionData,
      { andor: "", fields_name: "", condition: "", value: "" },
    ]);
    setColumnData([...columnData, { columns: "", alias: "" }]);
  };

  /**
   * Delete a condition row from the condition table
   * @param {number} index - Index of the row to delete
   */
  const deleteRow = (index) => {
    const updatedData = conditionData.filter((_, i) => i !== index);
    setConditionData(updatedData);
  };

  /**
   * Toggle the query modal
   */
  const toggle = () => {
    setIsQueryModalOpen((prev) => !prev);
  };

  /**
   * Handle input changes in form fields
   * @param {Event} e - Change event
   */
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value,
    });
  };

  /**
   * Handle form submission
   * @param {Event} e - Submit event
   */
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Selected Conditions:", conditionData);
    console.log("Selected Columns:", columnData);
    onCreate(formData);
    toggle();
  };

  // ================= FILTERING & PAGINATION =================

  /**
   * Handle search input changes
   * @param {Event} event - Change event
   */
  const handleSearchChange = (event) => {
    const value = event.target.value;
    setSearchTable(value);
    setSearchCol(value);
    setCurrentPage(1); // Reset to the first page on search
    setSearchcol(value);
    // Filter the columns based on search criteria
    setFilteredCollist(collist.filter((item) => item.includes(value)));
  };

  /**
   * Toggle modal visibility
   */
  const toggleModal = () => setIsModalOpen(!isModalOpen);

  /**
   * Handle pagination page changes
   * @param {number} pageNumber - New page number
   */
  const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  /**
   * Open the query selection modal and fetch saved queries
   */
  const openQueryModal = () => {
    // Fetch saved queries
    ReportBuilderService.getall()
      .then((response) => {
        const queries = response && response.data ? response.data : response || [];
        console.log("Fetched queries:", queries);
        setData(queries);
        setFilteredData(queries);
        // Reset search and open modal
        setSearchQuery("");
        setIsQueryModalOpen(true);
      })
      .catch((error) => {
        console.error("Error fetching queries:", error);
        toast.error("Failed to load saved queries");
        setData([]);
        setFilteredData([]);
        setIsQueryModalOpen(true); // Still open modal to show empty state
      });
  };

  /**
   * Save the current query to the database
   */
  const saveQuery = () => {
    if (!selectedQuery || selectedQuery.trim() === '') {
      toast.warning("No query to save. Please write or select a query first.");
      return;
    }

    console.log("Saving query:", selectedQuery);

    // Prepare data object
    const queryData = {
      sql_query: selectedQuery,
      queryname: databaseName || "default_database"
    };

    ReportBuilderService.saveq(queryData)
      .then((response) => {
        console.log("Query saved successfully:", response);
        toast.success("Query saved successfully");
      })
      .catch((error) => {
        console.error("Error saving query:", error);
        toast.error("Failed to save query. Please try again.");
      });
  };

  /**
   * Toggle between tabs
   * @param {number} tab - Tab index to switch to
   */
  const toggleTab = (tab) => {
    if (activeTab !== tab) setActiveTab(tab);
  };

  /**
   * Add a new tab
   */
  const addTab = () => {
    setTabs([...tabs, `Tab${tabs.length + 1}`]);
  };

  /**
   * Remove a tab
   * @param {number} index - Tab index to remove
   */
  const removeTab = (index) => {
    if (tabs.length > 1) {
      setTabs(tabs.filter((tab, i) => i !== index));
    }
  };

  /**
   * Handle query text changes
   * @param {Event} event - Change event
   */
  const handleQueryChange = (event) => {
    setSqlQuery(event.target.value);
  };

  /**
   * Save the report with all selected parameters
   */
  const handleSaveReport = () => {
    // Create report data object first
    const reportData = {
      conn_name: databaseName,
      folderName: folderName,
      sql_str: selectedQuery,
      date_param_req: dataParameter,
      column_str: JSON.stringify(selectedCol),
      adhoc_param_html: JSON.stringify(selectedCol),
      std_param_html: JSON.stringify(selectedTable),
    };

    const saveReportData = {
      header_id:reportId,
      model: JSON.stringify(reportData),
    };
    // console.log("location.state.Rpt_builder2_lines[0].id", location.state.Rpt_builder2_lines[0].id)
    
    // Log the data we're about to save
    console.log("Report being saved: ", reportData);
    console.log("payload for save report : ", saveReportData);
    
    // Use the ID received from UserDetailsView if available
    if (reportId) {
      // Call the API with the correct ID
      ReportBuilderService.updaterbLineData(saveReportData, reportId)
        .then(response => {
          console.log("Report updated successfully:", response);
          toast.success("Report saved successfully");

          setTimeout(() => {
            navigate(-1);
          }, 1000);
        })
        .catch(error => {
          console.error("Error updating report:", error);
          toast.error("Failed to save report");
        });
    } else {
      // If no ID is provided, show a message
      toast.warning("No report ID provided. Cannot update.");
    }
  };

  /**
   * Run the current SQL query and display results
   */
  const handleRunQuery = () => {
    if (!selectedQuery || selectedQuery.trim() === '') {
      toast.warning("No query to run. Please write or select a query first.");
      return;
    }

    setQueryResultsLoading(true);
    setIsQueryResultVisible(true);
    setQueryResultError(null);
    
    console.log("Running query:", selectedQuery);
    
    ReportBuilderService.getMasterData(selectedQuery)
      .then((response) => {
        console.log("Query results:", response.data);
        if (response && response.data && Array.isArray(response.data)) {
          // Extract data and column headers
          const results = response.data;
          
          // Get column names from the first row
          const columns = results.length > 0 ? Object.keys(results[0]) : [];
          
          setQueryResults(results);
          setQueryColumns(columns);
          toast.success("Query executed successfully");
        } else {
          setQueryResults([]);
          setQueryColumns([]);
          setQueryResultError("No results returned or invalid response format");
          toast.info("Query executed but no results returned");
        }
      })
      .catch((error) => {
        console.error("Error executing query:", error);
        setQueryResults([]);
        setQueryColumns([]);
        setQueryResultError(error.message || "Failed to execute query");
        toast.error("Failed to execute query");
      })
      .finally(() => {
        setQueryResultsLoading(false);
      });
  };

  /**
   * Handle query selection from the saved queries modal
   * @param {string} query - Selected query
   */
  const handleQuerySelect = (query) => {
    setSelectedQuery(query);
    setIsQueryModalOpen(false);
    toast.info("Query selected");
  };

  /**
   * Handle search query input changes
   * @param {Event} e - Change event
   */
  const handleSearchQueryChange = (e) => {
    const query = e.target.value;
    setSearchQuery(query);
    setCurrentPage(1); // Reset to first page when searching
  };

  // ================= TABLE & COLUMN HANDLING =================

  /**
   * Handle table list icon click to generate query based on selected tables
   */
  const onTableListClick = () => {
    console.log("Icon clicked for Table List", selectedTable);
    if (!selectedTable || !Array.isArray(selectedTable) || selectedTable.length === 0) {
      setMsg("Please first select table(s)");
      return;
    }
    
    setMsg("");
    fetchAllColumnsFromAllTables(selectedTable);
    
    // Create a query with all selected tables and their aliases
    const selectedTables = selectedTable.map((table, index) => {
      const alias = generateAlias(index); // Use the existing alias generation function
      return `${table} ${alias}`;
    }).join(', ');

    setSelectedTableQuery(`SELECT * FROM ${selectedTables} WHERE 1=1`);
  };
  
  /**
   * Effect to update selected query when table query changes
   */
  useEffect(() => {
    console.log("Updated Query:", selectedTableQuery);
    setSelectedQuery(selectedTableQuery);
  }, [selectedTableQuery]); // Runs whenever selectedTableQuery changes

  /**
   * Fetch columns from all selected tables
   * @param {Array} val - Array of selected table names
   */
  const fetchAllColumnsFromAllTables = async (val) => {
    try {
      console.log("Selected tables for API call:", val);
      const response = await ReportBuilderService.getAllColumnsFromAllTables(val);
      if (response && response.data) {
        console.log("Fetched all columns of selected tables: ", response.data);
        setAllColumnList(response.data);
      } else {
        console.log("Fetched Table List:", response);
      }
    } catch (error) {
      console.error("Error fetching table list:", error);
    }
  };

  /**
   * Toggle column modal visibility
   */
  const toggleColumnModal = () => {
    setIsColumnModalOpen(!isColumnModalOpen);
  };

  /**
   * Handle column modal form submission to update query with column aliases
   */
  const handleColumnModalSubmit = () => {
    // Create a formatted query with the selected columns and their aliases
    const formattedColumns = selectedCol.map(column => {
      const alias = columnAliases[column] || getColumnNamePart(column);
      return `${column} AS ${alias}`;
    }).join(', ');

    // Update the selected query with the formatted columns
    const baseQuery = selectedTableQuery.split('*')[0]; // Get the part before *
    const newQuery = `${baseQuery}${formattedColumns} FROM ${selectedTable.map((table, index) => `${table} ${generateAlias(index)}`).join(', ')} WHERE 1=1`;
    console.log(newQuery);
    setSelectedQuery(newQuery);
    setIsColumnModalOpen(false);
    toast.success("Column aliases updated successfully");
  };

  /**
   * Toggle condition modal visibility and initialize condition data
   */
  const toggleConditionModal = () => {
    if (!isConditionModalOpen) {
      // When opening the modal, initialize conditionData with existing selected conditions
      const initialConditions = selectedCondition.map(condition => {
        // Parse the existing condition string to extract components
        const parts = condition.split(' ');
        const andor = parts[0] === 'AND' || parts[0] === 'OR' ? parts[0] : '';
        const fields_name = parts[0] === 'AND' || parts[0] === 'OR' ? parts[1] : parts[0];
        const operator = parts[parts.length - 2];
        const value = parts[parts.length - 1].replace(/'/g, '');
        
        // Map operator back to condition type
        let conditionType = 'Equals';
        if (operator === '!=') conditionType = 'Not Equals';
        else if (operator === 'LIKE') {
          if (value.startsWith('%') && value.endsWith('%')) conditionType = 'Contains';
          else if (value.endsWith('%')) conditionType = 'Starts With';
        }

        return {
          andor,
          fields_name,
          condition: conditionType,
          value
        };
      });
      setConditionData(initialConditions.length > 0 ? initialConditions : [{ andor: '', fields_name: '', condition: '', value: '' }]);
    }
    setIsConditionModalOpen(!isConditionModalOpen);
  };

  /**
   * Handle condition modal form submission to update query with conditions
   */
  const handleConditionModalSubmit = () => {
    // Store only the valid conditions (with all required fields)
    const validConditions = conditionData.filter(
      condition => condition.fields_name && condition.condition && condition.value
    );
    
    // If no valid conditions are present, use default WHERE clause
    if (validConditions.length === 0) {
      setSelectedCondition([]);
      const baseQuery = selectedQuery.split('WHERE')[0];
      const newQuery = `${baseQuery}WHERE 1=1`;
      setSelectedQuery(newQuery);
      setIsConditionModalOpen(false);
      toast.success("Conditions updated successfully");
      return;
    }
    
    // Format the conditions for display
    const formattedConditions = validConditions.map(condition => {
      const operator = condition.condition === "Equals" ? "=" :
                      condition.condition === "Not Equals" ? "!=" :
                      condition.condition === "Contains" ? "LIKE" :
                      condition.condition === "Starts With" ? "LIKE" : "=";
      
      const value = condition.condition === "Contains" ? `'%${condition.value}%'` :
                   condition.condition === "Starts With" ? `'${condition.value}%'` :
                   `'${condition.value}'`;
      
      return `${condition.andor} ${condition.fields_name} ${operator} ${value}`;
    });

    // Update the selected conditions
    setSelectedCondition(formattedConditions);
    
    // Update the query with the conditions
    const baseQuery = selectedQuery.split('WHERE')[0];
    const conditions = formattedConditions.join(' ');
    console.log(conditions)
    const newQuery = `${baseQuery}WHERE 1=1 ${conditions}`;
    console.log(newQuery)
    setSelectedQuery(newQuery);
    
    // Close the modal but don't reset conditionData - it will be preserved for next time
    setIsConditionModalOpen(false);
    toast.success("Conditions updated successfully");
  };

  /**
   * Format cell data with special handling for dates and objects
   * @param {any} data - Data to format
   * @returns {string} - Formatted string representation
   */
  const formatCellData = (data) => {
    if (data === null || data === undefined) {
      return 'NULL';
    }
    
    // Check if the value is a date object (has properties typical of date objects)
    if (typeof data === 'object' && 
        (data.hasOwnProperty('year') || 
         data.hasOwnProperty('month') || 
         data.hasOwnProperty('dayOfMonth') || 
         data.hasOwnProperty('monthValue'))) {
      try {
        // Try to convert it to a readable date string
        const year = data.year || '';
        const month = data.monthValue ? String(data.monthValue).padStart(2, '0') : '';
        const day = data.dayOfMonth ? String(data.dayOfMonth).padStart(2, '0') : '';
        
        if (year && month && day) {
          return `${year}-${month}-${day}`;
        }
        
        // If we can't format it as a date, return a JSON string
        return JSON.stringify(data);
      } catch (e) {
        return JSON.stringify(data);
      }
    }
    
    // Handle other objects
    if (typeof data === 'object') {
      return JSON.stringify(data);
    }
    
    // Return all other types as strings
    return String(data);
  };

  // ================= DATABASE MANAGEMENT FUNCTIONS =================

  /**
   * Toggle new database modal visibility and reset form
   */
  const toggleNewDatabaseModal = () => {
    setIsNewDatabaseModalOpen(!isNewDatabaseModalOpen);
    // Reset form data when opening/closing
    setFormData({
      name: "",
      conn_string: "",
      username: "",
      password: "",
      driver_class_name: "",
      description: "",
      active: null,
      type: ""
    });
  };

  /**
   * Handle adding a new database connection
   * @param {Event} e - Submit event
   */
  const handleAddNewDatabase = (e) => {
    e.preventDefault();
    console.log("Adding new database connection:", formData);
    
    // Call the API to add a new database connection
    ReportBuilderService.createdb(formData)
      .then((response) => {
        console.log("Database connection added successfully:", response);
        toast.success("Database connection added successfully");
        toggleNewDatabaseModal();
        // Refresh the database list
        handleSwitch();
      })
      .catch((error) => {
        console.error("Error adding database connection:", error);
        toast.error("Failed to add database connection");
      });
  };

  /**
   * Handle edit database button click
   * @param {Object} db - Database object to edit
   */
  const handleEditDatabase = (db) => {
    setEditingDatabase(db);
    setFormData({
      id: db.id,
      name: db.name || "",
      conn_string: db.conn_string || "",
      username: db.username || "",
      password: db.password || "",
      driver_class_name: db.driver_class_name || "",
      description: db.description || "",
      active: db.active,
      type: db.type || ""
    });
    setIsEditDatabaseModalOpen(true);
  };

  /**
   * Toggle edit database modal visibility
   */
  const toggleEditDatabaseModal = () => {
    setIsEditDatabaseModalOpen(!isEditDatabaseModalOpen);
    if (isEditDatabaseModalOpen) {
      setEditingDatabase(null);
    }
  };

  /**
   * Handle updating a database connection
   * @param {Event} e - Submit event
   */
  const handleUpdateDatabase = (e) => {
    e.preventDefault();
    console.log("Updating database connection:", formData);
    
    // Call the API to update the database connection
    ReportBuilderService.updateSqlModel(formData.id, formData)
      .then((response) => {
        console.log("Database connection updated successfully:", response);
        toast.success("Database connection updated successfully");
        toggleEditDatabaseModal();
        // Refresh the database list
        handleSwitch();
      })
      .catch((error) => {
        console.error("Error updating database connection:", error);
        toast.error("Failed to update database connection");
      });
  };

  return (
    <div>
      {/* SQL Worksheet Container */}
      <Container style={{ marginBottom: "2rem" }}>
        {/* Header with Database Name and Actions */}
        <Row className="align-items-center mb-3">
          <Col md="8">
            <h3>
              SQL Worksheet - {" "}
              {databaseName ? (
                <b style={{ color: "#59a5d8" }}>{`${databaseName} `}</b>
              ) : (
                <b>connection name</b>
              )}
              <Button
                color="success"
                size="sm"
                className="ms-2"
                onClick={() => handleSwitch()}
                style={{ backgroundColor: "#59a5d8"}}
              >
                switch
              </Button>
              <Button
                color="success"
                size="sm"
                className="ms-2"
                onClick={toggleNewDatabaseModal}
                style={{ backgroundColor: "#59a5d8" }}
              >
                Add New
              </Button>
            </h3>
          </Col>
          <Col md="4" className="text-end">
            <Button
              color="primary"
              onClick={addTab}
              style={{ backgroundColor: "#59a5d8" }}
            >
              <i className="bi bi-plus"></i> New Tab
            </Button>
          </Col>
        </Row>

        {/* Tabs Navigation */}
        <Nav tabs>
          {tabs.map((tab, index) => (
            <NavItem key={index}>
              <NavLink
                className={classnames({ active: activeTab === index })}
                onClick={() => toggleTab(index)}
                style={activeTab === index ? { 
                  borderColor: "#59a5d8", 
                  borderBottomColor: "transparent",
                  color: "#59a5d8",
                  fontWeight: "bold"
                } : {}}
              >
                {tab}
              </NavLink>
            </NavItem>
          ))}
        </Nav>

        {/* Tab Content */}
        <TabContent activeTab={activeTab}>
          {tabs.map((tab, index) => (
            <TabPane tabId={index} key={index}>
              <Row className="mt-3">
                <Col md="8">
                  {/* Table List Dropdown */}
                  <FormGroup>
                    <Label for="tableSelect">Table List</Label>
                    <div className="input-group" ref={tableDropdownRef}>
                      {/* Icon in front of the input */}
                      <span
                        className="input-group-text"
                        style={{
                          cursor: "pointer",
                          backgroundColor: "#59a5d8",
                        }}
                      >
                        <i
                          className="bi bi-caret-down-fill"
                          style={{ backgroundColor: "#59a5d8", color: "white" }}
                          onClick={() => onTableListClick()}
                        />
                      </span>
                      <div className="position-relative" style={{ flex: 1 }}>
                        <Multiselect
                          options={Array.isArray(tableList) ? tableList.map(table => ({ name: table, id: table })) : []}
                          selectedValues={Array.isArray(selectedTable) ? selectedTable.map(table => ({ name: table, id: table })) : []}
                          onSelect={(selectedList) => {
                            setSelectedTable(selectedList.map(item => item.id));
                          }}
                          onRemove={(selectedList) => {
                            setSelectedTable(selectedList.map(item => item.id));
                          }}
                          displayValue="name"
                          placeholder="Select Tables"
                          showCheckbox={true}
                          style={{ 
                            searchBox: { 
                              borderRadius: '0 0.25rem 0.25rem 0',
                              border: '1px solid #ced4da'
                            },
                            chips: {
                              background: "#59a5d8"
                            },
                            optionContainer: {
                              borderColor: "#ced4da"
                            }
                          }}
                        />
                    </div>
                    </div>
                    {msg && <div className="text-danger mt-1">{msg}</div>}
                  </FormGroup>

                  {/* Column List Dropdown */}
                  <FormGroup>
                    <Label for="columnSelect">Column List</Label>
                    <div className="input-group" ref={columnDropdownRef}>
                      {/* Icon in front of the input */}
                      <span
                        className="input-group-text"
                        style={{
                          cursor: "pointer",
                          backgroundColor: "#59a5d8",
                        }}
                      >
                        <i
                          className="bi bi-caret-down-fill"
                          style={{ backgroundColor: "#59a5d8", color: "white" }}
                          onClick={() => {
                            if (selectedCol.length === 0) {
                              setMsg("Please select columns first");
                              return;
                            }
                            setIsColumnModalOpen(true);
                          }}
                        />
                      </span>
                      <div className="position-relative" style={{ flex: 1 }}>
                        <Multiselect
                          options={Array.isArray(allColumnList) ? allColumnList.map(column => ({ name: column, id: column })) : []}
                          selectedValues={Array.isArray(selectedCol) ? selectedCol.map(column => ({ name: column, id: column })) : []}
                          onSelect={(selectedList) => {
                            setSelectedCol(selectedList.map(item => item.id));
                          }}
                          onRemove={(selectedList) => {
                            setSelectedCol(selectedList.map(item => item.id));
                          }}
                          displayValue="name"
                          placeholder="Select Columns"
                          showCheckbox={true}
                          style={{ 
                            searchBox: { 
                              borderRadius: '0 0.25rem 0.25rem 0',
                              border: '1px solid #ced4da' 
                            },
                            chips: {
                              background: "#59a5d8"
                            },
                            optionContainer: {
                              borderColor: "#ced4da"
                            }
                          }}
                        />
                        </div>
                      </div>
                    {msg && <div className="text-danger mt-1">{msg}</div>}
                  </FormGroup>

                  {/* Condition List Dropdown */}
                  <FormGroup>
                    <Label for="conditionSelect">Condition List</Label>
                    <div className="input-group" ref={conditionDropdownRef}>
                      {/* Icon in front of the input */}
                      <span
                        className="input-group-text"
                        style={{
                          cursor: "pointer",
                          backgroundColor: "#59a5d8",
                        }}
                      >
                        <i
                          className="bi bi-caret-down-fill"
                          style={{ backgroundColor: "#59a5d8", color: "white" }}
                          onClick={() => {
                            if (selectedCol.length === 0) {
                              setMsg("Please select columns first");
                              return;
                            }
                            toggleConditionModal();
                          }}
                        />
                      </span>
                      <div className="position-relative" style={{ flex: 1 }}>
                        <Multiselect
                          options={Array.isArray(allColumnList) ? allColumnList.map(condition => ({ name: condition, id: condition })) : []}
                          selectedValues={Array.isArray(selectedCondition) ? selectedCondition.map(condition => ({ name: condition, id: condition })) : []}
                          onSelect={(selectedList) => {
                            setSelectedCondition(selectedList.map(item => item.id));
                          }}
                          onRemove={(selectedList) => {
                            setSelectedCondition(selectedList.map(item => item.id));
                          }}
                          displayValue="name"
                          placeholder="Select Conditions"
                          showCheckbox={true}
                          style={{ 
                            searchBox: { 
                              borderRadius: '0 0.25rem 0.25rem 0',
                              border: '1px solid #ced4da' 
                            },
                            chips: {
                              background: "#59a5d8"
                            },
                            optionContainer: {
                              borderColor: "#ced4da"
                            }
                          }}
                        />
                    </div>
                    </div>
                  </FormGroup>

                  {/* Parameter List Dropdown */}
                  <FormGroup>
                    <Label for="parameterSelect">Select Parameter List</Label>
                    <div className="input-group" ref={parameterDropdownRef}>
                      {/* Icon in front of the input */}
                      <span
                        className="input-group-text"
                        style={{
                          cursor: "pointer",
                          backgroundColor: "#59a5d8",
                        }}
                      >
                        <i
                          className="bi bi-caret-down-fill"
                          style={{ backgroundColor: "#59a5d8", color: "white" }}
                          onClick={() => console.log("Icon clicked for Parameter List")}
                        />
                      </span>
                      <div className="position-relative" style={{ flex: 1 }}>
                        <Multiselect
                          options={Array.isArray(allColumnList) ? allColumnList.map(parameter => ({ name: parameter, id: parameter })) : []}
                          selectedValues={Array.isArray(selectedParameter) ? selectedParameter.map(parameter => ({ name: parameter, id: parameter })) : []}
                          onSelect={(selectedList) => {
                            setSelectedParameter(selectedList.map(item => item.id));
                          }}
                          onRemove={(selectedList) => {
                            setSelectedParameter(selectedList.map(item => item.id));
                          }}
                          displayValue="name"
                          placeholder="Select Parameters"
                          showCheckbox={true}
                          style={{ 
                            searchBox: { 
                              borderRadius: '0 0.25rem 0.25rem 0',
                              border: '1px solid #ced4da' 
                            },
                            chips: {
                              background: "#59a5d8"
                            },
                            optionContainer: {
                              borderColor: "#ced4da"
                            }
                          }}
                        />
                      </div>
                    </div>
                    {msg && <div className="text-danger mt-1">{msg}</div>}
                  </FormGroup>
                </Col>
                
                {/* Tab Management */}
                <Col md="4" className="text-end">
                  <Button
                    color="danger"
                    disabled={tabs.length === 1}
                    onClick={() => removeTab(index)}
                  >
                    <i className="bi bi-trash"></i> {tab}
                  </Button>
                </Col>
              </Row>

              {/* Report Parameters */}
              <Row>
                <Col md="4">
                  <FormGroup>
                    <Label>Data Parameters Required</Label>
                    <Input
                      type="select"
                      value={dataParameter}
                      onChange={(e) => setDataParameter(e.target.value)}
                      className="form-select"
                    >
                      <option value="null">Select Data Parameters</option>
                      <option>Yes</option>
                      <option>No</option>
                    </Input>
                  </FormGroup>
                </Col>
                <Col md="4">
                  <FormGroup>
                    <Label>Folder Name</Label>
                    <Input
                      type="select"
                      value={folderName}
                      onChange={(e) => setFolderName(e.target.value)}
                      className="form-select"
                    >
                      <option value="null">Select Folder Name</option>
                      <option>Report 1</option>
                      <option>Report 2</option>
                    </Input>
                  </FormGroup>
                </Col>
              </Row>

              {/* SQL Query Editor */}
              <FormGroup>
                <Label for="sql_query">
                  <Button
                    color="success"
                    className="p-2"
                    style={{
                      marginTop: ".4em",
                      display: "inline",
                      cursor: "pointer",
                      marginRight: "1rem",
                      backgroundColor: "#59a5d8",
                    }}
                    onClick={openQueryModal}
                  >
                    Select Query
                  </Button>
                </Label>
                <Label for="sql_query">
                  <Button
                    color="success"
                    className="p-2"
                    style={{
                      marginTop: ".4em",
                      display: "inline",
                      cursor: "pointer",
                      backgroundColor: "#59a5d8",
                    }}
                    onClick={saveQuery}
                  >
                    Save Query
                  </Button>
                </Label>
                <Input
                  type="textarea"
                  value={selectedQuery}
                  onChange={(e) => setSelectedQuery(e.target.value)}
                  placeholder="Enter Query here"
                  style={{ 
                    minHeight: "150px", 
                    fontFamily: "monospace",
                    fontSize: "14px"
                  }}
                />
              </FormGroup>
              
              {/* Action Buttons */}
              <div className="text-end">
                <Button
                  color="primary"
                  onClick={() => handleSaveReport()}
                  style={{ backgroundColor: "#59a5d8" }}
                >
                  Save Report
                </Button>
                <Button
                  color="primary"
                  onClick={() => handleRunQuery()}
                  style={{ backgroundColor: "#59a5d8", marginLeft: "10px" }}
                >
                  Run
                </Button>
              </div>
              
              {/* Query Results Table */}
              {isQueryResultVisible && (
                <div className="mt-4">
                  <h4>Query Results</h4>
                  {queryResultsLoading ? (
                    <div className="text-center my-4">
                      <Spinner color="primary" />
                      <p>Executing query...</p>
                    </div>
                  ) : queryResultError ? (
                    <Alert color="danger">
                      <h5>Error executing query:</h5>
                      <p>{queryResultError}</p>
                    </Alert>
                  ) : queryResults.length === 0 ? (
                    <Alert color="info">No results found for the query.</Alert>
                  ) : (
                    <div className="table-responsive">
                      <Table striped bordered hover className="mt-2">
                        <thead>
                          <tr>
                            {queryColumns.map((column, i) => (
                              <th key={i}>{column}</th>
                            ))}
                          </tr>
                        </thead>
                        <tbody>
                          {queryResults.map((row, rowIndex) => (
                            <tr key={rowIndex}>
                              {queryColumns.map((column, colIndex) => (
                                <td key={colIndex}>{formatCellData(row[column])}</td>
                              ))}
                            </tr>
                          ))}
                        </tbody>
                      </Table>
                      <div className="text-muted mt-2">
                        Showing {queryResults.length} result{queryResults.length !== 1 ? 's' : ''}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </TabPane>
          ))}
        </TabContent>
      </Container>

      {/* ================= MODALS ================= */}

      {/* Database Selection Modal */}
      <div>
        <Modal isOpen={isModalOpen} toggle={toggleModal} size="xl">
          <ModalHeader toggle={toggleModal} className="bg-light">
            <b>Select Database</b>
          </ModalHeader>
          <ModalBody>
            {/* Search Input */}
            <Input
              type="text"
              placeholder="Search database..."
              value={searchDatabase}
              onChange={(e) => setSearchDatabase(e.target.value)}
              className="mb-3"
            />

            {/* Column Management */}
            <div className="d-flex justify-content-between align-items-center mt-3">
              <div>
                <label className="fw-bold me-2">Show Columns: </label>
                {[
                  "No",
                  "Database Name",
                  "Description",
                  "Active",
                  "Type",
                  "Action",
                ].map((col, idx) => (
                  <div key={idx} className="form-check form-check-inline">
                    <Input
                      type="checkbox"
                      id={`col-${idx}`}
                      className="form-check-input"
                      checked={visibleColumns.includes(col)}
                      onChange={() => toggleColumnVisibility(col)}
                    />
                    <label htmlFor={`col-${idx}`} className="form-check-label">
                      {col}
                    </label>
                  </div>
                ))}
              </div>

              {/* Rows Per Page Selector */}
              <div>
                <label className="fw-bold me-2">Rows Per Page: </label>
                <Input
                  type="number"
                  value={pageSize}
                  min="1"
                  max="50"
                  style={{ width: "60px", display: "inline-block" }}
                  onChange={(e) => setPageSize(Number(e.target.value))}
                />
              </div>
            </div>

            {/* Database Table */}
            <Table striped bordered hover className="mt-3">
              <thead style={{ backgroundColor: "#f8f9fa" }}>
                <tr>
                  {visibleColumns.includes("No") && <th>No</th>}
                  {visibleColumns.includes("Database Name") && (
                    <th>Database Name</th>
                  )}
                  {visibleColumns.includes("Description") && (
                    <th>Description</th>
                  )}
                  {visibleColumns.includes("Active") && <th>Active</th>}
                  {visibleColumns.includes("Type") && <th>Type</th>}
                  {visibleColumns.includes("Action") && <th>Action</th>}
                </tr>
              </thead>
              <tbody>
                {databaseList
                  .filter(db =>
                    db.name?.toLowerCase().includes(searchDatabase.toLowerCase())
                  )
                  .slice((currentPage - 1) * pageSize, currentPage * pageSize)
                  .map((db, index) => (
                    <tr key={db.id || index}>
                      {visibleColumns.includes("No") && (
                        <td>{(currentPage - 1) * pageSize + index + 1}</td>
                      )}
                      {visibleColumns.includes("Database Name") && (
                        <td
                          style={{ color: "#59a5d8", cursor: "pointer", fontWeight: "500" }}
                          onClick={() => handleDatabaseSelect(db)}
                        >
                          {db.name}
                        </td>
                      )}
                      {visibleColumns.includes("Description") && (
                        <td>{db.description || "-"}</td>
                      )}
                      {visibleColumns.includes("Active") && (
                        <td>
                          <span className={`badge ${db.active ? "bg-success" : "bg-danger"}`}>
                            {db.active ? "Yes" : "No"}
                          </span>
                        </td>
                      )}
                      {visibleColumns.includes("Type") && <td>{db.type || "-"}</td>}
                      {visibleColumns.includes("Action") && (
                        <td>
                          <span
                            style={{ cursor: "pointer", color: "#dc3545", marginRight: "15px" }}
                            onClick={() => console.log(`Delete ${db.name}`)}
                          >
                            <i className="fa fa-trash"></i>
                          </span>
                          <span
                            style={{
                              cursor: "pointer",
                              color: "#59a5d8",
                            }}
                            onClick={() => handleEditDatabase(db)}
                          >
                            <i className="fa fa-edit"></i>
                          </span>
                        </td>
                      )}
                    </tr>
                  ))}
              </tbody>
            </Table>

            {/* Pagination */}
            <Pagination className="d-flex justify-content-center">
              {[...Array(Math.ceil(databaseList.length / pageSize)).keys()].map(
                (page) => (
                  <PaginationItem active={currentPage === page + 1} key={page}>
                    <PaginationLink 
                      onClick={() => handlePageChange(page + 1)}
                      style={currentPage === page + 1 ? { backgroundColor: "#59a5d8", borderColor: "#59a5d8" } : {}}
                    >
                      {page + 1}
                    </PaginationLink>
                  </PaginationItem>
                )
              )}
            </Pagination>
          </ModalBody>
        </Modal>
      </div>

      {/* Select Query Modal */}
      <Modal isOpen={isQueryModalOpen} toggle={toggle} size="lg">
        <ModalHeader className="bg-light">
          <div className="d-flex justify-content-between align-items-center w-100">
            <strong>Select Query:</strong>
            <button
              type="button"
              className="btn-close"
              aria-label="Close"
              onClick={toggle}
              style={{ marginLeft: "auto" }}
            ></button>
          </div>
        </ModalHeader>
        <ModalBody>
          <div className="mb-3">
            <Input
              id="data"
              type="text"
              placeholder="Search for queries..."
              value={searchQuery}
              onChange={handleSearchQueryChange}
            />
          </div>
          {loading ? (
            <div className="text-center my-3">
              <span className="spinner-border" role="status">
                <span className="sr-only">Loading...</span>
              </span>
            </div>
          ) : (
            <div className="table-responsive">
              <Table striped bordered hover className="mb-0">
                <thead style={{ backgroundColor: "#f8f9fa" }}>
                <tr>
                    <th style={{ width: "60px" }}>No</th>
                  <th>Query</th>
                </tr>
              </thead>
              <tbody>
                {filteredData.filter(item =>
                  (item.sql_query && item.sql_query.toLowerCase().includes(searchQuery.toLowerCase())) ||
                  searchQuery === ""
                ).slice(
                  (currentPage - 1) * pageSize,
                  currentPage * pageSize
                ).map((item, index) => (
                  <tr key={index}>
                      <td className="text-center">{(currentPage - 1) * pageSize + index + 1}</td>
                      <td
                        style={{ 
                          color: "#59a5d8", 
                          cursor: "pointer",
                          maxWidth: "0",
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                          whiteSpace: "nowrap" 
                        }}
                      onClick={() => handleQuerySelect(item.sql_query)}
                        title={item.sql_query}
                    >
                      {item.sql_query}
                    </td>
                  </tr>
                ))}
              </tbody>
            </Table>
            </div>
          )}
          <div className="d-flex justify-content-between align-items-center mt-3">
            <div className="text-muted small">
              {`Showing ${Math.min(filteredData.length, 1) || 0} - ${Math.min(
                currentPage * pageSize,
                filteredData.length
              )} of ${filteredData.length} Records`}
            </div>
            <Pagination className="mb-0">
              {[...Array(totalPages || 1)].map((_, index) => (
                <PaginationItem key={index} active={index + 1 === currentPage}>
                  <PaginationLink
                    onClick={() => handlePageChange(index + 1)}
                    style={index + 1 === currentPage ? { backgroundColor: "#59a5d8", borderColor: "#59a5d8" } : {}}
                  >
                    {index + 1}
                  </PaginationLink>
                </PaginationItem>
              ))}
            </Pagination>
          </div>
        </ModalBody>
      </Modal>
      
      {/* Condition Modal */}
      <Modal isOpen={isConditionModalOpen} toggle={toggleConditionModal} size="lg" backdrop="static">
        <ModalHeader toggle={toggleConditionModal} className="bg-light">
          <b>Condition Table</b>
        </ModalHeader>
        <ModalBody>
          <form onSubmit={(e) => {
            e.preventDefault();
            handleConditionModalSubmit();
          }}>
            <Table striped bordered>
              <thead style={{ backgroundColor: "#f8f9fa" }}>
                <tr>
                  <th width="20%">AND/OR</th>
                  <th width="30%">Field Name</th>
                  <th width="20%">Condition</th>
                  <th width="20%">Value</th>
                  <th width="10%">Action</th>
                </tr>
              </thead>
              <tbody>
                {conditionData.map((data, index) => (
                  <tr key={index}>
                    <td>
                      <Input
                        type="select"
                        value={data.andor}
                        onChange={(e) =>
                          handleInputChange(index, "andor", e.target.value)
                        }
                        className="form-select"
                      >
                        <option value="">Select Values</option>
                        {andorOptions.map((option, i) => (
                          <option key={i} value={option}>
                            {option}
                          </option>
                        ))}
                      </Input>
                    </td>
                    <td>
                      <Input
                        type="select"
                        value={data.fields_name}
                        onChange={(e) =>
                          handleInputChange(
                            index,
                            "fields_name",
                            e.target.value
                          )
                        }
                        className="form-select"
                      >
                        <option value="">Select Field Name</option>
                        {allColumnList.map((column, i) => (
                          <option key={i} value={column}>
                            {column}
                          </option>
                        ))}
                      </Input>
                    </td>
                    <td>
                      <Input
                        type="select"
                        value={data.condition}
                        onChange={(e) =>
                          handleInputChange(index, "condition", e.target.value)
                        }
                        className="form-select"
                      >
                        <option value="">Select Values</option>
                        {conditionOptions.map((condition, i) => (
                          <option key={i} value={condition}>
                            {condition}
                          </option>
                        ))}
                      </Input>
                    </td>
                    <td>
                      <Input
                        type="text"
                        value={data.value}
                        onChange={(e) =>
                          handleInputChange(index, "value", e.target.value)
                        }
                      />
                    </td>
                    <td>
                      <Button
                        color="danger"
                        size="sm"
                        onClick={() => deleteRow(index)}
                      >
                        <i className="bi bi-trash"></i>
                      </Button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </Table>
            <Button color="primary" onClick={addRow} style={{ backgroundColor: "#59a5d8" }}>
              <i className="bi bi-plus"></i> Add Row
            </Button>
            <ModalFooter>
              <Button color="secondary" onClick={toggleConditionModal}>
                Cancel
              </Button>
              <Button color="primary" type="submit" style={{ backgroundColor: "#59a5d8" }}>
                Submit
              </Button>
            </ModalFooter>
          </form>
        </ModalBody>
      </Modal>

      {/* Column Modal */}
      <Modal isOpen={isColumnModalOpen} toggle={toggleColumnModal} size="lg" backdrop="static">
        <ModalHeader toggle={toggleColumnModal} className="bg-light">
          <b>Column Table</b>
        </ModalHeader>
        <ModalBody>
          <form onSubmit={(e) => {
            e.preventDefault();
            handleColumnModalSubmit();
          }}>
            <Table striped bordered>
              <thead style={{ backgroundColor: "#f8f9fa" }}>
                <tr>
                  <th width="40%">Column</th>
                  <th width="40%">Alias</th>
                  <th width="20%">Action</th>
                </tr>
              </thead>
              <tbody>
                {Array.isArray(selectedCol) && selectedCol.map((column, index) => (
                  <tr key={index}>
                    <td>
                      <Input
                        type="text"
                        value={column}
                        readOnly
                        placeholder="Column Name"
                        style={{ backgroundColor: "#f8f9fa" }}
                      />
                    </td>
                    <td>
                      <Input
                        type="text"
                        value={columnAliases[column] || getColumnNamePart(column)}
                        onChange={(e) => handleAliasChange(column, e.target.value)}
                        placeholder="Alias"
                      />
                    </td>
                    <td>
                      <Button
                        color="danger"
                        size="sm"
                        onClick={() => {
                          setSelectedCol(selectedCol.filter((_, i) => i !== index));
                          // Remove the alias when removing the column
                          const newAliases = { ...columnAliases };
                          delete newAliases[column];
                          setColumnAliases(newAliases);
                        }}
                      >
                        <i className="bi bi-trash"></i> Delete
                      </Button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </Table>
            <ModalFooter>
              <Button color="secondary" onClick={toggleColumnModal}>
                Cancel
              </Button>
              <Button color="primary" type="submit" style={{ backgroundColor: "#59a5d8" }}>
                Submit
              </Button>
            </ModalFooter>
          </form>
        </ModalBody>
      </Modal>

      {/* Add New Database Modal */}
      <Modal isOpen={isNewDatabaseModalOpen} toggle={toggleNewDatabaseModal} size="lg" backdrop="static">
        <ModalHeader toggle={toggleNewDatabaseModal} className="bg-light">
          <b>Add New Database Connection</b>
        </ModalHeader>
        <ModalBody>
          <Form onSubmit={handleAddNewDatabase}>
            <Row>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="name">
                    Database Name<span className="text-danger">*</span>
                  </Label>
                  <Input
                    type="text"
                    name="name"
                    id="name"
                    value={formData.name}
                    onChange={handleChange}
                    placeholder="Enter database name"
                    required
                  />
                </FormGroup>
              </Col>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="conn_string">
                    Connection String<span className="text-danger">*</span>
                  </Label>
                  <Input
                    type="text"
                    name="conn_string"
                    id="conn_string"
                    value={formData.conn_string}
                    onChange={handleChange}
                    placeholder="jdbc:mysql://hostname:port/databasename"
                    required
                  />
                </FormGroup>
              </Col>
            </Row>
            <Row>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="username">
                    Username<span className="text-danger">*</span>
                  </Label>
                  <Input
                    type="text"
                    name="username"
                    id="username"
                    value={formData.username}
                    onChange={handleChange}
                    placeholder="Enter database username"
                    required
                  />
                </FormGroup>
              </Col>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="password">
                    Password<span className="text-danger">*</span>
                  </Label>
                  <Input
                    type="password"
                    name="password"
                    id="password"
                    value={formData.password}
                    onChange={handleChange}
                    placeholder="Enter database password"
                    required
                  />
                </FormGroup>
              </Col>
            </Row>
            <Row>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="driver_class_name">
                    Driver Class Name<span className="text-danger">*</span>
                  </Label>
                  <Input
                    type="text"
                    name="driver_class_name"
                    id="driver_class_name"
                    value={formData.driver_class_name}
                    onChange={handleChange}
                    placeholder="com.mysql.jdbc.Driver"
                    required
                  />
                </FormGroup>
              </Col>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="type">
                    Type<span className="text-danger">*</span>
                  </Label>
                  <Input
                    type="select"
                    name="type"
                    id="type"
                    value={formData.type}
                    onChange={handleChange}
                    required
                    className="form-select"
                  >
                    <option value="">Select Type</option>
                    <option value="MySQL">MySQL</option>
                    <option value="PostgreSQL">PostgreSQL</option>
                    <option value="Oracle">Oracle</option>
                    <option value="SQL Server">SQL Server</option>
                  </Input>
                </FormGroup>
              </Col>
            </Row>
            <Row>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="description">
                    Description
                  </Label>
                  <Input
                    type="textarea"
                    name="description"
                    id="description"
                    value={formData.description}
                    onChange={handleChange}
                    placeholder="Enter database description"
                    style={{ minHeight: "100px" }}
                  />
                </FormGroup>
              </Col>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="active">
                    Active
                  </Label>
                  <Input
                    type="select"
                    name="active"
                    id="active"
                    value={formData.active === null ? "" : formData.active}
                    onChange={(e) => {
                      const value = e.target.value === "" ? null : e.target.value === "true";
                      setFormData({...formData, active: value});
                    }}
                    className="form-select"
                  >
                    <option value="">Select Status</option>
                    <option value="true">Yes</option>
                    <option value="false">No</option>
                  </Input>
                </FormGroup>
              </Col>
            </Row>
            <ModalFooter>
              <Button color="secondary" onClick={toggleNewDatabaseModal}>
                Cancel
              </Button>
              <Button color="primary" type="submit" style={{ backgroundColor: "#59a5d8" }}>
                Add Database
              </Button>
            </ModalFooter>
          </Form>
        </ModalBody>
      </Modal>

      {/* Edit Database Modal */}
      <Modal isOpen={isEditDatabaseModalOpen} toggle={toggleEditDatabaseModal} size="lg" backdrop="static">
        <ModalHeader toggle={toggleEditDatabaseModal} className="bg-light">
          <b>Edit Database Connection</b>
        </ModalHeader>
        <ModalBody>
          <Form onSubmit={handleUpdateDatabase}>
            <input type="hidden" name="id" value={formData.id} />
            <Row>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="name">
                    Database Name<span className="text-danger">*</span>
                  </Label>
                  <Input
                    type="text"
                    name="name"
                    id="edit_name"
                    value={formData.name}
                    onChange={handleChange}
                    placeholder="Enter database name"
                    required
                  />
                </FormGroup>
              </Col>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="conn_string">
                    Connection String<span className="text-danger">*</span>
                  </Label>
                  <Input
                    type="text"
                    name="conn_string"
                    id="edit_conn_string"
                    value={formData.conn_string}
                    onChange={handleChange}
                    placeholder="jdbc:mysql://hostname:port/databasename"
                    required
                  />
                </FormGroup>
              </Col>
            </Row>
            <Row>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="username">
                    Username<span className="text-danger">*</span>
                  </Label>
                  <Input
                    type="text"
                    name="username"
                    id="edit_username"
                    value={formData.username}
                    onChange={handleChange}
                    placeholder="Enter database username"
                    required
                  />
                </FormGroup>
              </Col>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="password">
                    Password<span className="text-danger">*</span>
                  </Label>
                  <Input
                    type="password"
                    name="password"
                    id="edit_password"
                    value={formData.password}
                    onChange={handleChange}
                    placeholder="Enter database password"
                    required
                  />
                </FormGroup>
              </Col>
            </Row>
            <Row>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="driver_class_name">
                    Driver Class Name<span className="text-danger">*</span>
                  </Label>
                  <Input
                    type="text"
                    name="driver_class_name"
                    id="edit_driver_class_name"
                    value={formData.driver_class_name}
                    onChange={handleChange}
                    placeholder="com.mysql.jdbc.Driver"
                    required
                  />
                </FormGroup>
              </Col>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="type">
                    Type<span className="text-danger">*</span>
                  </Label>
                  <Input
                    type="select"
                    name="type"
                    id="edit_type"
                    value={formData.type}
                    onChange={handleChange}
                    required
                    className="form-select"
                  >
                    <option value="">Select Type</option>
                    <option value="MySQL">MySQL</option>
                    <option value="PostgreSQL">PostgreSQL</option>
                    <option value="Oracle">Oracle</option>
                    <option value="SQL Server">SQL Server</option>
                  </Input>
                </FormGroup>
              </Col>
            </Row>
            <Row>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="description">
                    Description
                  </Label>
                  <Input
                    type="textarea"
                    name="description"
                    id="edit_description"
                    value={formData.description}
                    onChange={handleChange}
                    placeholder="Enter database description"
                    style={{ minHeight: "100px" }}
                  />
                </FormGroup>
              </Col>
              <Col md={6} sm={12}>
                <FormGroup>
                  <Label for="active">
                    Active
                  </Label>
                  <Input
                    type="select"
                    name="active"
                    id="edit_active"
                    value={formData.active === null ? "" : formData.active}
                    onChange={(e) => {
                      const value = e.target.value === "" ? null : e.target.value === "true";
                      setFormData({...formData, active: value});
                    }}
                    className="form-select"
                  >
                    <option value="">Select Status</option>
                    <option value="true">Yes</option>
                    <option value="false">No</option>
                  </Input>
                </FormGroup>
              </Col>
            </Row>
        <ModalFooter>
              <Button color="secondary" onClick={toggleEditDatabaseModal}>
            Cancel
          </Button>
              <Button color="primary" type="submit" style={{ backgroundColor: "#59a5d8" }}>
                Update Database
          </Button>
        </ModalFooter>
          </Form>
        </ModalBody>
      </Modal>
    </div>
  );
};

export default ReportQuery;
