import { createSignal, type Component } from "solid-js";
import { Show } from "solid-js/web";

const ContactForm: Component = () => {
  const [firstName, setFirstName] = createSignal("");
  const [lastName, setLastName] = createSignal("");
  const [email, setEmail] = createSignal("");
  const [company, setCompany] = createSignal("");
  const [service, setService] = createSignal("");
  const [budget, setBudget] = createSignal("");
  const [message, setMessage] = createSignal("");
  const [status, setStatus] = createSignal<
    "idle" | "sending" | "success" | "error"
  >("idle");
  const [errorMessage, setErrorMessage] = createSignal("");

  const handleSubmit = async (e: Event) => {
    e.preventDefault();
    setStatus("sending");
    setErrorMessage("");

    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          subject: `New Contact Form Message from ${firstName()} ${lastName()}`,
          message: `From: ${firstName()} ${lastName()}
Email: ${email()}
Company: ${company() || "Not specified"}
Service Needed: ${service() || "Not specified"}
Budget: ${budget() || "Not specified"}

Project Details:
${message()}`,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || data.message || "Failed to send message");
      }

      setStatus("success");
      setFirstName("");
      setLastName("");
      setEmail("");
      setCompany("");
      setService("");
      setBudget("");
      setMessage("");
      setTimeout(() => setStatus("idle"), 3000);
    } catch (error) {
      setStatus("error");
      setErrorMessage(
        error instanceof Error ? error.message : "Failed to send message",
      );
      console.error("Submission error:", error);
    }
  };

  return (
    <form class="space-y-6" onSubmit={handleSubmit}>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div class="form-control">
          <label class="label">
            <span class="label-text font-semibold">First Name *</span>
          </label>
          <input
            type="text"
            name="firstName"
            class="input input-bordered w-full"
            required
            value={firstName()}
            onInput={(e) => setFirstName(e.currentTarget.value)}
            disabled={status() === "sending"}
          />
        </div>
        <div class="form-control">
          <label class="label">
            <span class="label-text font-semibold">Last Name *</span>
          </label>
          <input
            type="text"
            name="lastName"
            class="input input-bordered w-full"
            required
            value={lastName()}
            onInput={(e) => setLastName(e.currentTarget.value)}
            disabled={status() === "sending"}
          />
        </div>
      </div>

      <div class="form-control">
        <label class="label">
          <span class="label-text font-semibold">Email Address *</span>
        </label>
        <input
          type="email"
          name="email"
          class="input input-bordered w-full"
          required
          value={email()}
          onInput={(e) => setEmail(e.currentTarget.value)}
          disabled={status() === "sending"}
        />
      </div>

      <div class="form-control">
        <label class="label">
          <span class="label-text font-semibold">Company</span>
        </label>
        <input
          type="text"
          name="company"
          class="input input-bordered w-full"
          value={company()}
          onInput={(e) => setCompany(e.currentTarget.value)}
          disabled={status() === "sending"}
        />
      </div>

      <div class="form-control">
        <label class="label">
          <span class="label-text font-semibold">Service Needed</span>
        </label>
        <select
          name="service"
          class="select select-bordered w-full"
          value={service()}
          onChange={(e) => setService(e.currentTarget.value)}
          disabled={status() === "sending"}
        >
          <option value="">Select a service...</option>
          <option value="web-development">Web Development</option>
          <option value="mobile-development">Mobile App Development</option>
          <option value="devops">DevOps</option>
          <option value="it-support">IT Support Processes</option>
          <option value="consultation">General Consultation</option>
        </select>
      </div>

      <div class="form-control">
        <label class="label">
          <span class="label-text font-semibold">Project Budget</span>
        </label>
        <select
          name="budget"
          class="select select-bordered w-full"
          value={budget()}
          onChange={(e) => setBudget(e.currentTarget.value)}
          disabled={status() === "sending"}
        >
          <option value="">Select budget range...</option>
          <option value="under-5k">Under $5,000</option>
          <option value="5k-15k">$5,000 - $15,000</option>
          <option value="15k-50k">$15,000 - $50,000</option>
          <option value="50k-plus">$50,000+</option>
        </select>
      </div>

      <div class="form-control">
        <label class="label" for="project-details">
          <span class="label-text font-semibold">Project Details *</span>
        </label>
        <textarea
          id="project-details"
          name="message"
          class="textarea textarea-bordered h-32 w-full resize-none"
          placeholder="Tell us about your project requirements, timeline, and any specific needs..."
          required
          value={message()}
          onInput={(e) => setMessage(e.currentTarget.value)}
          disabled={status() === "sending"}
        />
      </div>

      <Show when={status() === "error"}>
        <div class="alert alert-error">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            class="stroke-current shrink-0 h-6 w-6"
            fill="none"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
            />
          </svg>
          <span>
            {errorMessage() || "Error sending message. Please try again."}
          </span>
        </div>
      </Show>

      <Show when={status() === "success"}>
        <div class="alert alert-success">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            class="stroke-current shrink-0 h-6 w-6"
            fill="none"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
            />
          </svg>
          <span>Message sent successfully!</span>
        </div>
      </Show>

      <div class="form-control pt-4">
        <button
          type="submit"
          class="btn btn-primary btn-lg w-full"
          disabled={status() === "sending"}
        >
          {status() === "sending" ? (
            <>
              <span class="loading loading-spinner"></span>
              Sending...
            </>
          ) : (
            "Send Message"
          )}
        </button>
      </div>
    </form>
  );
};

export default ContactForm;
