import { createFileRoute, Link } from "@tanstack/react-router";
import { useMutation } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { Check, CreditCard, Mail, Smartphone, Users } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";

import { PageHeader, PageShell, Reveal } from "@/components/page-shell";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { useAuth } from "@/hooks/useAuth";
import { requestUpgrade } from "@/lib/plan.functions";
import {
  MEMBERSHIP_CATEGORIES,
  PAYMENT_METHODS,
  PLANS,
  SUPPORT_EMAIL,
  formatKesAmount,
  type PlanOption,
} from "@/lib/plans";

export const Route = createFileRoute("/pricing")({
  head: () => ({
    meta: [
      { title: "Pricing — Free, Pro and Team plans | UZIA Academy" },
      {
        name: "description",
        content:
          "UZIA Academy pricing for marketplace founders, incubators and accelerators, and development partners. Pay with M-Pesa, Airtel Money, PayPal or card.",
      },
      { property: "og:title", content: "UZIA Academy pricing" },
      {
        property: "og:description",
        content:
          "Sponsored assessment access, monthly Pro from KSh 1,500, and team plans for up to 15 learners.",
      },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: PricingPage,
});

function PricingPage() {
  const { user } = useAuth();
  const submit = useServerFn(requestUpgrade);
  const [selected, setSelected] = useState<PlanOption | null>(null);
  const [method, setMethod] = useState(PAYMENT_METHODS[0]!.id);
  const [form, setForm] = useState({
    payment_reference: "",
    contact_email: "",
    contact_phone: "",
    notes: "",
  });

  const activeMethod = PAYMENT_METHODS.find((m) => m.id === method) ?? PAYMENT_METHODS[0]!;

  const mutation = useMutation({
    mutationFn: () =>
      submit({
        data: {
          plan: selected?.id ?? "",
          membership_category: selected?.category ?? "marketplace",
          amount_kes: selected?.priceKes ?? 0,
          payment_method: method,
          ...form,
        },
      }),
    onSuccess: () => {
      toast.success("Payment reference received. UZIA Support will activate your plan shortly.");
      setForm({ payment_reference: "", contact_email: "", contact_phone: "", notes: "" });
      setSelected(null);
    },
    onError: (e) => toast.error(e instanceof Error ? e.message : "Could not submit request"),
  });

  return (
    <PageShell>
      <PageHeader
        eyebrow="Plans and pricing"
        title="Choose the plan that fits your journey"
        description="Every plan includes your score across the 12 UZIA Academy Pillars and the fully sponsored Foundation courses. Monthly Pro unlocks your action plan and the rest of the 50-course catalogue."
      />

      <section className="mx-auto w-full max-w-6xl px-4 py-14">
        <div className="space-y-16">
          {MEMBERSHIP_CATEGORIES.map((membership) => {
            const plans = PLANS.filter((plan) => plan.category === membership.value);
            return (
              <section key={membership.value} className="border-b border-border pb-16 last:border-0 last:pb-0">
                <p className="text-xs font-semibold uppercase tracking-[0.22em] text-terracotta">
                  {membership.value === "marketplace" ? "For founders and SMEs" : membership.value === "incubator" ? "For enterprise support organisations" : "For programme partners"}
                </p>
                <h2 className="mt-2 text-2xl sm:text-3xl">{membership.label}</h2>
                <p className="mt-3 max-w-2xl text-sm text-muted-foreground">{membership.blurb}</p>
                <div className="mt-8 grid gap-6 md:grid-cols-2 lg:grid-cols-3">
                  {plans.map((plan, i) => (
                    <Reveal key={plan.id} delay={(i % 3) * 0.06}>
                      <Card className="card-hover flex h-full flex-col overflow-hidden border-border/70">
                        <div className="h-1.5 bg-ember" aria-hidden />
                        <CardHeader className="gap-3">
                          <div className="flex items-center gap-2">
                            <Badge className="bg-secondary text-secondary-foreground">{plan.name}</Badge>
                            {plan.seats > 1 ? <Badge variant="outline" className="border-primary/40 text-primary"><Users className="mr-1 size-3" /> {plan.seats} seats</Badge> : null}
                          </div>
                          <CardTitle className="font-display text-3xl">
                            {plan.contactOnly ? "Let's talk" : plan.priceKes === 0 ? "Fully sponsored" : formatKesAmount(plan.priceKes)}
                            <span className="ml-2 align-middle text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">{plan.cadence}</span>
                          </CardTitle>
                          <p className="text-sm text-muted-foreground">{plan.headline}</p>
                        </CardHeader>
                        <CardContent className="mt-auto flex flex-col gap-5">
                          <ul className="space-y-2.5">{plan.features.map((feature) => <li key={feature} className="flex gap-2.5 text-sm text-muted-foreground"><Check className="mt-0.5 size-4 shrink-0 text-primary" />{feature}</li>)}</ul>
                          {plan.contactOnly ? (
                            <Button asChild className="rounded-full"><a href={`mailto:${SUPPORT_EMAIL}?subject=UZIA%20Academy%20partnership`}><Mail className="mr-2 size-4" /> Contact UZIA Support</a></Button>
                          ) : plan.priceKes === 0 ? (
                            <Button asChild variant="outline" className="rounded-full"><Link to="/assessment">Start your assessment</Link></Button>
                          ) : (
                            <Button className="rounded-full" onClick={() => setSelected(plan)}>Choose {plan.name}</Button>
                          )}
                        </CardContent>
                      </Card>
                    </Reveal>
                  ))}
                </div>
              </section>
            );
          })}
        </div>
      </section>

      <section className="border-t border-border bg-surface">
        <div className="mx-auto w-full max-w-6xl px-4 py-14">
          <h2 className="text-2xl">Ways to pay</h2>
          <p className="mt-3 max-w-2xl text-sm text-muted-foreground">
            Pay with M-Pesa, Airtel Money, PayPal or Visa / Mastercard, then send us the payment
            reference. Our team activates your plan and you will see it on your dashboard.
          </p>
          <div className="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            {PAYMENT_METHODS.map((m) => (
              <div key={m.id} className="rounded-2xl border border-border bg-card p-5">
                {m.id === "card" ? (
                  <CreditCard className="size-5 text-primary" />
                ) : (
                  <Smartphone className="size-5 text-primary" />
                )}
                <p className="mt-3 font-semibold">{m.label}</p>
                <p className="mt-1.5 text-xs text-muted-foreground">{m.instructions}</p>
              </div>
            ))}
          </div>

          {selected ? (
            <div className="mt-10 max-w-2xl rounded-3xl border border-border bg-card p-6 sm:p-8">
              <h3 className="text-xl">
                Activate {selected.name} · {formatKesAmount(selected.priceKes)} per month
              </h3>
              {user ? (
                <form
                  className="mt-5 space-y-5"
                  onSubmit={(e) => {
                    e.preventDefault();
                    mutation.mutate();
                  }}
                >
                  <div className="space-y-2">
                    <Label>Payment method</Label>
                    <Select value={method} onValueChange={setMethod}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {PAYMENT_METHODS.map((m) => (
                          <SelectItem key={m.id} value={m.id}>
                            {m.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-muted-foreground">{activeMethod.instructions}</p>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="ref">Payment reference</Label>
                    <Input
                      id="ref"
                      required
                      maxLength={120}
                      placeholder="e.g. QGR4TX9KLM"
                      value={form.payment_reference}
                      onChange={(e) => setForm({ ...form, payment_reference: e.target.value })}
                    />
                  </div>
                  <div className="grid gap-5 sm:grid-cols-2">
                    <div className="space-y-2">
                      <Label htmlFor="pemail">Contact email</Label>
                      <Input
                        id="pemail"
                        type="email"
                        maxLength={255}
                        value={form.contact_email}
                        onChange={(e) => setForm({ ...form, contact_email: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="pphone">Phone</Label>
                      <Input
                        id="pphone"
                        maxLength={40}
                        placeholder="07xx xxx xxx"
                        value={form.contact_phone}
                        onChange={(e) => setForm({ ...form, contact_phone: e.target.value })}
                      />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="pnotes">Anything we should know?</Label>
                    <Textarea
                      id="pnotes"
                      maxLength={1000}
                      value={form.notes}
                      onChange={(e) => setForm({ ...form, notes: e.target.value })}
                    />
                  </div>
                  <div className="flex gap-3">
                    <Button type="submit" className="rounded-full" disabled={mutation.isPending}>
                      {mutation.isPending ? "Sending…" : "Submit payment reference"}
                    </Button>
                    <Button
                      type="button"
                      variant="ghost"
                      className="rounded-full"
                      onClick={() => setSelected(null)}
                    >
                      Cancel
                    </Button>
                  </div>
                </form>
              ) : (
                <div className="mt-5">
                  <p className="text-sm text-muted-foreground">
                    Sign in first so we can attach the payment to your account.
                  </p>
                  <Button asChild className="mt-4 rounded-full">
                    <Link to="/auth" search={{ redirect: "/pricing" }}>Sign in to continue</Link>
                  </Button>
                </div>
              )}
            </div>
          ) : null}
        </div>
        <div className="motif-divider" />
      </section>
    </PageShell>
  );
}
