import { createFileRoute } from "@tanstack/react-router";
import { useState, type FormEvent } from "react";
import { Phone, Mail, MapPin, MessageCircle, Send } from "lucide-react";
import { apiUrl } from "@/lib/api";

export const Route = createFileRoute("/contact")({
  head: () => ({
    meta: [
      { title: "Contact — Igiciro" },
      {
        name: "description",
        content:
          "Get in touch with Igiciro — for orders, partnerships, or to refer a farmer to our network.",
      },
      { property: "og:title", content: "Contact — Igiciro" },
      {
        property: "og:description",
        content: "Get in touch — orders, partnerships, or referring a farmer.",
      },
    ],
  }),
  component: ContactPage,
});

function ContactPage() {
  const [sent, setSent] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const onSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);
    setSubmitting(true);

    const form = new FormData(e.currentTarget);
    const payload = {
      name: String(form.get("name") ?? "").trim(),
      email: String(form.get("email") ?? "").trim(),
      subject: String(form.get("subject") ?? "").trim(),
      message: String(form.get("message") ?? "").trim(),
    };

    try {
      const response = await fetch(apiUrl("/api/contact"), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      const data = await response.json();
      if (!response.ok) {
        setError(data.message ?? "Unable to send message.");
      } else {
        setSent(true);
        e.currentTarget.reset();
      }
    } catch (err) {
      setError("Unable to connect to the contact server.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section className="container-editorial pt-16 md:pt-24 pb-24 grid gap-16 md:grid-cols-12">
      <div className="md:col-span-5">
        <p className="text-xs uppercase tracking-widest text-tomato">Get in touch</p>
        <h1 className="mt-3 font-display text-5xl md:text-6xl text-balance">
          We'd love to hear from you.
        </h1>
        <p className="mt-5 text-muted-foreground leading-relaxed max-w-md">
          Whether you're a customer, a chef, a wholesaler, or a farmer who'd
          like to join our network — we read every message.
        </p>

        <ul className="mt-10 space-y-5">
          <Item icon={MapPin} label="Visit" value="KG 11 Ave, Kigali, Rwanda" />
          <Item icon={Phone} label="Call" value="+250 788 000 000" />
          <Item icon={Mail} label="Email" value="hello@igiciro.rw" />
          <Item icon={MessageCircle} label="WhatsApp" value="+250 790 217 818" />
        </ul>
      </div>

      <div className="md:col-span-7">
        <form
          onSubmit={onSubmit}
          className="rounded-3xl border border-border bg-card p-8 md:p-10 shadow-soft"
        >
          {sent ? (
            <div className="py-12 text-center">
              <div className="mx-auto h-12 w-12 grid place-items-center rounded-full bg-leaf/15 text-leaf">
                <Send className="h-5 w-5" />
              </div>
              <h2 className="mt-5 font-display text-2xl">Message sent</h2>
              <p className="mt-2 text-muted-foreground">
                Murakoze! We'll respond within one business day.
              </p>
            </div>
          ) : (
            <div className="grid gap-5">
              <div className="grid gap-5 sm:grid-cols-2">
                <Field label="Full name" name="name" required />
                <Field label="Email" name="email" type="email" required />
              </div>
              <Field label="Subject" name="subject" />
              <div>
                <label className="block text-xs uppercase tracking-widest text-muted-foreground mb-2">
                  Message
                </label>
                <textarea
                  name="message"
                  required
                  rows={5}
                  maxLength={1000}
                  className="w-full rounded-2xl border border-border bg-background px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-none"
                />
              </div>
              {error && <p className="text-sm text-destructive">{error}</p>}
              <button
                type="submit"
                disabled={submitting}
                className="mt-2 inline-flex items-center justify-center gap-2 rounded-full bg-foreground text-background px-6 py-4 text-sm font-medium hover:bg-foreground/90 disabled:opacity-70"
              >
                {submitting ? "Sending..." : "Send message"} <Send className="h-4 w-4" />
              </button>
            </div>
          )}
        </form>
      </div>
    </section>
  );
}

function Field({
  label,
  name,
  type = "text",
  required,
}: {
  label: string;
  name: string;
  type?: string;
  required?: boolean;
}) {
  return (
    <div>
      <label className="block text-xs uppercase tracking-widest text-muted-foreground mb-2">
        {label}
      </label>
      <input
        type={type}
        name={name}
        required={required}
        maxLength={255}
        className="w-full rounded-full border border-border bg-background px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
      />
    </div>
  );
}

function Item({
  icon: Icon,
  label,
  value,
}: {
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  value: string;
}) {
  return (
    <li className="flex items-start gap-4">
      <div className="grid h-11 w-11 place-items-center rounded-full bg-muted border border-border">
        <Icon className="h-5 w-5 text-leaf" />
      </div>
      <div>
        <p className="text-xs uppercase tracking-widest text-muted-foreground">{label}</p>
        <p className="mt-0.5 font-display text-lg">{value}</p>
      </div>
    </li>
  );
}
