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 response = await fetch("/Report_builder/Report_builder"); // Replace with your API URL
  //     const data = await response.json();
  //     setGridData(data);
  //     setReports(data); 
  //     if (data.length === 0) setError("No data Available");
  //   } catch (err) {
  //     console.error(err);
  //     setError("Error fetching data.");

  //   } finally {
  //     setIsLoading(false);
  //   }
  // };

  const fetchAllReports = async () => {
    setIsLoading(true); // Set loading state to true
    try {
      const data = await fetchAllReportsApi(); // Call the API to fetch reports
      console.log("Fetched all reports:", data);

      setGridData(data); // Set the grid data state with the fetched reports
      setReports(data);  // Set the reports state

      if (data.length === 0) {
        setError("No data available");
      }
    } catch (error) {
      console.error("Error while fetching reports:", error);
      setError("Error fetching data.");
    } finally {
      setIsLoading(false); // Set loading state to false once the request is complete
    }
  };

  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}});    //reportRunnerEdit.js is called
    }
  };

  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">

      {/* Header */}
      <div className="row">
        <div className="col-md-4">
          <h3><b>All Reports</b></h3>
        </div>
        <div className="col-md-8 text-end">
          <button className="btn btn-primary" onClick={goToAdd}>
            <i className="bi bi-plus"></i> Report Builder SQL
          </button>
          <button className="btn btn-primary ms-2" onClick={goToAdd2}>
            <i className="bi bi-plus"></i> Report Builder URL
          </button>
        </div>
      </div>

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


      {/* Report Cards */}
      {!isLoading && gridData.length > 0 && (
        <div className="row mt-4">
          {gridData.map((report, index) => (
            <div className="col-md-6 col-lg-4 mb-4" key={index}>
              <div
                className="card h-100 border-0"
                onClick={() => goToRunner(report)}
                style={{
                  cursor: 'pointer',
                  transition: 'all 0.3s cubic-bezier(0.165, 0.84, 0.44, 1)',
                  borderRadius: '16px',
                  overflow: 'hidden',
                  backgroundColor: '#ffffff',
                  boxShadow: '0 10px 25px rgba(0,0,0,0.05)',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.transform = 'translateY(-8px)';
                  e.currentTarget.style.boxShadow = '0 15px 30px rgba(0,0,0,0.1)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.transform = 'translateY(0)';
                  e.currentTarget.style.boxShadow = '0 10px 25px rgba(0,0,0,0.05)';
                }}
              >
                {/* Card Header with Gradient */}
                <div 
                  className="d-flex justify-content-between align-items-center p-3"
                  style={{
                    borderBottom: '1px solid rgba(0,0,0,0.05)',
                    background: report.isSql 
                      ? 'linear-gradient(135deg, #f5f7fa 0%,rgb(198, 218, 255) 100%)' 
                      : 'linear-gradient(135deg, #fff9f0 0%,rgb(217, 204, 255) 100%)',
                    height: '50px'
                  }}
                >
                  <div className="d-flex align-items-center">
                    <div 
                      className="me-3 d-flex align-items-center justify-content-center" 
                      style={{ 
                        width: '36px', 
                        height: '36px', 
                        borderRadius: '10px', 
                        background: report.isSql ? 'rgba(65, 105, 225, 0.15)' : 'rgba(255, 165, 0, 0.15)'
                      }}
                    >
                      <i 
                        className={`bi ${report.isSql ? 'bi-database' : 'bi-link-45deg'} fs-5`}
                        style={{ color: report.isSql ? '#4169E1' : '#FF8C00' }}
                      ></i>
                    </div>
                    <span
                      className="fw-semibold"
                      style={{ 
                        color: report.isSql ? '#4169E1' : '#FF8C00',
                        fontSize: '0.9rem'
                      }}
                    >
                      {report.isSql == null ? "N/A" : report.isSql ? "SQL Report" : "URL Report"}
                    </span>
                  </div>

                  {/* Status Indicator */}
                  <div 
                    className="d-flex align-items-center" 
                    style={{ 
                      backgroundColor: report.active ? 'rgba(40, 167, 69, 0.1)' : 'rgba(220, 53, 69, 0.1)',
                      padding: '6px 12px',
                      borderRadius: '30px'
                    }}
                  >
                    <div 
                      style={{ 
                        width: '8px', 
                        height: '8px', 
                        borderRadius: '50%', 
                        backgroundColor: report.active ? '#28a745' : '#dc3545',
                        marginRight: '6px'
                      }}
                    ></div>
                    <span 
                      style={{ 
                        fontSize: '0.8rem', 
                        fontWeight: '500',
                        color: report.active ? '#28a745' : '#dc3545' 
                      }}
                    >
                      {report.active ? "Active" : "Inactive"}
                    </span>
                  </div>
                </div>

                {/* Card Body */}
                <div className="card-body p-4">
                  <h5
                    className="fw-bold mb-3"
                    style={{ 
                      fontSize: '1.15rem',
                      color: '#343a40',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap'
                    }}
                    title={report.reportName}
                  >
                    {report.reportName}
                  </h5>

                  <p
                    style={{
                      display: '-webkit-box',
                      WebkitLineClamp: '2',
                      WebkitBoxOrient: 'vertical',
                      overflow: 'hidden',
                      fontSize: '0.9rem',
                      lineHeight: '1.5',
                      color: '#6c757d',
                      height: '42px',
                      marginBottom: '0'
                    }}
                    title={report.description}
                  >
                    {report.description || "No description available"}
                  </p>
                </div>

                {/* Card Footer */}
                <div 
                  className="p-3" 
                  style={{ 
                    borderTop: '1px solid rgba(0,0,0,0.05)',
                    backgroundColor: '#f8f9fa' 
                  }}
                >
                  <div className="d-flex justify-content-between align-items-center">
                    <div className="d-flex align-items-center" style={{ fontSize: '0.75rem', color: '#6c757d' }}>
                      <i className="bi bi-clock me-1"></i>
                      <span>Updated: {new Date(report.updatedAt).toLocaleDateString()}</span>
                    </div>
                    <div 
                      className="d-flex align-items-center justify-content-center" 
                      style={{ 
                        width: '32px', 
                        height: '32px', 
                        borderRadius: '8px', 
                        backgroundColor: '#e9ecef',
                        transition: 'all 0.2s ease',
                        color: '#495057'
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.backgroundColor = '#dee2e6';
                        e.stopPropagation();
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = '#e9ecef';
                        e.stopPropagation();
                      }}
                    >
                      <i className="bi bi-three-dots"></i>
                    </div>
                  </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" role="dialog">
          <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)}
                />
              </div>
              <div className="modal-body">
                <p>Are you sure you want to delete the report?</p>
                <h2>{rowSelected?.id}</h2>
              </div>
              <div className="modal-footer">
                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={() => setModalDelete(false)}
                >
                  Cancel
                </button>
                <button
                  type="button"
                  className="btn btn-primary"
                  onClick={() => handleDelete(rowSelected.id)}
                >
                  Delete
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ReportRunnerAll;
