import { createFileRoute, Link } from "@tanstack/react-router";
import { useState, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Slider } from "@/components/ui/slider";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { PublicFooter } from "@/components/public-footer";
import { PublicSiteHeader } from "@/components/public-site-header";
import {
  Calculator,
  ArrowRight,
  Check,
  TrendingDown,
  PiggyBank,
  Send,
  BarChart3,
} from "lucide-react";

const TIERS = [
  { qty: 1000, price: 35000, label: "1,000 SMS" },
  { qty: 5000, price: 125000, label: "5,000 SMS", popular: true },
  { qty: 10000, price: 220000, label: "10,000 SMS" },
  { qty: 25000, price: 500000, label: "25,000 SMS" },
  { qty: 50000, price: 900000, label: "50,000 SMS" },
  { qty: 100000, price: 1600000, label: "100,000 SMS" },
];

const BASE_RATE = 35; // UGX per SMS at lowest tier (1,000)

function formatUGX(n: number) {
  return new Intl.NumberFormat("en-UG", {
    style: "currency",
    currency: "UGX",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(n);
}

export const Route = createFileRoute("/sms-calculator")({
  head: () => ({
    meta: [
      { title: "Bulk SMS Cost Calculator Uganda — UGX Pricing | Gatavase Bulky SMS" },
      {
        name: "description",
        content:
          "Calculate your bulk SMS cost in Uganda Shillings (UGX). Estimate pricing for 1,000 to 100,000 SMS messages. UGX 125,000 for 5,000 SMS. Compare volume tiers and save with Gatavase Bulky SMS.",
      },
      {
        property: "og:title",
        content: "Bulk SMS Cost Calculator Uganda — UGX Pricing | Gatavase Bulky SMS",
      },
      {
        property: "og:description",
        content:
          "Calculate your bulk SMS cost in Uganda Shillings. Estimate pricing for 1,000 to 100,000 SMS. UGX 125,000 for 5,000 SMS.",
      },
      { name: "twitter:card", content: "summary" },
      { property: "og:url", content: "https://sms.gatavaseug.com/sms-calculator" },
      { property: "og:type", content: "website" },
    ],
    links: [
      { rel: "canonical", href: "https://sms.gatavaseug.com/sms-calculator" },
    ],
  }),
  component: SmsCalculatorPage,
});

function SmsCalculatorPage() {
  const [quantity, setQuantity] = useState<number>(5000);

  const computed = useMemo(() => {
    // Linear interpolation between tiers for custom quantities
    let rate = BASE_RATE;
    let tierPrice = quantity * BASE_RATE;

    for (let i = 0; i < TIERS.length; i++) {
      if (quantity >= TIERS[i].qty) {
        rate = TIERS[i].price / TIERS[i].qty;
        tierPrice = TIERS[i].price;
      }
    }

    // If between tiers, interpolate price
    let matchedTier = TIERS[0];
    for (const t of TIERS) {
      if (quantity >= t.qty) matchedTier = t;
    }

    const unitPrice = matchedTier.price / matchedTier.qty;
    const totalPrice = Math.round(quantity * unitPrice);
    const savingsVsBase = quantity * BASE_RATE - totalPrice;
    const savingsPercent = ((savingsVsBase / (quantity * BASE_RATE)) * 100).toFixed(0);

    return {
      unitPrice,
      totalPrice,
      savingsVsBase,
      savingsPercent,
      matchedTier,
    };
  }, [quantity]);

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

      <main className="container mx-auto max-w-5xl px-4 pt-12 pb-24">
        {/* Hero */}
        <div className="text-center">
          <div className="mx-auto mb-4 inline-flex items-center gap-2 rounded-full border border-border bg-card px-4 py-1.5 text-xs font-medium text-muted-foreground shadow-sm">
            <Calculator className="h-3.5 w-3.5" />
            Free tool — no signup required
          </div>
          <h1 className="font-display text-4xl font-bold tracking-tight md:text-6xl">
            Bulk SMS <span className="text-gradient-brand">Cost Calculator</span>
          </h1>
          <p className="mx-auto mt-4 max-w-xl text-lg text-muted-foreground">
            Estimate your SMS campaign cost in Uganda Shillings. Compare volume tiers and see how much you save at scale.
          </p>
        </div>

        {/* Calculator Card */}
        <Card className="mx-auto mt-10 max-w-3xl border-border shadow-card">
          <CardContent className="p-6 md:p-10">
            <div className="flex flex-col gap-8 md:flex-row md:items-center md:justify-between">
              {/* Input */}
              <div className="flex-1 space-y-6">
                <div>
                  <Label htmlFor="sms-qty" className="text-sm font-medium">
                    Number of SMS messages
                  </Label>
                  <div className="mt-2 flex items-center gap-3">
                    <Input
                      id="sms-qty"
                      type="number"
                      min={100}
                      max={200000}
                      value={quantity}
                      onChange={(e) => {
                        const val = parseInt(e.target.value || "0", 10);
                        setQuantity(Math.min(200000, Math.max(100, val)));
                      }}
                      className="h-12 text-lg font-semibold"
                    />
                    <span className="whitespace-nowrap text-sm text-muted-foreground">SMS</span>
                  </div>
                </div>
                <div>
                  <Slider
                    value={[quantity]}
                    min={100}
                    max={100000}
                    step={100}
                    onValueChange={(v) => setQuantity(v[0])}
                  />
                  <div className="mt-2 flex justify-between text-xs text-muted-foreground">
                    <span>100</span>
                    <span>25k</span>
                    <span>50k</span>
                    <span>75k</span>
                    <span>100k</span>
                  </div>
                </div>
              </div>

              {/* Result */}
              <div className="flex flex-col items-start gap-3 md:items-end md:text-right">
                <div className="text-sm text-muted-foreground">Estimated cost</div>
                <div className="font-display text-4xl font-bold text-primary md:text-5xl">
                  {formatUGX(computed.totalPrice)}
                </div>
                <div className="text-sm text-muted-foreground">
                  {formatUGX(Math.round(computed.unitPrice))} per SMS
                </div>
                {computed.savingsVsBase > 0 && (
                  <div className="inline-flex items-center gap-1.5 rounded-full bg-success/10 px-3 py-1 text-xs font-medium text-success">
                    <PiggyBank className="h-3.5 w-3.5" />
                    Save {formatUGX(computed.savingsVsBase)} ({computed.savingsPercent}%)
                  </div>
                )}
              </div>
            </div>

            {/* CTA */}
            <div className="mt-8 flex flex-col items-center justify-center gap-3 border-t border-border pt-8 md:flex-row">
              <Link to="/auth" className="w-full md:w-auto">
                <Button size="lg" className="w-full bg-gradient-brand text-primary-foreground shadow-glow hover:opacity-95">
                  Start sending <ArrowRight className="ml-2 h-4 w-4" />
                </Button>
              </Link>
              <span className="text-xs text-muted-foreground">
                No credit card required. 50 free SMS on signup.
              </span>
            </div>
          </CardContent>
        </Card>

        {/* Volume Tier Comparison */}
        <div className="mt-16">
          <h2 className="font-display text-center text-2xl font-bold md:text-3xl">
            Volume tier pricing
          </h2>
          <p className="mx-auto mt-2 max-w-lg text-center text-sm text-muted-foreground">
            The more you send, the less you pay per SMS. All tiers include delivery reports, sender ID, and analytics.
          </p>

          <div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {TIERS.map((tier) => {
              const unit = tier.price / tier.qty;
              const isActive = quantity >= tier.qty && (TIERS.indexOf(tier) === TIERS.length - 1 || quantity < TIERS[TIERS.indexOf(tier) + 1].qty);
              return (
                <Card
                  key={tier.qty}
                  className={`relative transition hover:-translate-y-0.5 ${
                    isActive
                      ? "border-primary shadow-glow"
                      : tier.popular
                      ? "border-primary/60 shadow-card"
                      : "border-border shadow-card"
                  }`}
                >
                  {tier.popular && (
                    <div className="absolute -top-3 left-4 rounded-full bg-gradient-warm px-3 py-1 text-xs font-semibold text-accent-foreground">
                      Most popular
                    </div>
                  )}
                  {isActive && !tier.popular && (
                    <div className="absolute -top-3 left-4 rounded-full bg-primary px-3 py-1 text-xs font-semibold text-primary-foreground">
                      Your tier
                    </div>
                  )}
                  <CardContent className="p-5">
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium text-muted-foreground">{tier.label}</span>
                      <span className="font-display text-2xl font-bold">{formatUGX(tier.price)}</span>
                    </div>
                    <div className="mt-2 flex items-center gap-2 text-sm text-muted-foreground">
                      <TrendingDown className="h-4 w-4 text-success" />
                      <span>{formatUGX(Math.round(unit))} per SMS</span>
                    </div>
                    {tier.popular && (
                      <div className="mt-3 rounded-lg bg-muted p-3 text-xs text-muted-foreground">
                        <div className="flex items-center gap-1.5">
                          <Check className="h-3.5 w-3.5 text-success" />
                          Best value for small businesses
                        </div>
                      </div>
                    )}
                  </CardContent>
                </Card>
              );
            })}
          </div>
        </div>

        {/* What is included */}
        <div className="mt-16 grid gap-8 md:grid-cols-3">
          {[
            {
              icon: Send,
              title: "Instant delivery",
              desc: "Messages reach MTN, Airtel & Africell in under 3 seconds.",
            },
            {
              icon: BarChart3,
              title: "Real-time reports",
              desc: "Track every message: sent, delivered, failed, with reasons.",
            },
            {
              icon: PiggyBank,
              title: "No hidden fees",
              desc: "What you see is what you pay. No setup costs or monthly minimums.",
            },
          ].map((item) => (
            <div key={item.title} className="rounded-2xl border border-border bg-card p-6 shadow-card">
              <div className="grid h-10 w-10 place-items-center rounded-xl bg-gradient-brand text-primary-foreground">
                <item.icon className="h-5 w-5" />
              </div>
              <h3 className="mt-4 font-display text-lg font-semibold">{item.title}</h3>
              <p className="mt-1 text-sm text-muted-foreground">{item.desc}</p>
            </div>
          ))}
        </div>

        {/* FAQ */}
        <div className="mx-auto mt-16 max-w-2xl">
          <h2 className="font-display text-center text-2xl font-bold md:text-3xl">
            Frequently asked questions
          </h2>
          <div className="mt-8 space-y-4">
            {[
              {
                q: "How is the SMS cost calculated?",
                a: "We use volume-tiered pricing. The more SMS you send, the lower your per-SMS rate. Enter any quantity above to see your exact cost.",
              },
              {
                q: "What payment methods are accepted?",
                a: "We accept Mobile Money (MTN MoMo, Airtel Money), bank transfer, and card payments. All transactions are in Uganda Shillings (UGX).",
              },
              {
                q: "Do unused SMS roll over?",
                a: "Yes, unused SMS from monthly bundles roll over for 30 days. Pay-as-you-go credits never expire.",
              },
              {
                q: "Is there a minimum order?",
                a: "No minimum. You can purchase as few as 100 SMS. However, our 5,000 SMS plan at UGX 125,000 offers the best value for most businesses.",
              },
              {
                q: "Can I send SMS to networks outside Uganda?",
                a: "Yes. We cover 12+ African countries including Kenya, Tanzania, Rwanda, Nigeria, and Ghana. International rates vary by destination.",
              },
            ].map((faq) => (
              <div key={faq.q} className="rounded-xl border border-border bg-card p-5 shadow-card">
                <h3 className="font-semibold text-sm">{faq.q}</h3>
                <p className="mt-1 text-sm text-muted-foreground">{faq.a}</p>
              </div>
            ))}
          </div>
        </div>

        {/* Bottom CTA */}
        <div className="mt-16 text-center">
          <div className="overflow-hidden rounded-3xl bg-gradient-hero p-10 text-center text-primary-foreground shadow-glow md:p-14">
            <h2 className="font-display text-3xl font-bold md:text-4xl">
              Ready to send your first campaign?
            </h2>
            <p className="mx-auto mt-3 max-w-lg text-primary-foreground/90">
              Get 50 free SMS when you sign up. No credit card required. Send to MTN, Airtel & Africell instantly.
            </p>
            <Link to="/auth" className="mt-8 inline-block">
              <Button size="lg" variant="secondary" className="font-semibold">
                Create your free account <ArrowRight className="ml-2 h-4 w-4" />
              </Button>
            </Link>
          </div>
        </div>
      </main>

      <PublicFooter />
    </div>
  );
}
