import { useEffect, useState } from "react";

const API_BASE_URL = "YOUR_API_BASE_URL";
const API_KEY = "YOUR_API_KEY";

export default function AffiliateLeadForm() {
  const [caseTypes, setCaseTypes] = useState([]);
  const [form, setForm] = useState({
    name: "",
    email: "",
    phone: "",
    caseTypeId: "",
    message: ""
  });
  const [status, setStatus] = useState("");

  useEffect(() => {
    fetch(`${API_BASE_URL}/api/leads/casetypes`)
      .then((response) => response.json())
      .then(setCaseTypes)
      .catch(() => setStatus("Unable to load case types."));
  }, []);

  async function handleSubmit(event) {
    event.preventDefault();
    setStatus("Submitting...");

    const response = await fetch(`${API_BASE_URL}/api/leads`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Api-Key": API_KEY
      },
      body: JSON.stringify({
        ...form,
        caseTypeId: Number(form.caseTypeId),
        sourceType: 2,
        sourceUrl: window.location.href
      })
    });

    const data = await response.json();
    setStatus(response.ok ? `Lead submitted: ${data.leadId}` : data.error || "Please try again.");
  }

  return (
    <form className="dp-affiliate-form" onSubmit={handleSubmit}>
      <input placeholder="Name" onChange={(e) => setForm({ ...form, name: e.target.value })} />
      <input placeholder="Email" type="email" onChange={(e) => setForm({ ...form, email: e.target.value })} />
      <input placeholder="Phone" onChange={(e) => setForm({ ...form, phone: e.target.value })} />
      <select onChange={(e) => setForm({ ...form, caseTypeId: e.target.value })}>
        <option value="">Select case type</option>
        {caseTypes.map((item) => (
          <option key={item.id} value={item.id}>{item.name}</option>
        ))}
      </select>
      <textarea placeholder="Message" onChange={(e) => setForm({ ...form, message: e.target.value })} />
      <button type="submit">Submit Lead</button>
      <p>{status}</p>
    </form>
  );
}
