import { A } from "@solidjs/router";
import { Show, createMemo, createSignal, onCleanup, onMount, For } from "solid-js";
import PublicBackground from "~/components/PublicBackground";
import PublicHeader from "~/components/PublicHeader";
import PublicFooter from "~/components/PublicFooter";

type FormValues = {
  fullName: string;
  email: string;
  phone: string;
  userType: string;
  topic: string;
  message: string;
  attachment: File | null;
};

type FormErrors = Partial<Record<keyof FormValues, string>>;

const initialValues: FormValues = {
  fullName: "",
  email: "",
  phone: "",
  userType: "",
  topic: "",
  message: "",
  attachment: null,
};

const userTypes = [
  "Customer (Hire professional)",
  "Company (Post job)",
  "Professional (Provide services)",
  "Job Seeker (Apply jobs)",
] as const;

const topics = [
  "Account & Login",
  "Verification",
  "Posting a Job",
  "Posting a Requirement",
  "Leads / Matching",
  "Payments / Credits",
  "Bug Report",
  "Other",
] as const;

function IconMail() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <path d="M4 6h16v12H4z" />
      <path d="m4 7 8 6 8-6" />
    </svg>
  );
}

function IconClock() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <circle cx="12" cy="12" r="9" />
      <path d="M12 7v6l4 2" />
    </svg>
  );
}

function IconPin() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <path d="M12 21s6-5.4 6-11a6 6 0 1 0-12 0c0 5.6 6 11 6 11Z" />
      <circle cx="12" cy="10" r="2.2" />
    </svg>
  );
}

export default function ContactPage() {
  const [values, setValues] = createSignal<FormValues>(initialValues);
  const [errors, setErrors] = createSignal<FormErrors>({});
  const [submitted, setSubmitted] = createSignal(false);
  const [submitting, setSubmitting] = createSignal(false);
  const [showBackToTop, setShowBackToTop] = createSignal(false);
  const [scrollY, setScrollY] = createSignal(0);
  const [err, setErr] = createSignal("");

  const validate = (v: FormValues): FormErrors => {
    const next: FormErrors = {};
    if (!v.fullName.trim()) next.fullName = "Full name is required.";
    if (!v.email.trim()) next.email = "Email is required.";
    if (v.email.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.email.trim()))
      {next.email = "Enter a valid email.";}
    if (!v.userType.trim()) next.userType = "Please select user type.";
    if (!v.topic.trim()) next.topic = "Please select a topic.";
    if (!v.message.trim()) next.message = "Message is required.";
    if (v.message.trim() && v.message.trim().length < 20)
      {next.message = "Message must be at least 20 characters.";}
    if (v.attachment) {
      if (v.attachment.size > 10 * 1024 * 1024)
        {next.attachment = "Attachment must be 10MB or smaller.";}
      const allowed = ["application/pdf", "image/png", "image/jpeg", "image/jpg"];
      if (!allowed.includes(v.attachment.type)) next.attachment = "Allowed formats: PDF, PNG, JPG.";
    }
    return next;
  };

  const canSubmit = createMemo(() => Object.keys(validate(values())).length === 0);

  const update = <K extends keyof FormValues>(key: K, next: FormValues[K]) => {
    setValues((prev) => ({ ...prev, [key]: next }));
  };

  onMount(() => {
    const onScroll = () => {
      setShowBackToTop(window.scrollY > 500);
      setScrollY(window.scrollY || 0);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    onCleanup(() => window.removeEventListener("scroll", onScroll));
  });

  return (
    <main class="lp-main">
      <PublicBackground scrollY={scrollY()} />

      <div class="lp-content">
        <PublicHeader />

        <section class="public-section help-section-lg">
          <div class="container panel panel-dark contact-hero-panel">
            <p class="eyebrow">Reach out</p>
            <h1 class="lp-hero-title">Contact us</h1>
            <p class="lp-hero-copy">Tell us what you need — we’ll get back to you.</p>
            <div class="contact-pill-row">
              <span class="contact-pill">Support</span>
              <span class="contact-pill">Partnerships</span>
              <span class="contact-pill">Verification</span>
              <span class="contact-pill">General</span>
            </div>
          </div>
        </section>

        <section class="public-section help-section-mid">
          <div class="container">
            <div class="contact-layout-grid">
              <form
                class="card glass-light contact-form-card"
                onSubmit={async (event) => {
                  event.preventDefault();
                  const nextErrors = validate(values());
                  setErrors(nextErrors);
                  if (Object.keys(nextErrors).length > 0) return;

                  setSubmitting(true);
                  setErr("");
                  try {
                    const userTypeToCategory: Record<string, string> = {
                      "Customer (Hire professional)": "GENERAL",
                      "Company (Post job)": "ACCOUNT",
                      "Professional (Provide services)": "GENERAL",
                      "Job Seeker (Apply jobs)": "GENERAL",
                    };
                    const category = userTypeToCategory[values().userType] || "GENERAL";
                    const res = await fetch("/api/gateway/support/tickets", {
                      method: "POST",
                      headers: { "Content-Type": "application/json", Accept: "application/json" },
                      credentials: "include",
                      body: JSON.stringify({
                        subject: values().topic,
                        description: values().message,
                        category: category,
                        requester_name: values().fullName,
                        requester_email: values().email,
                        phone: values().phone,
                      }),
                    });
                    const data = await res.json().catch(() => ({}));
                    if (!res.ok) {
                      setErr(data.error || data.message || "Failed to submit ticket.");
                      return;
                    }
                    setSubmitted(true);
                    setValues(initialValues);
                    window.setTimeout(() => {
                      setSubmitted(false);
                      setErr("");
                    }, 3200);
                  } catch {
                    setErr("Network error while submitting ticket.");
                  } finally {
                    setSubmitting(false);
                  }
                }}
              >
                <div class="grid" style={{ "grid-template-columns": "1fr 1fr", margin: 0 }}>
                  <label class="field">
                    <span class="label">Full Name *</span>
                    <input
                      class="input"
                      value={values().fullName}
                      onInput={(e) => update("fullName", e.currentTarget.value)}
                    />
                    <Show when={errors().fullName}>
                      <p class="error">{errors().fullName}</p>
                    </Show>
                  </label>
                  <label class="field">
                    <span class="label">Email *</span>
                    <input
                      class="input"
                      type="email"
                      value={values().email}
                      onInput={(e) => update("email", e.currentTarget.value)}
                    />
                    <Show when={errors().email}>
                      <p class="error">{errors().email}</p>
                    </Show>
                  </label>
                </div>

                <div class="grid" style={{ "grid-template-columns": "1fr 1fr", margin: 0 }}>
                  <label class="field">
                    <span class="label">Phone</span>
                    <input
                      class="input"
                      value={values().phone}
                      onInput={(e) => update("phone", e.currentTarget.value)}
                    />
                  </label>
                  <label class="field">
                    <span class="label">User Type *</span>
                    <select
                      class="select"
                      value={values().userType}
                      onInput={(e) => update("userType", e.currentTarget.value)}
                    >
                      <option value="">Select user type</option>
                      <For each={userTypes}>{(type) => (
                        <option value={type}>{type}</option>
                      )}</For>
                    </select>
                    <Show when={errors().userType}>
                      <p class="error">{errors().userType}</p>
                    </Show>
                  </label>
                </div>

                <div class="grid" style={{ "grid-template-columns": "1fr 1fr", margin: 0 }}>
                  <label class="field">
                    <span class="label">Topic *</span>
                    <select
                      class="select"
                      value={values().topic}
                      onInput={(e) => update("topic", e.currentTarget.value)}
                    >
                      <option value="">Select topic</option>
                      <For each={topics}>{(topic) => (
                        <option value={topic}>{topic}</option>
                      )}</For>
                    </select>
                    <Show when={errors().topic}>
                      <p class="error">{errors().topic}</p>
                    </Show>
                  </label>
                  <label class="field">
                    <span class="label">Attachment</span>
                    <label class="contact-upload">
                      <span class="contact-upload-icon" aria-hidden="true">
                        ⌁
                      </span>
                      <span class="contact-upload-text">
                        {values().attachment
                          ? values().attachment?.name
                          : "Upload pdf/png/jpg (max 10MB)"}
                      </span>
                      <input
                        class="contact-upload-input"
                        type="file"
                        accept=".pdf,.png,.jpg,.jpeg"
                        onChange={(e) => update("attachment", e.currentTarget.files?.[0] ?? null)}
                      />
                    </label>
                    <Show when={errors().attachment}>
                      <p class="error">{errors().attachment}</p>
                    </Show>
                  </label>
                </div>

                <label class="field">
                  <span class="label">Message *</span>
                  <textarea
                    class="textarea"
                    value={values().message}
                    onInput={(e) => update("message", e.currentTarget.value)}
                  />
                  <Show when={errors().message}>
                    <p class="error">{errors().message}</p>
                  </Show>
                </label>

                <div class="hero-actions">
                  <button
                    class="lp-primary-btn"
                    type="submit"
                    disabled={!canSubmit() || submitting()}
                  >
                    {submitting() ? "Sending..." : "Send message"}
                  </button>
                  <button
                    class="lp-ghost-btn"
                    type="button"
                    onClick={() => {
                      setValues(initialValues);
                      setErrors({});
                      setErr("");
                    }}
                  >
                    Reset
                  </button>
                </div>
              </form>

              <aside class="card glass-dark contact-side-card">
                <h3>Contact details</h3>
                <p class="sub contact-detail">
                  <span class="contact-icon">
                    <IconMail />
                  </span>
                  support@nxtgauge.com
                </p>
                <p class="sub contact-detail">
                  <span class="contact-icon">
                    <IconClock />
                  </span>
                  Typically within 24–48 hours
                </p>
                <p class="sub contact-detail">
                  <span class="contact-icon">
                    <IconPin />
                  </span>
                  Remote-first, India
                </p>
                <div class="hero-actions">
                  <A class="lp-ghost-btn lp-ghost-btn-dark" href="/about">
                    About Us
                  </A>
                  <A class="lp-ghost-btn lp-ghost-btn-dark" href="/#faqs">
                    FAQs
                  </A>
                </div>
              </aside>
            </div>
          </div>
        </section>

        <section class="public-section help-section-lg">
          <div class="container">
            <h2 class="center">Common Questions</h2>
            <p class="center sub contact-quick-clarity">Quick clarity before you raise a query.</p>
            <div class="contact-mini-faq-grid">
              <article class="contact-mini-faq-card">
                <h3>Approval time</h3>
                <p>Most profile and listing approvals are completed in 24–48 hours.</p>
              </article>
              <article class="contact-mini-faq-card">
                <h3>Verification</h3>
                <p>Verification is required to reduce spam and improve trust.</p>
              </article>
              <article class="contact-mini-faq-card">
                <h3>Posting flow</h3>
                <p>You can submit multiple requirements and jobs after onboarding.</p>
              </article>
            </div>
          </div>
        </section>

        <Show when={submitted()}>
          <div
            style={{
              position: "fixed",
              right: "16px",
              top: "88px",
              "z-index": 90,
              padding: "10px 14px",
              "border-radius": "12px",
              border: "1px solid rgba(255,255,255,0.25)",
              background: "rgba(16,11,47,0.88)",
              color: "white",
              "font-weight": 700,
            }}
          >
            Message sent. We'll reply soon.
          </div>
        </Show>
        <Show when={err()}>
          <div
            style={{
              position: "fixed",
              right: "16px",
              top: "88px",
              "z-index": 90,
              padding: "10px 14px",
              "border-radius": "12px",
              border: "1px solid rgba(239,68,68,0.25)",
              background: "rgba(220,38,38,0.1)",
              color: "#DC2626",
              "font-weight": 700,
            }}
          >
            {err()}
          </div>
        </Show>

        <PublicFooter />

        <Show when={showBackToTop()}>
          <button class="back-top" onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}>
            ↑
          </button>
        </Show>
      </div>
    </main>
  );
}
