import { useState } from "react";
import { coachService } from "../api";

export default function EdtCoach() {
  const [name, setName] = useState("");
  const [error, setError] = useState("");
  const [statusCode, setStatusCode] = useState<number | null>(null);

  const handleCreate = async () => {
    try {
      const response = await coachService.create({ name });
      console.log("Success:", response.status, response.data);
      alert(`Coach created! Status: ${response.status}`);
      setError("");
      setStatusCode(response.status);
    } catch (err: any) {
      if (err.response) {
        // This is the HTTP response from the server
        console.error("HTTP status:", err.response.status);
        console.error("Response data:", err.response.data);
        setError(`Failed to create coach: ${err.response.data}`);
        setStatusCode(err.response.status);
      } else if (err.request) {
        console.error("No response received", err.request);
        setError("No response from server!");
        setStatusCode(null);
      } else {
        console.error("Error", err.message);
        setError(err.message);
        setStatusCode(null);
      }
    }
  };

  return (
    <div>
      <h2>Create Coach</h2>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Coach name"
      />
      <button onClick={handleCreate}>Create</button>

      {error && <p style={{ color: "red" }}>{error}</p>}
      {statusCode && <p>HTTP Status: {statusCode}</p>}
    </div>
  );
}
