import { createFileRoute } from "@tanstack/react-router";
import type { FormEvent } from "react";
import { useState } from "react";

import { PlanSubmitButton, WhatsAppCta } from "~/components/site/ctas";
import { PLAN_PAGE } from "~/lib/content";
import {
  DESTINATIONS,
  getDestination,
  whatsappHref,
} from "~/lib/destinations";
import { currentOrigin } from "~/lib/origin";

export const Route = createFileRoute("/plan")({
  validateSearch: (search: Record<string, unknown>): { dest?: string } => {
    return typeof search.dest === "string" && getDestination(search.dest)
      ? { dest: search.dest }
      : {};
  },
  loader: async () => ({ origin: await currentOrigin() }),
  head: ({ loaderData }) => {
    const origin = loaderData?.origin ?? "";
    const title = "Plan My Trip | Zaviamo";
    return {
      meta: [
        { title },
        { name: "description", content: PLAN_PAGE.sub },
        { property: "og:title", content: title },
        { property: "og:description", content: PLAN_PAGE.sub },
        { property: "og:url", content: `${origin}/plan` },
        { name: "twitter:title", content: title },
        { name: "twitter:description", content: PLAN_PAGE.sub },
      ],
      links: [{ rel: "canonical", href: `${origin}/plan` }],
    };
  },
  component: PlanPage,
});

function PlanPage() {
  const { dest } = Route.useSearch();
  const preselected = dest ? (getDestination(dest)?.name ?? "") : "";

  const [name, setName] = useState("");
  const [destination, setDestination] = useState(
    preselected || PLAN_PAGE.otherDestination
  );
  const [dates, setDates] = useState("");
  const [travelers, setTravelers] = useState("");
  const [budget, setBudget] = useState("");
  const [notes, setNotes] = useState("");

  /* Composes the brief and opens the WhatsApp thread. The thread is the
     real channel; there is no backend and no fake success state. */
  const onSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const parts: string[] = [];
    parts.push(
      name.trim()
        ? `Assalam o Alaikum Zaviamo! I'm ${name.trim()}.`
        : "Assalam o Alaikum Zaviamo!"
    );
    let wish = "I want to plan a trip";
    if (destination && destination !== PLAN_PAGE.otherDestination) {
      wish += ` to ${destination}`;
    }
    if (dates.trim()) {
      wish += ` in ${dates.trim()}`;
    }
    if (travelers.trim()) {
      wish += ` for ${travelers.trim()}`;
    }
    parts.push(`${wish}.`);
    if (budget.trim()) {
      parts.push(`Budget: ${budget.trim()}.`);
    }
    if (notes.trim()) {
      parts.push(notes.trim());
    }
    window.open(whatsappHref(parts.join(" ")), "_blank", "noopener,noreferrer");
  };

  return (
    <main className="bg-cream text-ink">
      {/* Aspirational hero: the family already up there, looking out. The
          promise sits over it; the brief is one scroll away. */}
      <section className="zv-plan-hero">
        <img
          alt="A thrilled Pakistani family on holiday in a modern city skyline at golden hour"
          className="zv-plan-hero-img"
          src="/assets/plan/plan-hero-v4.jpg"
        />
        <div aria-hidden="true" className="zv-plan-hero-scrim" />
        <div className="zv-plan-hero-inner">
          <p className="zv-script zv-plan-hero-script">
            {PLAN_PAGE.scriptAccent}
          </p>
          <h1 className="zv-plan-hero-h1">{PLAN_PAGE.heading}</h1>
          <p className="zv-plan-hero-sub">{PLAN_PAGE.sub}</p>
          <ul className="zv-plan-chips">
            {PLAN_PAGE.heroChips.map((chip) => (
              <li className="zv-plan-chip" key={chip}>
                {chip}
              </li>
            ))}
          </ul>
        </div>
      </section>

      {/* Persuasion beside the form. The form card is sticky on desktop, so
          it stays in reach while the reassurance reads alongside it. */}
      <section className="zv-plan-body">
        <div className="zv-plan-grid">
          <div className="zv-plan-aside">
            <h2 className="zv-plan-h2">{PLAN_PAGE.reasonsTitle}</h2>
            <ul className="zv-plan-reasons">
              {PLAN_PAGE.reasons.map((reason) => (
                <li className="zv-plan-reason" key={reason.title}>
                  <h3 className="zv-plan-reason-title">{reason.title}</h3>
                  <p className="zv-plan-reason-text">{reason.text}</p>
                </li>
              ))}
            </ul>

            <h2 className="zv-plan-h2 zv-plan-h2-steps">
              {PLAN_PAGE.stepsTitle}
            </h2>
            <ol className="zv-plan-steps">
              {PLAN_PAGE.steps.map((step, index) => (
                <li className="zv-plan-step" key={step.title}>
                  <span aria-hidden="true" className="zv-plan-step-num">
                    {index + 1}
                  </span>
                  <div>
                    <h3 className="zv-plan-step-title">{step.title}</h3>
                    <p className="zv-plan-step-text">{step.text}</p>
                  </div>
                </li>
              ))}
            </ol>
          </div>

          <div className="zv-plan-formwrap">
            <div className="zv-plan-formcard">
              <div className="zv-plan-formhead">
                <h2 className="zv-plan-formtitle">{PLAN_PAGE.formCardTitle}</h2>
                <p className="zv-plan-formcardnote">{PLAN_PAGE.formCardNote}</p>
              </div>
              <form className="zv-plan-form" onSubmit={onSubmit}>
                <div className="grid gap-5 sm:grid-cols-2">
                  <div>
                    <label className="zv-field-label" htmlFor="plan-name">
                      Name
                    </label>
                    <input
                      className="zv-field"
                      id="plan-name"
                      onChange={(event) => setName(event.target.value)}
                      type="text"
                      value={name}
                    />
                  </div>
                  <div>
                    <label className="zv-field-label" htmlFor="plan-destination">
                      Destination
                    </label>
                    <select
                      className="zv-field"
                      id="plan-destination"
                      onChange={(event) => setDestination(event.target.value)}
                      value={destination}
                    >
                      {DESTINATIONS.map((d) => (
                        <option key={d.slug} value={d.name}>
                          {d.name}
                        </option>
                      ))}
                      <option value={PLAN_PAGE.otherDestination}>
                        {PLAN_PAGE.otherDestination}
                      </option>
                    </select>
                  </div>
                  <div>
                    <label className="zv-field-label" htmlFor="plan-dates">
                      Month and dates
                    </label>
                    <input
                      className="zv-field"
                      id="plan-dates"
                      onChange={(event) => setDates(event.target.value)}
                      placeholder="e.g. December, 10 days"
                      type="text"
                      value={dates}
                    />
                  </div>
                  <div>
                    <label className="zv-field-label" htmlFor="plan-travelers">
                      Travelers
                    </label>
                    <input
                      className="zv-field"
                      id="plan-travelers"
                      onChange={(event) => setTravelers(event.target.value)}
                      placeholder="2 adults, 2 kids"
                      type="text"
                      value={travelers}
                    />
                  </div>
                </div>
                <div>
                  <label className="zv-field-label" htmlFor="plan-budget">
                    Budget (optional)
                  </label>
                  <input
                    className="zv-field"
                    id="plan-budget"
                    onChange={(event) => setBudget(event.target.value)}
                    type="text"
                    value={budget}
                  />
                </div>
                <div>
                  <label className="zv-field-label" htmlFor="plan-notes">
                    Anything else we should know?
                  </label>
                  <textarea
                    className="zv-field"
                    id="plan-notes"
                    onChange={(event) => setNotes(event.target.value)}
                    placeholder="dietary needs, kids' ages, prayer timings, special occasions"
                    rows={4}
                    value={notes}
                  />
                </div>
                <PlanSubmitButton />
              </form>

              <p className="zv-plan-finenote">{PLAN_PAGE.formNote}</p>
              <p className="zv-plan-finenote">{PLAN_PAGE.reassurance}</p>

              <div className="zv-plan-or">
                <span>or</span>
              </div>
              <div className="zv-plan-wa">
                <WhatsAppCta tone="light" />
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}
