import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { fetchAllReportsApi } from '../../../APIServices/ReportRunnerAPI';

const ReportRunnerAll = () => {
  const [gridData, setGridData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const [rowSelected, setRowSelected] = useState(null);
  const [modalDelete, setModalDelete] = useState(false);
  const [reports, setReports] = useState([]);

  const navigate = useNavigate();

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

  const fetchAllReports = async () => {
    setIsLoading(true);
    try {
      const data = await fetchAllReportsApi();
      console.log("Fetched all reports:", data);

      setGridData(data);
      setReports(data);

      if (data.length === 0) {
        setError("No data available");
      }
    } catch (error) {
      console.error("Error while fetching reports:", error);
      setError("Error fetching data.");
    } finally {
      setIsLoading(false);
    }
  };

  const goToAdd = () => navigate("/admin/user-report");
  const goToAdd2 = () => navigate("/admin/reportbuild2all");

  const goToRunner = (report) => {
    console.log("at time of navigating reportID: ",report.id, " report: ",report);
    if (report.isSql) {
      navigate(`/admin/report-runner1/${report.id}`,{ state: { reportId: report.id, reportData: report}});
    } else {
      navigate(`/admin/report-runner2/${report.id}`,{ state: { reportId: report.id, reportData: report}});
    }
  };

  const handleDelete = async (id) => {
    setModalDelete(false);
    try {
      const response = await fetch(`/api/report-builder/${id}`, { method: "DELETE" });
      if (response.ok) {
        toast.success("Deleted successfully");
        fetchAllReports();
      } else {
        toast.error("Error deleting data.");
      }
    } catch (err) {
      console.error(err);
      toast.error("Error deleting data.");
    }
  };

  const openDeleteModal = (row) => {
    setRowSelected(row);
    setModalDelete(true);
  };

  return (
    <div className="container-fluid p-4">
      {/* Header */}
      <div className="d-flex justify-content-between align-items-center mb-4">
        <h3 className="m-0"><strong>All Reports</strong></h3>
        <div>
          <button className="btn btn-primary me-2" onClick={goToAdd}>
            <i className="bi bi-plus me-1"></i> Report Builder SQL
          </button>
          <button className="btn btn-primary" onClick={goToAdd2}>
            <i className="bi bi-plus me-1"></i> Report Builder URL
          </button>
        </div>
      </div>

      {/* Loading Spinner */}
      {isLoading && (
        <div className="alert alert-info d-flex align-items-center mt-3">
          <div className="spinner-border me-2" role="status"></div>
          Loading...
        </div>
      )}

      {/* Report Cards */}
      {!isLoading && gridData.length > 0 && (
        <div className="row row-cols-1 row-cols-md-2 row-cols-lg-3 row-cols-xl-4 g-4">
          {gridData.map((report, index) => (
            <div className="col" key={index}>
              <div 
                className="card h-100 shadow-sm border-0"
                onClick={() => goToRunner(report)}
                style={{ cursor: 'pointer' }}
              >
                {/* Card Header */}
                <div 
                  className={`card-header d-flex justify-content-between align-items-center ${report.isSql ? 'bg-primary bg-opacity-10' : 'bg-warning bg-opacity-10'}`}
                >
                  <div className="d-flex align-items-center">
                    <div className={`me-2 p-2 rounded ${report.isSql ? 'bg-primary bg-opacity-25' : 'bg-warning bg-opacity-25'}`}>
                      <i className={`bi ${report.isSql ? 'bi-database' : 'bi-link-45deg'} ${report.isSql ? 'text-primary' : 'text-warning'}`}></i>
                    </div>
                    <span className={`fw-semibold ${report.isSql ? 'text-primary' : 'text-warning'}`}>
                      {report.isSql == null ? "N/A" : report.isSql ? "SQL Report" : "URL Report"}
                    </span>
                  </div>
                  <span className={`badge ${report.active ? 'bg-success' : 'bg-danger'}`}>
                    {report.active ? "Active" : "Inactive"}
                  </span>
                </div>

                {/* Card Body */}
                <div className="card-body">
                  <h5 className="card-title fw-bold text-truncate" title={report.reportName}>
                    {report.reportName}
                  </h5>
                  <p 
                    className="card-text text-muted" 
                    style={{
                      display: '-webkit-box',
                      WebkitLineClamp: '2',
                      WebkitBoxOrient: 'vertical',
                      overflow: 'hidden',
                      height: '42px'
                    }}
                    title={report.description}
                  >
                    {report.description || "No description available"}
                  </p>
                </div>

                {/* Card Footer */}
                <div className="card-footer bg-light">
                  <div className="d-flex justify-content-between align-items-center">
                    <small className="text-muted">
                      <i className="bi bi-clock me-1"></i>
                      Updated: {new Date(report.updatedAt).toLocaleDateString()}
                    </small>
                    <button 
                      className="btn btn-sm btn-outline-secondary"
                      onClick={(e) => {
                        e.stopPropagation();
                        openDeleteModal(report);
                      }}
                    >
                      <i className="bi bi-three-dots"></i>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Error */}
      {error && <div className="alert alert-danger mt-3">{error}</div>}

      {/* Delete Modal */}
      {modalDelete && (
        <div className="modal show d-block" tabIndex="-1" style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
          <div className="modal-dialog">
            <div className="modal-content">
              <div className="modal-header">
                <h5 className="modal-title">Delete Confirmation</h5>
                <button
                  type="button"
                  className="btn-close"
                  onClick={() => setModalDelete(false)}
                ></button>
              </div>
              <div className="modal-body">
                <p>Are you sure you want to delete the report?</p>
                <h6>{rowSelected?.reportName}</h6>
              </div>
              <div className="modal-footer">
                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={() => setModalDelete(false)}
                >
                  Cancel
                </button>
                <button
                  type="button"
                  className="btn btn-danger"
                  onClick={() => handleDelete(rowSelected.id)}
                >
                  Delete
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ReportRunnerAll;