import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import {
  CheckCircle2,
  Globe2,
  Mail,
  MapPin,
  MessageSquare,
  Phone,
  Send,
  Tag,
  User,
} from "lucide-react";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { PageHeader, Section, SectionHeading } from "@/components/site/PageHeader";
import { COUNTRIES } from "@/data/site";

export const Route = createFileRoute("/contact")({
  head: () => ({
    meta: [
      { title: "Contact Seed Co Group | Regional Offices & Enquiries" },
      {
        name: "description",
        content:
          "Contact Seed Co Group. Send an enquiry or reach our regional offices in Zimbabwe, Zambia, Kenya, Nigeria and across Africa.",
      },
      { property: "og:title", content: "Contact Seed Co Group" },
      { property: "og:description", content: "Send an enquiry or reach a regional Seed Co office." },
    ],
  }),
  component: ContactPage,
});

const schema = z.object({
  name: z.string().trim().min(2, "Please enter your full name").max(100, "Name must be under 100 characters"),
  email: z.string().trim().email("Enter a valid email address").max(255),
  country: z.string().min(1, "Please select your country"),
  subject: z.string().trim().min(3, "Please add a subject").max(150),
  message: z.string().trim().min(10, "Please give us a little more detail").max(1000, "Message must be under 1000 characters"),
});

type Errors = Partial<Record<keyof z.infer<typeof schema>, string>>;

const ENQUIRY_TOPICS = [
  { label: "Variety Advice", subject: "Agronomy & Variety Recommendation" },
  { label: "Commercial / Distributor", subject: "Commercial & Seed Distribution Enquiry" },
  { label: "Investor Relations", subject: "Investor Relations & Shareholder Inquiry" },
  { label: "General Support", subject: "General Enquiry" },
];

const OFFICES = [
  { region: "Group head office", city: "Harare, Zimbabwe", phone: "+263 242 707 700", email: "info@seedcogroup.com" },
  { region: "Zambia", city: "Lusaka", phone: "+260 211 213 000", email: "zambia@seedcogroup.com" },
  { region: "Kenya (East Africa)", city: "Nairobi", phone: "+254 20 300 4000", email: "kenya@seedcogroup.com" },
  { region: "Nigeria (West Africa)", city: "Abuja", phone: "+234 9 291 5000", email: "nigeria@seedcogroup.com" },
  { region: "Malawi", city: "Lilongwe", phone: "+265 1 750 300", email: "malawi@seedcogroup.com" },
  { region: "Botswana", city: "Gaborone", phone: "+267 390 0500", email: "botswana@seedcogroup.com" },
];

function ContactPage() {
  const [form, setForm] = useState({ name: "", email: "", country: "", subject: "", message: "" });
  const [activeTopic, setActiveTopic] = useState<string | null>(null);
  const [errors, setErrors] = useState<Errors>({});
  const [sent, setSent] = useState(false);

  const set = (key: keyof typeof form, value: string) => {
    setForm((f) => ({ ...f, [key]: value }));
    setErrors((e) => {
      const next = { ...e };
      delete next[key];
      return next;
    });
    setSent(false);
  };

  const handleTopicSelect = (topic: (typeof ENQUIRY_TOPICS)[number]) => {
    setActiveTopic(topic.label);
    setForm((f) => ({ ...f, subject: topic.subject }));
    setErrors((e) => {
      const next = { ...e };
      delete next.subject;
      return next;
    });
  };

  const onSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const result = schema.safeParse(form);
    if (!result.success) {
      const next: Errors = {};
      result.error.issues.forEach((issue) => {
        const key = issue.path[0] as keyof Errors;
        if (!next[key]) next[key] = issue.message;
      });
      setErrors(next);
      setSent(false);
      return;
    }
    setErrors({});
    setSent(true);
  };

  const handleReset = () => {
    setForm({ name: "", email: "", country: "", subject: "", message: "" });
    setActiveTopic(null);
    setSent(false);
    setErrors({});
  };

  const errorId = (k: string) => `${k}-error`;

  return (
    <>
      <PageHeader
        crumbs={[{ label: "Contact Us" }]}
        eyebrow="Contact"
        title="Talk to us"
        lead="Whether you need variety advice for your field, distributor information or investor material, our teams across Africa are ready to help."
      />

      <Section>
        <div className="grid gap-10 items-start lg:grid-cols-[1.25fr_1fr]">
          {/* Main Enquiry Form Card (compact height) */}
          <div className="relative isolate overflow-hidden rounded-3xl border border-black/[0.08] bg-card p-6 sm:p-7 shadow-card dark:border-white/[0.08] h-fit">
            {/* Ambient subtle glow at top of card */}
            <div
              aria-hidden="true"
              className="pointer-events-none absolute -top-16 -right-16 -z-10 h-48 w-48 rounded-full bg-[#009F4F]/10 blur-3xl"
            />

            <div className="border-b border-border pb-3">
              <h2 className="font-display text-2xl font-bold tracking-tight md:text-3xl">
                Send us a message
              </h2>
            </div>

            {sent ? (
              /* Success State */
              <div className="mt-8 rounded-2xl border border-[#009F4F]/30 bg-[#009F4F]/10 p-8 text-center sm:p-10">
                <div className="mx-auto flex size-14 items-center justify-center rounded-full bg-[#009F4F] text-white shadow-md">
                  <CheckCircle2 className="size-7" />
                </div>
                <h3 className="mt-4 text-xl font-bold text-foreground">
                  Enquiry Received
                </h3>
                <p className="mx-auto mt-2 max-w-md text-sm leading-relaxed text-muted-foreground">
                  Thank you for reaching out. Your enquiry has been routed to our regional agronomist and client services
                  team. We will be in touch shortly.
                </p>
                <div className="mt-6 flex justify-center">
                  <Button type="button" variant="outline" onClick={handleReset}>
                    Send another message
                  </Button>
                </div>
              </div>
            ) : (
              /* Interactive Form */
              <form onSubmit={onSubmit} noValidate className="mt-5 space-y-4">
                {/* Topic quick-select pills */}
                <div>
                  <label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                    What can we help you with?
                  </label>
                  <div className="mt-2 flex flex-wrap gap-1.5">
                    {ENQUIRY_TOPICS.map((t) => {
                      const isSelected = activeTopic === t.label;
                      return (
                        <button
                          key={t.label}
                          type="button"
                          onClick={() => handleTopicSelect(t)}
                          className={`rounded-full px-3 py-1 text-xs font-medium transition-all ${
                            isSelected
                              ? "bg-[#009F4F] text-white shadow-xs"
                              : "border border-border bg-background text-foreground/85 hover:border-[#009F4F]/50 hover:bg-[#009F4F]/5"
                          }`}
                        >
                          {t.label}
                        </button>
                      );
                    })}
                  </div>
                </div>

                <div className="grid gap-4 sm:grid-cols-2">
                  <div>
                    <Label htmlFor="name" className="flex items-center gap-1.5 text-xs font-semibold">
                      <User className="size-3.5 text-muted-foreground" /> Full name
                    </Label>
                    <Input
                      id="name"
                      placeholder="e.g. Tendai Moyo"
                      value={form.name}
                      onChange={(e) => set("name", e.target.value)}
                      aria-invalid={Boolean(errors.name)}
                      aria-describedby={errors.name ? errorId("name") : undefined}
                      className="mt-1 bg-background focus-visible:ring-[#009F4F]"
                      autoComplete="name"
                    />
                    {errors.name && (
                      <p id={errorId("name")} className="mt-1 text-xs text-destructive">
                        {errors.name}
                      </p>
                    )}
                  </div>

                  <div>
                    <Label htmlFor="email" className="flex items-center gap-1.5 text-xs font-semibold">
                      <Mail className="size-3.5 text-muted-foreground" /> Email address
                    </Label>
                    <Input
                      id="email"
                      type="email"
                      placeholder="tendai@farm.co.zw"
                      value={form.email}
                      onChange={(e) => set("email", e.target.value)}
                      aria-invalid={Boolean(errors.email)}
                      aria-describedby={errors.email ? errorId("email") : undefined}
                      className="mt-1 bg-background focus-visible:ring-[#009F4F]"
                      autoComplete="email"
                    />
                    {errors.email && (
                      <p id={errorId("email")} className="mt-1 text-xs text-destructive">
                        {errors.email}
                      </p>
                    )}
                  </div>
                </div>

                <div className="grid gap-4 sm:grid-cols-2">
                  <div>
                    <Label htmlFor="country" className="flex items-center gap-1.5 text-xs font-semibold">
                      <Globe2 className="size-3.5 text-muted-foreground" /> Country / Region
                    </Label>
                    <Select value={form.country} onValueChange={(v) => set("country", v)}>
                      <SelectTrigger
                        id="country"
                        className="mt-1 bg-background focus:ring-[#009F4F]"
                        aria-invalid={Boolean(errors.country)}
                        aria-describedby={errors.country ? errorId("country") : undefined}
                      >
                        <SelectValue placeholder="Select your country" />
                      </SelectTrigger>
                      <SelectContent>
                        {COUNTRIES.map((c) => (
                          <SelectItem key={c.name} value={c.name}>
                            {c.name}
                          </SelectItem>
                        ))}
                        <SelectItem value="Other">Other</SelectItem>
                      </SelectContent>
                    </Select>
                    {errors.country && (
                      <p id={errorId("country")} className="mt-1 text-xs text-destructive">
                        {errors.country}
                      </p>
                    )}
                  </div>

                  <div>
                    <Label htmlFor="subject" className="flex items-center gap-1.5 text-xs font-semibold">
                      <Tag className="size-3.5 text-muted-foreground" /> Subject
                    </Label>
                    <Input
                      id="subject"
                      placeholder="Brief topic summary"
                      value={form.subject}
                      onChange={(e) => set("subject", e.target.value)}
                      aria-invalid={Boolean(errors.subject)}
                      aria-describedby={errors.subject ? errorId("subject") : undefined}
                      className="mt-1 bg-background focus-visible:ring-[#009F4F]"
                    />
                    {errors.subject && (
                      <p id={errorId("subject")} className="mt-1 text-xs text-destructive">
                        {errors.subject}
                      </p>
                    )}
                  </div>
                </div>

                <div>
                  <Label htmlFor="message" className="flex items-center gap-1.5 text-xs font-semibold">
                    <MessageSquare className="size-3.5 text-muted-foreground" /> Message
                  </Label>
                  <Textarea
                    id="message"
                    rows={3}
                    placeholder="Tell us about your crop plans, farm location, or any specific questions..."
                    value={form.message}
                    onChange={(e) => set("message", e.target.value)}
                    aria-invalid={Boolean(errors.message)}
                    aria-describedby={errors.message ? errorId("message") : undefined}
                    className="mt-1 bg-background focus-visible:ring-[#009F4F]"
                  />
                  {errors.message && (
                    <p id={errorId("message")} className="mt-1.5 text-xs text-destructive">
                      {errors.message}
                    </p>
                  )}
                </div>

                {/* Submit action */}
                <div className="flex justify-end border-t border-border pt-4">
                  <Button type="submit" variant="harvest" size="lg" className="w-full sm:w-auto font-semibold gap-2">
                    <span>Send enquiry</span>
                    <Send className="size-4" />
                  </Button>
                </div>
              </form>
            )}
          </div>

          {/* Regional Contacts Column */}
          <div>
            <SectionHeading eyebrow="Offices" title="Regional contacts" />
            <ul className="mt-8 space-y-4">
              {OFFICES.map((o) => (
                <li
                  key={o.region}
                  className="group rounded-2xl border border-border bg-card p-5 shadow-card transition-all hover:border-[#009F4F]/40 hover:shadow-md"
                >
                  <p className="eyebrow text-[#FF1B2A] font-bold">{o.region}</p>
                  <p className="mt-2 flex items-center gap-2 text-sm font-semibold text-foreground">
                    <MapPin aria-hidden="true" className="size-4 text-[#009F4F]" /> {o.city}
                  </p>
                  <p className="mt-1.5 flex items-center gap-2 text-sm text-muted-foreground">
                    <Phone aria-hidden="true" className="size-4 group-hover:text-[#009F4F] transition-colors" />
                    <a href={`tel:${o.phone.replace(/\s/g, "")}`} className="hover:text-foreground hover:underline">
                      {o.phone}
                    </a>
                  </p>
                  <p className="mt-1.5 flex items-center gap-2 text-sm text-muted-foreground">
                    <Mail aria-hidden="true" className="size-4 group-hover:text-[#009F4F] transition-colors" />
                    <a href={`mailto:${o.email}`} className="hover:text-foreground hover:underline">
                      {o.email}
                    </a>
                  </p>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </Section>
    </>
  );
}
