import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import "./Report-buildall.css";
import { getReports } from "../../../../APIServices/reportBaseUrlAllAPI";
import { deleteReport } from "APIServices/reportBaseUrlDeleteAPI";
import { addReport } from "APIServices/reportBaseUrlAddAPI";
import ConfirmModal from "../../../common/ConfirmModal";
import {
  Table,
  Pagination,
  PaginationItem,
  PaginationLink,
  Badge,
} from "reactstrap";
import {
  Button,
  Form,
  Row,
  Col,
  InputGroup,
  FormControl,
  Modal,
  Dropdown,
} from "react-bootstrap";
import { BsJournals } from "react-icons/bs";
import Spinner from "../../../../UIComponants/Spinner";
import "react-toastify/dist/ReactToastify.css";
import "../../../Dashboard/CSS/CSS/CommonStyle.css";
import {
  faTrash,
  faPlus,
  faGripVertical,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { FaSearch, FaTimes } from "react-icons/fa";

const ReportBuild2All = () => {
  const [gridData, setGridData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [rowSelected, setRowSelected] = useState(null);
  const [visibleColumns, setVisibleColumns] = useState({
    goTo: true,
    reportName: true,
    description: true,
    active: true,
    action: true,
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [recordsPerPage, setRecordsPerPage] = useState(10);
  const navigate = useNavigate();
  const [searchQuery, setSearchQuery] = useState("");

  // Add new state variables for modals
  const [showAddModal, setShowAddModal] = useState(false);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [deleteItem, setDeleteItem] = useState({ id: null, reportName: "" });

  // Add state for new data
  const [newData, setNewData] = useState({
    reportName: "",
    description: "",
    active: false,
    isSql: false,
    Rpt_builder2_lines: [{ model: "" }]
  });

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

  useEffect(() => {
    // Simulate loading data
    setTimeout(() => {
      setLoading(false);
    }, 3000); // Simulated 3 seconds loading
  }, []);

  useEffect(() => {
    // Add custom styles to override Bootstrap's active styling
    const style = document.createElement('style');
    style.textContent = `
      .dropdown-item-custom:active, 
      .dropdown-item-custom:focus, 
      .dropdown-item-custom.active {
        background-color: white !important;
        color: #333 !important;
      }
      .dropdown-item-custom:hover {
        background-color: #f8f9fa !important;
      }
    `;
    document.head.appendChild(style);
    
    return () => {
      document.head.removeChild(style);
    };
  }, []);

  const filteredData = gridData
    .filter(
      (item) =>
        item.reportName &&
        item.reportName.toLowerCase().includes(searchQuery.toLowerCase())
    )
    .slice((currentPage - 1) * recordsPerPage, currentPage * recordsPerPage);

  const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
  };
  const totalPages = Math.ceil(gridData.length / recordsPerPage);
  const handleRecordsPerPageChange = (value) => {
    setRecordsPerPage(value);
    setCurrentPage(1);
  };

  const getAllReports = async () => {
    setLoading(true);
    try {
      const data = await getReports(); // Use the new API service
      if (data.length === 0) {
        setError("No data Available");
      } else {
        setGridData(data);
        console.log("data is coming", data);
      }
    } catch (err) {
      console.error("Error fetching reports:", err);
      setError("Failed to fetch data");
    } finally {
      setLoading(false);
    }
  };

  const goToRunner = () => {
    navigate("/admin/report-runner");
  };

  const goToAdd = () => {
    setShowAddModal(true);
  };

  const goToLines = (report) => {
    console.log("Complete Report Data:", report);  // Log full report data
    console.log("Rpt_builder2_lines:", report?.Rpt_builder2_lines); // Log Rpt_builder2_lines specifically

    navigate(`/admin/reportbuild2edit`, { state: { reportId: report.id, report: report } });

    // // Check if Rpt_builder2_lines is an array and has at least one item
    // if (Array.isArray(report?.Rpt_builder2_lines) && report.Rpt_builder2_lines.length > 0) {
    //   const firstLine = report.Rpt_builder2_lines[0];

    //   // Check if the model field in the first item is not empty
    //   if (firstLine?.model !== '') {
    //     navigate(`/admin/reportbuild2edit`, { state: { reportId: report.id } });
    //   } else {
    //     navigate(`/admin/reportbuild2edit`, { state: { reportId: report.id } });
    //   }
    // } else {
    //   // If Rpt_builder2_lines is missing or not an array, just navigate to /admin/reportbuild2edit
    //   console.warn("Rpt_builder2_lines is missing or not an array. Navigating to /admin/reportbuild2edit...");
    //   navigate(`/admin/reportbuild2edit`, { state: { reportId: report.id } });
    // }
  };

  const confirmDelete = (e, report) => {
    e.stopPropagation(); // Prevent any parent handlers from being called
    setDeleteItem({
      id: report.id,
      reportName: report.reportName || "this report"
    });
    setShowConfirmModal(true);
  };

  const toggleColumn = (column) => {
    setVisibleColumns((prev) => ({
      ...prev,
      [column]: !prev[column],
    }));
  };

  const handleDelete = async () => {
    const { id } = deleteItem;
    if (!id) {
      console.error("ID is undefined. Cannot delete.");
      toast.error("Invalid ID. Deletion failed.");
      return;
    }

    try {
      // Call the deleteReport service
      const response = await deleteReport(id);

      console.log("Delete response:", response);

      // Check if delete was successful
      if (response && (response.status === 200 || response.status === 204)) {
        toast.success("Report deleted successfully");

        // Remove the deleted item from the state
        setGridData(gridData.filter(item => item.id !== id));
      } else {
        toast.error("Error deleting data: Unexpected response");
      }

      // Hide the confirm modal
      setShowConfirmModal(false);
    } catch (err) {
      console.error("Error deleting report:", err);
      toast.error("Error deleting data");
      setShowConfirmModal(false);
    }
  };

  const handleAddSubmit = async () => {
    try {
      // Validate required fields
      if (!newData.reportName.trim()) {
        toast.warning("Report name is required");
        return;
      }

      // Prepare payload for API call
      const payload = {
        reportName: newData.reportName,
        description: newData.description,
        active: newData.active,
        isSql: false,
        Rpt_builder2_lines: [{ model: "" }],
      };

      console.log("payload to be submitted for add url report: ", payload)

      // Call the API to add the report
      const response = await addReport(payload);
      console.log("responce:",response)
      // Check if we received a proper response
      if (response && response.data && response.data.id) {
        toast.success("Report added successfully");

        // Add just the report data to the grid data (not the entire response)
        setGridData([...gridData, response.data]);

        // Reset form and close modal
        setNewData({
          reportName: "",
          description: "",
          active: false,
          isSql: false,
          Rpt_builder2_lines: [{ model: "" }]
        });
        setShowAddModal(false);

        // Refresh the report list to ensure data consistency
        getAllReports();
      } else {
        toast.error("Failed to add report: Unexpected response");
      }
    } catch (error) {
      console.error("Error adding report:", error);
      toast.error("Failed to add report");
    }
  };

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

  // Add custom CSS to override Bootstrap's active dropdown item styling
  const dropdownItemStyle = {
    backgroundColor: 'white',
    color: '#333',
    cursor: 'pointer',
    padding: '8px 12px',
    border: 'none',
    outline: 'none !important'
  };

  return (
    <div>
      {loading ? (
        <Spinner /> // The spinner will be centered in the viewport
      ) : (
        <div className="content-container ">
          <div className="container-fluid mb-7">
            <div className="row mb-3">
              <div className="col-md-4 title_name">
                <h3>
                  <b>Report Builder2 (URL) </b>
                </h3>
              </div>
              <div className="col-md-8 text-end">
                <button className="btn btn-primary me-2" onClick={goToRunner}>
                  <i className="bi bi-grid-fill"></i> Report Runner
                </button>
                <button className="btn btn-primary" onClick={goToAdd}>
                  <i className="bi bi-plus-lg"></i> ADD
                </button>
              </div>
            </div>

            {/* DataGrid */}
            {loading ? (
              <div>Loading...</div>
            ) : error ? (
              <div className="text-danger">{error}</div>
            ) : (
              <Table
                striped
                responsive
                hover
                className="align-middle table-flush shadow-sm"
              >
                <thead className="custom_header">
                  <tr>
                    {visibleColumns.goTo && <th>Go To</th>}
                    {visibleColumns.reportName && <th>Report Name</th>}
                    {visibleColumns.description && <th>Report Description</th>}
                    {visibleColumns.active && <th className="text-center">Active</th>}
                    {visibleColumns.action && <th className="text-center">Action</th>}
                  </tr>
                </thead>

                <tbody className="tbody">
                    {filteredData.length === 0 ? (
                      <tr>
                        <td
                          colSpan={Object.values(visibleColumns).filter(Boolean).length}
                          className="text-center"
                        >
                          No data available
                        </td>
                      </tr>
                    ) : (
                      filteredData.filter(user => user.isSql === false).map(user => (
                        <tr key={user.id}>
                          {visibleColumns.goTo && (
                            <td>
                              <Badge
                                color="primary"
                                pill
                                style={{
                                  cursor: "pointer",
                                  padding: "0.5em 1em",
                                  fontSize: "0.9rem",
                                  textTransform: "uppercase",
                                }}
                                onClick={() => goToLines(user)}
                              >
                                Set Up
                              </Badge>
                            </td>
                          )}
                          {visibleColumns.reportName && <td>{user.reportName}</td>}
                          {visibleColumns.description && <td>{user.description}</td>}
                          {visibleColumns.active && (
                            <td
                              style={{
                                fontWeight: user.active ? "bold" : "normal",
                                color: user.active ? "green" : "red",
                                backgroundColor: user.active ? "rgba(0, 128, 0, 0.1)" : "rgba(255, 0, 0, 0.1)",
                                padding: "2px 4px",
                                display: "inline-block",
                                borderRadius: "4px",
                                textAlign: "center",
                                marginTop: "10px",
                              }}
                            >
                              {user.active ? "Yes" : "No"}
                            </td>
                          )}
                          {visibleColumns.action && (
                            <td>
                              <FontAwesomeIcon
                                icon={faTrash}
                                onClick={(e) => confirmDelete(e, user)}
                                style={{
                                  cursor: "pointer",
                                  fontSize: "1rem",
                                  color: "red",
                                  marginRight: "15px",
                                }}
                              />
                            </td>
                          )}
                        </tr>
                      ))
                    )}
                  </tbody>

              </Table>
            )}

            {/* 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>
                    <Dropdown.Header className="fw-bold text-dark">Toggle Column Visibility</Dropdown.Header>
                    <Dropdown.Divider />
                    {[
                      { key: 'goTo', label: 'Go To' },
                      { key: 'reportName', label: 'Report Name' },
                      { key: 'description', label: 'Report Description' },
                      { key: 'active', label: 'Active Status' },
                      { key: 'action', label: 'Actions' }
                    ].map(column => (
                      <Dropdown.Item
                        key={column.key}
                        onClick={() => toggleColumn(column.key)}
                        style={dropdownItemStyle}
                        className="dropdown-item-custom"
                      >
                        <Form.Check
                          type="checkbox"
                          label={column.label}
                          checked={visibleColumns[column.key]}
                          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"
                  >
                    <Dropdown.Header className="fw-bold text-dark">Records Per Page</Dropdown.Header>
                    <Dropdown.Divider />
                    {[1, 5, 10, 20, 50].map((number) => (
                      <Dropdown.Item
                        key={number}
                        onClick={() => handleRecordsPerPageChange(number)}
                        style={dropdownItemStyle}
                        className="dropdown-item-custom d-flex justify-content-between align-items-center"
                      >
                        <span className={recordsPerPage === number ? 'fw-bold' : ''}>{number}</span>
                        {recordsPerPage === number && (
                          <i className="fa fa-check-circle text-primary" />
                        )}
                      </Dropdown.Item>
                    ))}
                  </Dropdown.Menu>
                </Dropdown>
              </Col>
            </Row>

            <Pagination className="pagination mt-3">
              <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>

            {/* Add Modal */}
            <Modal show={showAddModal} onHide={handleAddClose} centered>
              <Modal.Header>
                <Modal.Title style={{ color: "#0E6591" }}>
                  Add New Report
                </Modal.Title>
                <div
                  onClick={handleAddClose}
                  style={{
                    cursor: "pointer",
                    color: "#0E6591",
                    fontSize: "1.5rem",
                    position: "absolute",
                    right: "15px",
                    top: "15px",
                  }}
                  aria-label="Close"
                >
                  <FaTimes />
                </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 Report
                </Button>
              </Modal.Footer>
            </Modal>

            {/* Confirmation Modal */}
            <ConfirmModal
              show={showConfirmModal}
              onHide={() => setShowConfirmModal(false)}
              onConfirm={handleDelete}
              title="Confirm Deletion"
              message={`Are you sure you want to delete "${deleteItem.reportName}"? This action cannot be undone.`}
              confirmLabel="Delete"
              cancelLabel="Cancel"
              variant="danger"
            />
          </div>
        </div>
      )}
    </div>
  );
};

export default ReportBuild2All;