import { createFileRoute } from "@tanstack/react-router";
import { SiteHeader } from "@/components/SiteHeader";
import { SiteFooter } from "@/components/SiteFooter";
import { PageHero } from "@/components/PageHero";
import heroBg from "@/assets/gallery-community-2.jpg";
import { Phone, Mail, MapPin, Send, MessageSquareHeart, Loader2, MessageCircle } from "lucide-react";
import { useState } from "react";
import { supabase } from "@/integrations/supabase/client";

export const Route = createFileRoute("/contact")({
  head: () => ({
    meta: [
      { title: "Contact DSAG" },
      { name: "description", content: "Get in touch with the Down Syndrome Association of Ghana — questions, partnerships, support and feedback." },
      { property: "og:title", content: "Contact DSAG" },
    ],
  }),
  component: ContactPage,
});

function ContactPage() {
  const [sent, setSent] = useState(false);
  const [feedbackSent, setFeedbackSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [feedbackSending, setFeedbackSending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [feedbackError, setFeedbackError] = useState<string | null>(null);

  const handleContactSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);
    setSending(true);
    const fd = new FormData(e.currentTarget);
    const payload = {
      name: String(fd.get("name") || "").trim().slice(0, 200),
      email: String(fd.get("email") || "").trim().slice(0, 200),
      subject: String(fd.get("subject") || "").trim().slice(0, 200),
      message: String(fd.get("message") || "").trim().slice(0, 4000),
    };
    const { error: err } = await supabase.from("contact_messages").insert(payload);
    setSending(false);
    if (err) { setError("Could not send. Please try again."); return; }
    setSent(true);
    e.currentTarget.reset();
  };

  const handleFeedbackSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setFeedbackError(null);
    setFeedbackSending(true);
    const fd = new FormData(e.currentTarget);
    const payload = {
      name: String(fd.get("name") || "").trim().slice(0, 200),
      email: String(fd.get("email") || "").trim().slice(0, 200),
      phone: String(fd.get("phone") || "").trim().slice(0, 50) || null,
      affiliation: String(fd.get("affiliation") || "").trim().slice(0, 100) || null,
      comment: String(fd.get("comment") || "").trim().slice(0, 4000),
    };
    const { error: err } = await supabase.from("feedback_submissions").insert(payload);
    setFeedbackSending(false);
    if (err) { setFeedbackError("Could not send. Please try again."); return; }
    setFeedbackSent(true);
    e.currentTarget.reset();
  };

  return (
    <div className="min-h-screen flex flex-col bg-background">
      <SiteHeader />
      <main className="flex-1">
        <PageHero eyebrow="Contact" title="We'd love to hear from you." subtitle="Questions, partnerships, support requests or media enquiries — reach out anytime." bgImage={heroBg} />

        <section className="max-w-7xl mx-auto px-6 py-20 grid lg:grid-cols-3 gap-8">
          <div className="space-y-5 lg:col-span-1">
            {[
              { icon: Phone, t: "Call", v: "+233 (0) 20 740 5343" },
              { icon: MessageCircle, t: "WhatsApp", v: "+233 (0) 20 740 5343", href: "https://wa.me/233207405343" },
              { icon: Mail, t: "Email", v: "info@downsyndromeghana.org" },
              { icon: MapPin, t: "Visit", v: "Accra, Ghana" },
            ].map((b) => (
              <div key={b.t} className="bg-card border border-border rounded-2xl p-6 shadow-soft flex gap-4">
                <div className="h-12 w-12 rounded-xl bg-primary text-primary-foreground flex items-center justify-center shrink-0">
                  <b.icon className="h-5 w-5" />
                </div>
                <div>
                  <div className="font-display font-bold">{b.t}</div>
                  {b.href ? (
                    <a href={b.href} target="_blank" rel="noopener noreferrer" className="text-sm text-muted-foreground mt-1 block hover:text-primary">{b.v}</a>
                  ) : (
                    <div className="text-sm text-muted-foreground mt-1">{b.v}</div>
                  )}
                </div>
              </div>
            ))}
          </div>

          <form
            onSubmit={handleContactSubmit}
            className="lg:col-span-2 bg-card border border-border rounded-2xl p-8 shadow-soft space-y-5"
          >
            <div className="grid sm:grid-cols-2 gap-5">
              <label className="block">
                <span className="text-sm font-semibold">Your name</span>
                <input name="name" required maxLength={200} className="mt-1.5 w-full rounded-lg border border-border bg-background px-4 py-2.5 text-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20" />
              </label>
              <label className="block">
                <span className="text-sm font-semibold">Email</span>
                <input name="email" required type="email" maxLength={200} className="mt-1.5 w-full rounded-lg border border-border bg-background px-4 py-2.5 text-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20" />
              </label>
            </div>
            <label className="block">
              <span className="text-sm font-semibold">Subject</span>
              <input name="subject" required maxLength={200} className="mt-1.5 w-full rounded-lg border border-border bg-background px-4 py-2.5 text-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20" />
            </label>
            <label className="block">
              <span className="text-sm font-semibold">Message</span>
              <textarea name="message" required rows={5} maxLength={4000} className="mt-1.5 w-full rounded-lg border border-border bg-background px-4 py-2.5 text-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20" />
            </label>
            <button
              type="submit"
              disabled={sending}
              className="inline-flex items-center gap-2 rounded-full bg-primary text-primary-foreground font-semibold px-7 py-3 hover:scale-[1.02] transition disabled:opacity-60"
            >
              {sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />} {sending ? "Sending…" : "Send message"}
            </button>
            {sent && <p className="text-sm text-primary">Thank you — we'll be in touch soon!</p>}
            {error && <p className="text-sm text-destructive">{error}</p>}
          </form>
        </section>



        <section id="feedback" className="bg-surface border-y border-border">
          <div className="max-w-5xl mx-auto px-6 py-20">
            <div className="text-center max-w-2xl mx-auto mb-10">
              <div className="inline-flex h-12 w-12 rounded-xl bg-accent text-accent-foreground items-center justify-center mb-4"><MessageSquareHeart className="h-6 w-6" /></div>
              <h2 className="font-display font-bold text-3xl md:text-4xl">We value your voice</h2>
              <p className="mt-4 text-muted-foreground">Please share your comments, suggestions or inquiries. Your feedback helps us improve our support for families and communities across Ghana.</p>
            </div>
            <form
              onSubmit={handleFeedbackSubmit}
              className="bg-card border border-border rounded-2xl p-8 shadow-soft space-y-5"
            >
              <div className="grid sm:grid-cols-2 gap-5">
                <label className="block">
                  <span className="text-sm font-semibold">Name <span className="text-primary">*</span></span>
                  <input name="name" required maxLength={200} className="mt-1.5 w-full rounded-lg border border-border bg-background px-4 py-2.5 text-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20" />
                </label>
                <label className="block">
                  <span className="text-sm font-semibold">Email <span className="text-primary">*</span></span>
                  <input name="email" required type="email" maxLength={200} className="mt-1.5 w-full rounded-lg border border-border bg-background px-4 py-2.5 text-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20" />
                </label>
                <label className="block">
                  <span className="text-sm font-semibold">Phone number <span className="text-muted-foreground font-normal">(optional)</span></span>
                  <input name="phone" type="tel" maxLength={50} className="mt-1.5 w-full rounded-lg border border-border bg-background px-4 py-2.5 text-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20" />
                </label>
                <label className="block">
                  <span className="text-sm font-semibold">Affiliation</span>
                  <select name="affiliation" className="mt-1.5 w-full rounded-lg border border-border bg-background px-4 py-2.5 text-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20">
                    <option>Parent</option>
                    <option>Educator</option>
                    <option>Volunteer</option>
                    <option>Healthcare Professional</option>
                    <option>Other</option>
                  </select>
                </label>
              </div>
              <label className="block">
                <span className="text-sm font-semibold">Comment / suggestion</span>
                <textarea name="comment" required rows={5} maxLength={4000} className="mt-1.5 w-full rounded-lg border border-border bg-background px-4 py-2.5 text-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20" />
              </label>
              <button
                type="submit"
                disabled={feedbackSending}
                className="inline-flex items-center gap-2 rounded-full bg-accent text-accent-foreground font-semibold px-7 py-3 hover:scale-[1.02] transition disabled:opacity-60"
              >
                {feedbackSending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />} {feedbackSending ? "Sending…" : "Send Feedback"}
              </button>
              <p className="text-xs text-muted-foreground">Your information will only be used to respond to your inquiry and will not be shared.</p>
              {feedbackSent && <p className="text-sm text-primary">Thank you — your feedback has been received!</p>}
              {feedbackError && <p className="text-sm text-destructive">{feedbackError}</p>}
            </form>
          </div>
        </section>

        <section aria-label="Find us" className="border-t border-border">
          <div className="max-w-7xl mx-auto px-6 py-16">
            <div className="text-center max-w-2xl mx-auto mb-8">
              <span className="text-sm font-semibold text-primary uppercase tracking-widest">Find Us</span>
              <h2 className="font-display font-bold text-3xl md:text-4xl mt-3">Visit our office in Accra</h2>
            </div>
            <div className="rounded-2xl overflow-hidden border border-border shadow-soft">
              <iframe
                title="DSAG location — Accra, Ghana"
                src="https://www.google.com/maps?q=Accra,Ghana&output=embed"
                width="100%"
                height="450"
                loading="lazy"
                referrerPolicy="no-referrer-when-downgrade"
                style={{ border: 0 }}
              />
            </div>
          </div>
        </section>

      </main>
      <SiteFooter />
    </div>
  );
}
