import { createSignal, type Component } from "solid-js";
import { Show } from "solid-js/web";
import { Icon } from "solid-heroicons";
import {
  xCircle,
  checkCircle,
  paperAirplane,
  envelope,
} from "solid-heroicons/outline";
import { siteConfig } from "../../config/site";

const ContactSection: 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 (
    <section id="contact" class="py-20 lg:py-28 bg-base-200">
      <div class="max-w-7xl mx-auto px-6">
        <div class="text-center mb-16">
          <h2 class="text-3xl lg:text-4xl font-bold text-base-content mb-4">
            {siteConfig.contact.mainTitle}
          </h2>
        </div>

        <div class="max-w-2xl mx-auto">
          <div class="card bg-base-100 border border-base-300/50 shadow-xl">
            <div class="card-body p-8 lg:p-10">
              <form class="space-y-6" onSubmit={handleSubmit}>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                  <fieldset class="fieldset">
                    <legend class="fieldset-legend text-sm font-semibold text-base-content">
                      {siteConfig.contact.form.firstName}
                    </legend>
                    <input
                      type="text"
                      name="firstName"
                      class="input input-bordered w-full bg-base-100 focus:border-primary focus:outline-primary"
                      required
                      value={firstName()}
                      onInput={(e) => setFirstName(e.currentTarget.value)}
                      disabled={status() === "sending"}
                      placeholder={siteConfig.contact.form.placeholders.firstName}
                    />
                  </fieldset>
                  <fieldset class="fieldset">
                    <legend class="fieldset-legend text-sm font-semibold text-base-content">
                      {siteConfig.contact.form.lastName}
                    </legend>
                    <input
                      type="text"
                      name="lastName"
                      class="input input-bordered w-full bg-base-100 focus:border-primary focus:outline-primary"
                      required
                      value={lastName()}
                      onInput={(e) => setLastName(e.currentTarget.value)}
                      disabled={status() === "sending"}
                      placeholder={siteConfig.contact.form.placeholders.lastName}
                    />
                  </fieldset>
                </div>

                <fieldset class="fieldset">
                  <legend class="fieldset-legend text-sm font-semibold text-base-content">
                    {siteConfig.contact.form.email}
                  </legend>
                  <input
                    type="email"
                    name="email"
                    class="input input-bordered w-full bg-base-100 focus:border-primary focus:outline-primary"
                    required
                    value={email()}
                    onInput={(e) => setEmail(e.currentTarget.value)}
                    disabled={status() === "sending"}
                    placeholder={siteConfig.contact.form.placeholders.email}
                  />
                </fieldset>

                <fieldset class="fieldset">
                  <legend class="fieldset-legend text-sm font-semibold text-base-content">
                    {siteConfig.contact.form.company}
                  </legend>
                  <input
                    type="text"
                    name="company"
                    class="input input-bordered w-full bg-base-100 focus:border-primary focus:outline-primary"
                    value={company()}
                    onInput={(e) => setCompany(e.currentTarget.value)}
                    disabled={status() === "sending"}
                    placeholder={siteConfig.contact.form.placeholders.company}
                  />
                </fieldset>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                  <fieldset class="fieldset">
                    <legend class="fieldset-legend text-sm font-semibold text-base-content">
                      {siteConfig.contact.form.service}
                    </legend>
                    <select
                      name="service"
                      aria-label="Service Needed"
                      class="select select-bordered w-full bg-base-100 focus:border-primary focus:outline-primary"
                      value={service()}
                      onChange={(e) => setService(e.currentTarget.value)}
                      disabled={status() === "sending"}
                    >
                      <option value="">{siteConfig.contact.form.selectPlaceholders.service}</option>
                      {siteConfig.contact.form.services.map((s) => (
                        <option value={s.value}>{s.label}</option>
                      ))}
                    </select>
                  </fieldset>
                  <fieldset class="fieldset">
                    <legend class="fieldset-legend text-sm font-semibold text-base-content">
                      {siteConfig.contact.form.budget}
                    </legend>
                    <select
                      name="budget"
                      aria-label="Project Budget"
                      class="select select-bordered w-full bg-base-100 focus:border-primary focus:outline-primary"
                      value={budget()}
                      onChange={(e) => setBudget(e.currentTarget.value)}
                      disabled={status() === "sending"}
                    >
                      <option value="">{siteConfig.contact.form.selectPlaceholders.budget}</option>
                      {siteConfig.contact.form.budgets.map((b) => (
                        <option value={b.value}>{b.label}</option>
                      ))}
                    </select>
                  </fieldset>
                </div>

                <fieldset class="fieldset">
                  <legend class="fieldset-legend text-sm font-semibold text-base-content">
                    {siteConfig.contact.form.message}
                  </legend>
                  <textarea
                    id="project-details"
                    name="message"
                    class="textarea textarea-bordered h-36 w-full resize-none bg-base-100 focus:border-primary focus:outline-primary"
                    placeholder={siteConfig.contact.form.placeholders.message}
                    required
                    value={message()}
                    onInput={(e) => setMessage(e.currentTarget.value)}
                    disabled={status() === "sending"}
                  />
                </fieldset>

                <Show when={status() === "error"}>
                  <div role="alert" class="alert alert-error">
                    <Icon path={xCircle} class="stroke-current shrink-0 h-5 w-5" />
                    <span class="text-sm">
                      {errorMessage() || siteConfig.contact.form.error}
                    </span>
                  </div>
                </Show>

                <Show when={status() === "success"}>
                  <div role="alert" class="alert alert-success">
                    <Icon path={checkCircle} class="stroke-current shrink-0 h-5 w-5" />
                    <span class="text-sm">{siteConfig.contact.form.success}</span>
                  </div>
                </Show>

                <button
                  type="submit"
                  class="btn btn-primary btn-lg w-full shadow-lg shadow-primary/25 hover:shadow-xl hover:shadow-primary/30 transition-all duration-300"
                  disabled={status() === "sending"}
                >
                  {status() === "sending" ? (
                    <>
                      <span class="loading loading-spinner loading-sm"></span>
                      {siteConfig.contact.form.sending}
                    </>
                  ) : (
                    <>
                      <Icon path={paperAirplane} class="w-5 h-5" />
                      {siteConfig.contact.form.submit}
                    </>
                  )}
                </button>
              </form>
            </div>
          </div>

          <div class="mt-10 text-center">
            <p class="text-base-content/60 mb-4">{siteConfig.contact.direct.text}</p>
            <a
              href={`mailto:${siteConfig.contact.direct.email}`}
              class="link font-medium inline-flex items-center gap-2 hover:gap-3 transition-all text-base-content hover:text-primary"
            >
              <Icon path={envelope} class="w-5 h-5" />
              {siteConfig.contact.direct.email}
            </a>
          </div>
        </div>
      </div>
    </section>
  );
};

export default ContactSection;
