import React, { useState, useEffect } from "react";
import axios from "axios";

const API = `${process.env.REACT_APP_BACKEND_URL}/api`;

function DebugServices() {
  const [status, setStatus] = useState("Loading...");
  const [services, setServices] = useState([]);
  const [error, setError] = useState(null);

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

  const testAPI = async () => {
    try {
      console.log("Testing API:", `${API}/services`);
      setStatus("Fetching from API...");

      const response = await axios.get(`${API}/services`);
      console.log("API Response:", response.data);

      setServices(response.data);
      setStatus(`Success! Loaded ${response.data.length} services`);
      setError(null);
    } catch (err) {
      console.error("API Error:", err);
      setStatus("Error loading services");
      setError(err.message);
    }
  };

  return (
    <div style={{ padding: "20px", fontFamily: "Arial" }}>
      <h1>Services Debug Page</h1>

      <div
        style={{ background: "#f0f0f0", padding: "15px", marginBottom: "20px" }}
      >
        <strong>Status:</strong> {status}
        {error && (
          <div style={{ color: "red" }}>
            <strong>Error:</strong> {error}
          </div>
        )}
      </div>

      <div
        style={{ background: "#e8f5e9", padding: "15px", marginBottom: "20px" }}
      >
        <strong>API Endpoint:</strong> {`${API}/services`}
      </div>

      <button
        onClick={testAPI}
        style={{ padding: "10px 20px", marginBottom: "20px" }}
      >
        Reload Services
      </button>

      <h2>Services ({services.length}):</h2>

      {services.length === 0 ? (
        <p>No services loaded yet. Click "Reload Services" button.</p>
      ) : (
        <div>
          {services.map((service, index) => (
            <div
              key={service.id}
              style={{
                border: "1px solid #ddd",
                padding: "15px",
                marginBottom: "10px",
                background: "white",
              }}
            >
              <h3>
                {index + 1}. {service.name}
              </h3>
              <p>
                <strong>Category:</strong> {service.category}
              </p>
              <p>
                <strong>Price:</strong> ${service.price}
              </p>
              <p>
                <strong>Duration:</strong> {service.duration}
              </p>
              <p>
                <strong>ID:</strong> {service.id}
              </p>
            </div>
          ))}
        </div>
      )}

      <div
        style={{ marginTop: "30px", background: "#fff3cd", padding: "15px" }}
      >
        <h3>Debug Info:</h3>
        <pre>{JSON.stringify(services, null, 2)}</pre>
      </div>
    </div>
  );
}

export default DebugServices;
