import { createFileRoute, Link } from "@tanstack/react-router";
import { useState, type FormEvent, type MouseEvent } from "react";
import { Phone, Mail, MessageSquare, Clock, MapPin, LoaderCircle, Send, ArrowUpRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { GatavaseAiWidget } from "@/components/gatavase-ai";
import { PublicFooter } from "@/components/public-footer";
import { PublicSiteHeader } from "@/components/public-site-header";
import { submitContactRequest } from "@/lib/contact.functions";

export const Route = createFileRoute("/contact")({
  head: () => ({
    meta: [
      { title: "Contact & Support — Gatavase Bulky SMS" },
      { name: "description", content: "Talk to Gatavase Bulky SMS support: call +256 773 231 138 or +256 762 502 080, or email support@gatavase.com for help with bulk SMS in Uganda." },
      { property: "og:title", content: "Contact Gatavase Bulky SMS" },
      { property: "og:description", content: "Support numbers, email, and Gatavase AI assistant for bulk SMS help." },
      { name: "twitter:card", content: "summary" },
      { property: "og:type", content: "website" },
      { property: "og:url", content: "https://sms.gatavaseug.com/contact" },
    ],
    links: [{ rel: "canonical", href: "https://sms.gatavaseug.com/contact" }],
  }),
  component: ContactPage,
});

function ContactPage() {
  const [submitting, setSubmitting] = useState(false);
  const [status, setStatus] = useState("");
  const [statusIsError, setStatusIsError] = useState(false);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = event.currentTarget;
    const formData = new FormData(form);
    setSubmitting(true);
    setStatus("");
    setStatusIsError(false);

    try {
      await submitContactRequest({
        data: {
          name: String(formData.get("name") ?? ""),
          email: String(formData.get("email") ?? ""),
          phone: String(formData.get("phone") ?? ""),
          topic: String(formData.get("topic") ?? "General question") as "General question" | "Sales and pricing" | "Technical support" | "SMS API and integrations",
          message: String(formData.get("message") ?? ""),
          consent: formData.get("consent") === "on",
          website: String(formData.get("website") ?? ""),
        },
      });
      form.reset();
      setStatus("Thanks for reaching out. Your message has been sent to our support team.");
    } catch {
      setStatusIsError(true);
      setStatus("We couldn't send your request. Please try WhatsApp or email support@gatavase.com.");
    } finally {
      setSubmitting(false);
    }
  }

  function handleWhatsApp(event: MouseEvent<HTMLButtonElement>) {
    const form = event.currentTarget.form;
    if (!form || !form.reportValidity()) return;
    const formData = new FormData(form);
    const message = [
      "Hello Gatavase Bulky SMS, I have a question.",
      "",
      `Name: ${String(formData.get("name") ?? "")}`,
      `Email: ${String(formData.get("email") ?? "")}`,
      `Phone: ${String(formData.get("phone") ?? "Not provided") || "Not provided"}`,
      `Topic: ${String(formData.get("topic") ?? "General question")}`,
      "",
      String(formData.get("message") ?? ""),
    ].join("\n");
    window.open(`https://wa.me/256773231138?text=${encodeURIComponent(message)}`, "_blank", "noopener,noreferrer");
    setStatusIsError(false);
    setStatus("WhatsApp opened with your message. Review it there and tap Send.");
  }

  return (
    <div className="min-h-screen bg-background">
      <PublicSiteHeader activePath="/contact" />

      <section className="bg-gradient-hero py-16 text-primary-foreground">
        <div className="container mx-auto max-w-4xl px-4 text-center">
          <h1 className="font-display text-4xl font-bold md:text-5xl">We're here to help</h1>
          <p className="mt-3 text-primary-foreground/90">
            Real humans in Uganda + Gatavase AI, 24/7. Reach us any way you like.
          </p>
        </div>
      </section>

      <section className="container mx-auto max-w-7xl px-5 py-12 sm:px-8 sm:py-16">
        <div className="grid items-start gap-8 lg:grid-cols-[0.8fr_1.2fr]">
          <div>
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-1">
              <ContactCard icon={<Phone className="h-5 w-5" />} title="Call or WhatsApp">
                <a href="tel:+256773231138" className="block font-semibold text-primary hover:underline">+256 773 231 138</a>
                <a href="tel:+256762502080" className="block font-semibold text-primary hover:underline">+256 762 502 080</a>
                <p className="mt-2 text-sm text-muted-foreground">Mon–Sat · 8:00–20:00 EAT</p>
              </ContactCard>

              <ContactCard icon={<Mail className="h-5 w-5" />} title="Email support">
                <a href="mailto:support@gatavase.com" className="block font-semibold text-primary hover:underline">support@gatavase.com</a>
                <p className="mt-2 text-sm text-muted-foreground">We reply within a few working hours.</p>
              </ContactCard>

              <ContactCard icon={<MessageSquare className="h-5 w-5" />} title="Ask Gatavase AI">
                <p className="text-sm leading-6 text-muted-foreground">Get quick help with pricing, features, or drafting SMS copy from our assistant.</p>
                <div className="mt-4"><GatavaseAiWidget floating={false} buttonLabel="Chat with Gatavase AI" /></div>
              </ContactCard>

              <ContactCard icon={<MapPin className="h-5 w-5" />} title="Gatavase Corporation">
                <p className="text-sm">Kampala, Uganda 🇺🇬</p>
                <p className="mt-2 flex items-center gap-1 text-sm text-muted-foreground"><Clock className="h-3 w-3" /> Support in English, Luganda & Swahili.</p>
              </ContactCard>
            </div>
          </div>

          <div className="rounded-2xl border border-border bg-card p-5 shadow-card sm:p-8">
            <p className="text-sm font-semibold text-primary">Send us a message</p>
            <h2 className="mt-2 font-display text-2xl font-bold">How can we help?</h2>
            <p className="mt-2 text-sm leading-6 text-muted-foreground">Complete the form and our team will get back to you. Or continue in WhatsApp with your details filled in.</p>

            <form className="mt-7 space-y-5" onSubmit={handleSubmit}>
              <div className="grid gap-5 sm:grid-cols-2">
                <div className="space-y-2">
                  <label htmlFor="contact-name" className="text-sm font-medium">Your name</label>
                  <Input id="contact-name" name="name" autoComplete="name" maxLength={120} required minLength={2} placeholder="Jane Namusoke" />
                </div>
                <div className="space-y-2">
                  <label htmlFor="contact-email" className="text-sm font-medium">Email address</label>
                  <Input id="contact-email" name="email" type="email" autoComplete="email" maxLength={254} required placeholder="you@company.com" />
                </div>
              </div>
              <div className="grid gap-5 sm:grid-cols-2">
                <div className="space-y-2">
                  <label htmlFor="contact-phone" className="text-sm font-medium">Phone number <span className="font-normal text-muted-foreground">(optional)</span></label>
                  <Input id="contact-phone" name="phone" type="tel" autoComplete="tel" maxLength={40} placeholder="+256 7xx xxx xxx" />
                </div>
                <div className="space-y-2">
                  <label htmlFor="contact-topic" className="text-sm font-medium">What can we help with?</label>
                  <select id="contact-topic" name="topic" className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" defaultValue="General question">
                    <option>General question</option>
                    <option>Sales and pricing</option>
                    <option>Technical support</option>
                    <option>SMS API and integrations</option>
                  </select>
                </div>
              </div>
              <div className="space-y-2">
                <label htmlFor="contact-message" className="text-sm font-medium">Message</label>
                <Textarea id="contact-message" name="message" required minLength={10} maxLength={4000} rows={5} placeholder="Tell us a little about what you need…" className="resize-y" />
              </div>
              <label className="flex items-start gap-2.5 text-xs leading-5 text-muted-foreground">
                <input name="consent" type="checkbox" required className="mt-1 h-4 w-4 shrink-0 accent-primary" />
                <span>I agree that Gatavase can use these details to respond to my enquiry. See our <Link to="/privacy" className="font-medium text-primary underline underline-offset-2">Privacy Policy</Link>.</span>
              </label>
              <div className="hidden" aria-hidden="true">
                <label htmlFor="contact-website">Leave this field empty</label>
                <input id="contact-website" name="website" type="text" tabIndex={-1} autoComplete="off" />
              </div>
              <div className="flex flex-col gap-3 sm:flex-row">
                <Button type="submit" disabled={submitting} className="sm:flex-1">
                  {submitting ? <LoaderCircle className="animate-spin" /> : <Send className="h-4 w-4" />}
                  {submitting ? "Sending…" : "Submit"}
                </Button>
                <Button type="button" variant="outline" disabled={submitting} onClick={handleWhatsApp} className="sm:flex-1">
                  <MessageSquare className="h-4 w-4" /> Submit via WhatsApp <ArrowUpRight className="h-4 w-4" />
                </Button>
              </div>
              <p className={`min-h-5 text-sm ${statusIsError ? "text-destructive" : "text-muted-foreground"}`} aria-live="polite">{status}</p>
            </form>
          </div>
        </div>

        <div className="mt-12 rounded-2xl border border-border bg-card p-8 text-center">
          <h2 className="font-display text-2xl font-bold">Ready to send your first campaign?</h2>
          <p className="mt-2 text-muted-foreground">Start with 50 free SMS credits when you sign up.</p>
          <div className="mt-5 flex flex-wrap justify-center gap-3">
            <Link to="/auth"><Button size="lg" className="bg-gradient-brand text-primary-foreground">Create free account</Button></Link>
            <Link to="/sms-calculator"><Button size="lg" variant="outline">SMS cost calculator</Button></Link>
          </div>
        </div>
      </section>

      <PublicFooter />

    </div>
  );
}

function ContactCard({ icon, title, children }: { icon: React.ReactNode; title: string; children: React.ReactNode }) {
  return (
    <div className="rounded-2xl border border-border bg-card p-6 shadow-sm">
      <div className="mb-3 inline-flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-warm text-accent-foreground">
        {icon}
      </div>
      <h3 className="font-display text-lg font-bold">{title}</h3>
      <div className="mt-2">{children}</div>
    </div>
  );
}
