"use client";

import { useState } from "react";
import Link from "next/link";
import { ArrowRight, Mail, MapPin, Phone, ShieldCheck } from "lucide-react";
import ImmersivePage from "@/components/immersive/ImmersivePage";
import RevealText from "@/components/immersive/RevealText";
import Reveal from "@/components/immersive/Reveal";
import { scrollToFirstFormError } from "@/lib/form-utils";
import { validateRequired } from "@/lib/common";
import { clearFieldError, validateEmail, validatePhone } from "@/utils/form-validation";

const CONTACT_CARDS = [
  {
    icon: MapPin,
    title: "Our location",
    lines: ["Dubai, United Arab Emirates"],
    href: null as string | null,
  },
  {
    icon: Mail,
    title: "Email us",
    lines: ["hello@oxyfinz.com"],
    href: "mailto:hello@oxyfinz.com",
  },
  {
    icon: Phone,
    title: "Call us",
    lines: ["+971 54 224 3814"],
    href: "tel:+971542243814",
  },
];

const SUBJECT_OPTIONS = [
  "Portfolio & Analytics",
  "Product Demo",
  "Support",
  "Partnership",
  "Other",
] as const;

/**
 * `autoComplete` is spelled out per field rather than derived from `name`.
 * Deriving it produced `autocomplete="phone"`, which is not a token in the
 * spec — browsers ignored it and fell back to guessing the field from its
 * label, which is why autofill behaved erratically here. `tel` is the token.
 */
const FIELDS = [
  { name: "name", label: "Name", type: "text", autoComplete: "name", inputMode: undefined },
  { name: "email", label: "Email", type: "email", autoComplete: "email", inputMode: "email" },
  { name: "phone", label: "Phone", type: "tel", autoComplete: "tel", inputMode: "tel" },
] as const;

type FormState = {
  name: string;
  email: string;
  phone: string;
  subject: string;
  message: string;
};

const EMPTY: FormState = { name: "", email: "", phone: "", subject: "", message: "" };

type FieldErrors = Partial<Record<keyof FormState, string>>;

/** Shortest message we will forward to the team. Below this it is almost always
    a stray keystroke rather than an enquiry. */
const MESSAGE_MIN = 10;

/**
 * Everything the form can check before it costs a round trip.
 *
 * The server validates the same payload and its 422 response is still handled
 * below — this is the fast, per-field half of that, so a visitor sees which
 * field is wrong next to the field rather than one summary line after a wait.
 */
function validate(values: FormState): FieldErrors {
  const errors: FieldErrors = {};

  const name = validateRequired(values.name, "Name");
  if (name) errors.name = name;
  else if (values.name.trim().length < 2) errors.name = "Enter your full name.";

  const email = validateEmail(values.email);
  if (email) errors.email = email;

  const phone = validatePhone(values.phone);
  if (phone) errors.phone = phone;

  const message = validateRequired(values.message, "Message");
  if (message) errors.message = message;
  else if (values.message.trim().length < MESSAGE_MIN) {
    errors.message = `Tell us a little more — at least ${MESSAGE_MIN} characters.`;
  }

  return errors;
}

/**
 * Contact page, styled after the immersive landing page. The form posts the
 * same payload shape to the same same-origin proxy (/api/contact ->
 * Yii2 /contact-api/submit) the landing page's enquiry form uses, including
 * the 422 field-error handling, so both entry points behave identically
 * against the backend.
 */
export default function ContactPage() {
  const [form, setForm] = useState<FormState>(EMPTY);
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (submitting) return;

    const errors = validate(form);
    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) {
      setError(null);
      // Focuses the first field that failed, so the visitor lands on the
      // problem instead of hunting for it.
      scrollToFirstFormError(errors);
      return;
    }

    setError(null);
    setSubmitting(true);
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await res.json().catch(() => null);

      if (res.status === 422) {
        const firstError =
          data?.errors && typeof data.errors === "object"
            ? (Object.values(data.errors).flat()[0] as string | undefined)
            : undefined;
        setError(firstError || "Please check your details and try again.");
        return;
      }

      if (!res.ok) {
        const raw = typeof data?.message === "string" ? data.message : "";
        // Backend validation failures sometimes surface as raw SQL; never
        // show that to a visitor.
        const looksLikeSql = /sqlstate|sql being executed/i.test(raw);
        setError(looksLikeSql || !raw ? "Something went wrong. Please try again." : raw);
        return;
      }

      setSubmitted(true);
      setForm(EMPTY);
      setFieldErrors({});
    } catch {
      setError("Something went wrong. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  const setField = (name: keyof FormState) => (value: string) => {
    setForm((prev) => ({ ...prev, [name]: value }));
    // Clear on edit, never re-validate on every keystroke: flagging an email as
    // invalid while it is still being typed is noise, not help.
    setFieldErrors((prev) => clearFieldError(prev, name));
  };

  return (
    <ImmersivePage>
      <h1 className="sr-only">Contact Oxyfinz</h1>

      <section className="px-6 pt-14 lg:px-12 lg:pt-20">
        <div className="mx-auto w-full max-w-[88rem]">
          <div className="immersive-section-head">
            <span className="immersive-label">Get in touch</span>
            <span className="immersive-label">[ Contact ]</span>
          </div>

          <div className="grid gap-8 lg:grid-cols-12 lg:gap-16">
            <div className="lg:col-span-7">
              <RevealText as="h2" immediate className="immersive-display">
                Reach out to us.
              </RevealText>
            </div>
            <Reveal delay={0.15} className="flex items-end lg:col-span-4 lg:col-start-9">
              <p className="text-base leading-relaxed text-[hsl(var(--muted-foreground))]">
                Tell us what you manage today and we will show you what it looks
                like in Oxyfinz — running against data like your own.
              </p>
            </Reveal>
          </div>

          <Reveal stagger={0.08} className="mt-14 grid gap-4 sm:grid-cols-2 lg:mt-16 lg:grid-cols-3 lg:gap-5">
            {CONTACT_CARDS.map((card) => {
              const Icon = card.icon;
              const body = (
                <>
                  <span className="immersive-chip">
                    <Icon className="size-5" aria-hidden />
                  </span>
                  <h3 className="font-heading mt-5 text-lg font-medium tracking-tight">
                    {card.title}
                  </h3>
                  {card.lines.map((line) => (
                    <p key={line} className="mt-1.5 text-sm text-[hsl(var(--muted-foreground))]">
                      {line}
                    </p>
                  ))}
                </>
              );
              return (
                <div key={card.title} data-reveal>
                  {card.href ? (
                    card.href.startsWith("/") ? (
                      <Link href={card.href} className="immersive-card block h-full p-6 lg:p-7">
                        {body}
                      </Link>
                    ) : (
                      <a href={card.href} className="immersive-card block h-full p-6 lg:p-7">
                        {body}
                      </a>
                    )
                  ) : (
                    <div className="immersive-card h-full p-6 lg:p-7">{body}</div>
                  )}
                </div>
              );
            })}
          </Reveal>
        </div>
      </section>

      <section className="immersive-section mt-16 px-6 py-16 lg:mt-24 lg:px-12 lg:py-24">
        <div className="mx-auto w-full max-w-[88rem]">
          <div className="grid gap-12 lg:grid-cols-12 lg:gap-16">
            <div className="lg:col-span-7">
              <RevealText as="h2" className="immersive-heading max-w-2xl">
                Feel free to get in touch or visit our location.
              </RevealText>

              {submitted ? (
                <div className="mt-10 border-t border-white/10 py-12">
                  <p className="font-heading text-2xl font-medium tracking-tight text-[hsl(var(--primary))]">
                    Thank you — message received.
                  </p>
                  <p className="mt-3 text-sm text-[hsl(var(--muted-foreground))]">
                    Someone from the team will be in touch shortly.
                  </p>
                  <button
                    type="button"
                    onClick={() => setSubmitted(false)}
                    className="mt-8 rounded-lg border border-white/15 px-5 py-2.5 text-[13px] font-semibold transition-colors hover:border-white/35"
                  >
                    Send another
                  </button>
                </div>
              ) : (
                <Reveal stagger={0.06} className="immersive-card mt-10 p-7 lg:p-8">
                  <form onSubmit={handleSubmit} noValidate>
                    {FIELDS.map((field) => {
                      const fieldError = fieldErrors[field.name];
                      return (
                        <div
                          key={field.name}
                          data-reveal
                          className="border-t border-white/10 first:border-t-0"
                        >
                          <label className="flex flex-col gap-2 py-5 lg:flex-row lg:items-center lg:gap-8">
                            <span
                              className={`immersive-label lg:w-32 lg:shrink-0 ${
                                fieldError ? "text-[hsl(var(--destructive))]" : ""
                              }`}
                            >
                              {field.label} *
                            </span>
                            <input
                              type={field.type}
                              name={field.name}
                              required
                              value={form[field.name]}
                              onChange={(e) => setField(field.name)(e.target.value)}
                              autoComplete={field.autoComplete}
                              inputMode={field.inputMode}
                              aria-invalid={fieldError ? true : undefined}
                              aria-describedby={fieldError ? `${field.name}-error` : undefined}
                              className="w-full bg-transparent text-base text-[hsl(var(--foreground))] outline-none placeholder:text-[hsl(var(--muted-foreground))]/60 focus:placeholder:text-transparent"
                              placeholder={`Your ${field.label.toLowerCase()}`}
                            />
                          </label>
                          {fieldError ? (
                            // lg:pl-40 clears the label column (w-32 + gap-8) so
                            // the message sits under the input, not the label.
                            <p
                              id={`${field.name}-error`}
                              role="alert"
                              className="-mt-3 pb-4 text-sm text-[hsl(var(--destructive))] lg:pl-40"
                            >
                              {fieldError}
                            </p>
                          ) : null}
                        </div>
                      );
                    })}

                    <div data-reveal className="border-t border-white/10">
                      <label className="flex flex-col gap-2 py-5 lg:flex-row lg:items-center lg:gap-8">
                        <span className="immersive-label lg:w-32 lg:shrink-0">Subject</span>
                        <select
                          name="subject"
                          autoComplete="off"
                          value={form.subject}
                          onChange={(e) => setField("subject")(e.target.value)}
                          className="w-full cursor-pointer bg-transparent text-base text-[hsl(var(--foreground))] outline-none [&>option]:bg-[hsl(var(--card))] [&>option]:text-[hsl(var(--foreground))]"
                        >
                          <option value="">Choose a topic</option>
                          {SUBJECT_OPTIONS.map((opt) => (
                            <option key={opt} value={opt}>
                              {opt}
                            </option>
                          ))}
                        </select>
                      </label>
                    </div>

                    <div data-reveal className="border-y border-white/10">
                      <label className="flex flex-col gap-2 py-5 lg:flex-row lg:gap-8">
                        <span
                          className={`immersive-label lg:w-32 lg:shrink-0 lg:pt-1 ${
                            fieldErrors.message ? "text-[hsl(var(--destructive))]" : ""
                          }`}
                        >
                          Message *
                        </span>
                        <textarea
                          name="message"
                          required
                          rows={4}
                          value={form.message}
                          onChange={(e) => setField("message")(e.target.value)}
                          aria-invalid={fieldErrors.message ? true : undefined}
                          aria-describedby={fieldErrors.message ? "message-error" : undefined}
                          className="w-full resize-none bg-transparent text-base text-[hsl(var(--foreground))] outline-none placeholder:text-[hsl(var(--muted-foreground))]/60 focus:placeholder:text-transparent"
                          placeholder="What are you managing today?"
                        />
                      </label>
                      {fieldErrors.message ? (
                        <p
                          id="message-error"
                          role="alert"
                          className="-mt-3 pb-4 text-sm text-[hsl(var(--destructive))] lg:pl-40"
                        >
                          {fieldErrors.message}
                        </p>
                      ) : null}
                    </div>

                    {error ? (
                      <p role="alert" className="pt-5 text-sm text-[hsl(var(--destructive))]">
                        {error}
                      </p>
                    ) : null}

                    <button
                      data-reveal
                      type="submit"
                      disabled={submitting}
                      className="group mt-8 inline-flex items-center gap-2 rounded-lg bg-[hsl(var(--primary))] px-6 py-3 text-sm font-semibold text-[hsl(var(--primary-foreground))] transition-colors hover:bg-[hsl(var(--primary-hover))] disabled:opacity-60"
                    >
                      {submitting ? "Sending…" : "Submit"}
                      <ArrowRight className="size-4 transition-transform group-hover:translate-x-0.5" />
                    </button>
                  </form>
                </Reveal>
              )}
            </div>

            <Reveal delay={0.1} className="lg:col-span-5">
              <div className="immersive-card h-full min-h-[320px] overflow-hidden lg:min-h-full">
                <iframe
                  title="Office location"
                  src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3610.178509650649!2d55.2708!3d25.2048!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3e5f682d8b57b70f%3A0x6e7e2e8b5b5b5b5b!2sDubai!5e0!3m2!1sen!2sae!4v1745918398047"
                  width="100%"
                  height="100%"
                  style={{ border: 0, minHeight: "320px" }}
                  allowFullScreen
                  loading="lazy"
                  referrerPolicy="no-referrer-when-downgrade"
                  className="block h-full min-h-[320px] w-full"
                />
              </div>
            </Reveal>
          </div>

          <Reveal delay={0.1} className="mt-14 lg:mt-16">
            <div className="flex flex-col gap-5 rounded-xl border border-[hsl(var(--primary))]/20 bg-[hsl(var(--primary))]/[0.06] p-7 sm:flex-row sm:items-center sm:justify-between lg:p-8">
              <div className="flex items-start gap-4">
                <span className="immersive-chip shrink-0">
                  <ShieldCheck className="size-5" aria-hidden />
                </span>
                <div>
                  <p className="font-heading text-lg font-medium tracking-tight">
                    Let&apos;s build the future together.
                  </p>
                  <p className="mt-1 text-sm text-[hsl(var(--muted-foreground))]">
                    A working walkthrough with our team, not a slide deck.
                  </p>
                </div>
              </div>
              <Link
                href="/register"
                className="group inline-flex shrink-0 items-center justify-center gap-2 rounded-lg bg-[hsl(var(--primary))] px-6 py-3 text-sm font-semibold text-[hsl(var(--primary-foreground))] transition-colors hover:bg-[hsl(var(--primary-hover))]"
              >
                Get started now
                <ArrowRight className="size-4 transition-transform group-hover:translate-x-0.5" />
              </Link>
            </div>
          </Reveal>
        </div>
      </section>
    </ImmersivePage>
  );
}
