"use client";

import { useRef, useState, useTransition } from "react";
import { useStudioSlug } from "@/components/site/site-link";

export type ContactProfileFields = {
  publicEmail?: string | null;
  phone?: string | null;
  whatsapp?: string | null;
  businessHours?: string | null;
  location?: string | null;
  mapEmbedUrl?: string | null;
  socialLinks?: Record<string, string> | null;
};

export default function TenantContactForm({
  studioName,
  profile,
}: {
  studioName: string;
  profile?: ContactProfileFields | null;
}) {
  const formRef = useRef<HTMLFormElement>(null);
  const studioSlug = useStudioSlug();
  const [pending, startTransition] = useTransition();
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const location = profile?.location;
  const socialEntries = Object.entries(profile?.socialLinks ?? {}).filter(
    ([, url]) => Boolean(url?.trim()),
  );
  const hasContactDetails = Boolean(
    profile?.publicEmail ||
      profile?.phone ||
      profile?.whatsapp ||
      profile?.businessHours ||
      location ||
      profile?.mapEmbedUrl ||
      socialEntries.length > 0,
  );

  function onSubmit(formData: FormData) {
    setMessage(null);
    setError(null);
    startTransition(async () => {
      const payload = {
        name: String(formData.get("name") ?? ""),
        email: String(formData.get("email") ?? ""),
        phone: String(formData.get("phone") ?? "") || undefined,
        message: String(formData.get("message") ?? ""),
      };

      const headers: HeadersInit = {
        "Content-Type": "application/json",
      };
      if (studioSlug) {
        headers["x-archi-tenant-slug"] = studioSlug;
      }

      const res = await fetch("/api/public/inquiries", {
        method: "POST",
        headers,
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        const data = (await res.json().catch(() => null)) as {
          error?: string;
        } | null;
        setError(
          data?.error === "Tenant not available"
            ? "This studio is unavailable for inquiries right now."
            : data?.error === "Validation failed"
              ? "Please check your details and try again."
              : "Unable to send inquiry. Please try again in a moment.",
        );
        return;
      }

      formRef.current?.reset();
      setMessage(
        `Thank you — your inquiry was sent to ${studioName}. The studio will reply using the contact details you provided.`,
      );
    });
  }

  return (
    <div className="studio-container grid gap-10 pb-[max(4rem,env(safe-area-inset-bottom))] pt-10 sm:gap-12 sm:pt-12 lg:grid-cols-[0.95fr_1.05fr] lg:gap-20">
      <aside className="order-2 space-y-8 lg:order-1">
        {hasContactDetails ? (
          <dl className="space-y-5 text-sm">
            {profile?.publicEmail ? (
              <div>
                <dt className="tracking-[0.16em] text-[var(--archi-ink-muted)] uppercase">
                  Email
                </dt>
                <dd className="mt-1.5">
                  <a
                    href={`mailto:${profile.publicEmail}`}
                    className="inline-flex min-h-11 items-center underline decoration-[var(--archi-gold)] underline-offset-4 transition hover:opacity-70"
                  >
                    {profile.publicEmail}
                  </a>
                </dd>
              </div>
            ) : null}
            {profile?.phone ? (
              <div>
                <dt className="tracking-[0.16em] text-[var(--archi-ink-muted)] uppercase">
                  Phone
                </dt>
                <dd className="mt-1.5">
                  <a
                    href={`tel:${profile.phone}`}
                    className="inline-flex min-h-11 items-center underline decoration-[var(--archi-gold)] underline-offset-4 transition hover:opacity-70"
                  >
                    {profile.phone}
                  </a>
                </dd>
              </div>
            ) : null}
            {profile?.whatsapp ? (
              <div>
                <dt className="tracking-[0.16em] text-[var(--archi-ink-muted)] uppercase">
                  WhatsApp
                </dt>
                <dd className="mt-1.5">
                  <a
                    href={`https://wa.me/${profile.whatsapp.replace(/\D/g, "")}`}
                    target="_blank"
                    rel="noreferrer"
                    className="inline-flex min-h-11 items-center underline decoration-[var(--archi-gold)] underline-offset-4 transition hover:opacity-70"
                  >
                    {profile.whatsapp}
                  </a>
                </dd>
              </div>
            ) : null}
            {profile?.businessHours ? (
              <div>
                <dt className="tracking-[0.16em] text-[var(--archi-ink-muted)] uppercase">
                  Hours
                </dt>
                <dd className="mt-1.5 whitespace-pre-wrap text-[var(--archi-ink)]/80">
                  {profile.businessHours}
                </dd>
              </div>
            ) : null}
            {location ? (
              <div>
                <dt className="tracking-[0.16em] text-[var(--archi-ink-muted)] uppercase">
                  Location
                </dt>
                <dd className="mt-1.5 text-[var(--archi-ink)]/80">{location}</dd>
              </div>
            ) : null}
            {socialEntries.length > 0 ? (
              <div>
                <dt className="tracking-[0.16em] text-[var(--archi-ink-muted)] uppercase">
                  Social
                </dt>
                <dd className="mt-2 flex flex-wrap gap-x-5 gap-y-2">
                  {socialEntries.map(([key, url]) => (
                    <a
                      key={key}
                      href={url}
                      target="_blank"
                      rel="noreferrer"
                      className="inline-flex min-h-11 items-center capitalize underline decoration-[var(--archi-gold)] underline-offset-4 transition hover:opacity-70"
                    >
                      {key === "x" ? "X" : key}
                    </a>
                  ))}
                </dd>
              </div>
            ) : null}
          </dl>
        ) : (
          <p className="text-sm leading-7 text-[var(--archi-ink-muted)]">
            Use the form to reach {studioName} directly. Inquiries stay private
            to this studio.
          </p>
        )}

        {profile?.mapEmbedUrl ? (
          <div className="aspect-[4/3] w-full overflow-hidden bg-[var(--archi-bg-deep)] lg:max-w-md">
            <iframe
              src={profile.mapEmbedUrl}
              title="Studio location map"
              className="h-full w-full border-0"
              loading="lazy"
              referrerPolicy="no-referrer-when-downgrade"
            />
          </div>
        ) : null}

        <p className="text-xs leading-5 text-[var(--archi-ink-muted)]">
          By submitting, you agree that {studioName} may contact you about this
          inquiry. Your details are not shared with other studios on ARCHI.
        </p>
      </aside>

      <div className="order-1 lg:order-2">
        {message ? (
          <div
            className="border border-[var(--archi-line)] bg-[var(--studio-stone)] px-6 py-10 sm:px-8"
            role="status"
            aria-live="polite"
          >
            <div className="studio-line-accent mb-5 h-px w-12" />
            <p className="text-[0.65rem] tracking-[0.24em] text-[var(--archi-gold)] uppercase">
              Received
            </p>
            <h2 className="mt-3 font-[family-name:var(--font-display)] text-2xl tracking-tight sm:text-3xl">
              Inquiry sent
            </h2>
            <p className="mt-4 max-w-md text-sm leading-7 text-[var(--archi-ink-muted)]">
              {message}
            </p>
            <button
              type="button"
              className="studio-btn-ghost mt-8"
              onClick={() => setMessage(null)}
            >
              Send another message
            </button>
          </div>
        ) : (
          <form ref={formRef} action={onSubmit} className="space-y-5">
            <label className="block text-sm tracking-wide">
              Name
              <input
                name="name"
                required
                autoComplete="name"
                disabled={pending}
                className="archi-input mt-2"
              />
            </label>
            <label className="block text-sm tracking-wide">
              Email
              <input
                name="email"
                type="email"
                required
                autoComplete="email"
                inputMode="email"
                disabled={pending}
                className="archi-input mt-2"
              />
            </label>
            <label className="block text-sm tracking-wide">
              Phone
              <input
                name="phone"
                type="tel"
                autoComplete="tel"
                inputMode="tel"
                disabled={pending}
                className="archi-input mt-2"
              />
            </label>
            <label className="block text-sm tracking-wide">
              Message
              <textarea
                name="message"
                required
                minLength={10}
                rows={6}
                disabled={pending}
                className="archi-input mt-2 resize-y"
              />
            </label>
            {error ? (
              <p className="text-sm text-red-800" role="alert">
                {error}
              </p>
            ) : null}
            <button
              type="submit"
              disabled={pending}
              className="studio-btn-primary w-full disabled:opacity-60 sm:w-auto"
            >
              {pending ? "Sending…" : "Send inquiry"}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}
