import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { SiteLayout } from "@/components/site/SiteLayout";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Gift, Sparkles, Tag, Copy } from "lucide-react";
import { toast } from "sonner";

export const Route = createFileRoute("/offers")({
  head: () => ({
    meta: [
      { title: "Offers & Rewards — Flexflares Cyber Services" },
      { name: "description", content: "Promo codes, seasonal deals, referral rewards, loyalty points and a first-time customer discount." },
      { property: "og:title", content: "Offers & Rewards — Flexflares" },
      { property: "og:description", content: "Save more on cyber services with promos, referrals and loyalty rewards." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: OffersPage,
});

type Offer = { id: string; title: string; description: string; badge: string | null; promo_code: string | null; cta_label: string | null; cta_url: string | null; ends_at: string | null };
type Code = { code: string; kind: "percent" | "fixed"; value: number; description: string | null; expires_at: string | null };

function OffersPage() {
  const [offers, setOffers] = useState<Offer[]>([]);
  const [codes, setCodes] = useState<Code[]>([]);

  useEffect(() => {
    supabase.from("offers").select("id, title, description, badge, promo_code, cta_label, cta_url, ends_at").order("sort_order").then(({ data }) => {
      setOffers((data ?? []) as Offer[]);
    });
    supabase.from("promo_codes").select("code, kind, value, description, expires_at").then(({ data }) => {
      setCodes((data ?? []) as Code[]);
    });
  }, []);

  const copy = (code: string) => {
    navigator.clipboard.writeText(code);
    toast.success(`Copied ${code}`);
  };

  return (
    <SiteLayout>
      <section className="mx-auto max-w-6xl px-4 pt-12 pb-16 sm:px-6">
        <div className="text-center">
          <Badge variant="secondary" className="mb-3"><Sparkles className="mr-1 h-3 w-3" /> Rewards programme</Badge>
          <h1 className="text-3xl font-bold sm:text-4xl">Offers &amp; rewards</h1>
          <p className="mx-auto mt-2 max-w-2xl text-sm text-muted-foreground">Save on every service with promo codes, referral bonuses, loyalty points and a first-time customer discount.</p>
        </div>

        <div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          <RewardCard icon={<Gift className="h-5 w-5" />} title="First-time customer" body="Automatic 10% off your first paid service — applied at checkout." />
          <RewardCard icon={<Sparkles className="h-5 w-5" />} title="Referral rewards" body="Share your referral link. You earn KSh 100 when your friend makes their first payment, and they start with 100 points." cta={<Link className="text-primary hover:underline" to="/dashboard">Get your link</Link>} />
          <RewardCard icon={<Tag className="h-5 w-5" />} title="Loyalty points" body="Earn 5% back as points on every paid service. 1 point = KSh 1 off future services." />
        </div>

        {offers.length > 0 && (
          <div className="mt-10">
            <h2 className="text-xl font-semibold">Seasonal offers</h2>
            <div className="mt-4 grid gap-4 md:grid-cols-2">
              {offers.map((o) => (
                <Card key={o.id} className="glass overflow-hidden">
                  <CardContent className="p-5">
                    <div className="flex items-start justify-between gap-2">
                      <div>
                        {o.badge && <Badge className="mb-2" variant="secondary">{o.badge}</Badge>}
                        <h3 className="text-lg font-semibold">{o.title}</h3>
                      </div>
                      {o.ends_at && <span className="text-xs text-muted-foreground">Ends {new Date(o.ends_at).toLocaleDateString()}</span>}
                    </div>
                    <p className="mt-2 text-sm text-muted-foreground">{o.description}</p>
                    {o.promo_code && (
                      <button onClick={() => copy(o.promo_code!)} className="mt-3 inline-flex items-center gap-2 rounded-md border border-dashed px-3 py-1.5 text-sm font-mono hover:bg-muted">
                        {o.promo_code} <Copy className="h-3 w-3" />
                      </button>
                    )}
                    {o.cta_url && (
                      <div className="mt-3">
                        <Button asChild size="sm" variant="outline"><a href={o.cta_url}>{o.cta_label || "Learn more"}</a></Button>
                      </div>
                    )}
                  </CardContent>
                </Card>
              ))}
            </div>
          </div>
        )}

        {codes.length > 0 && (
          <div className="mt-10">
            <h2 className="text-xl font-semibold">Active promo codes</h2>
            <div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {codes.map((c) => (
                <button key={c.code} onClick={() => copy(c.code)} className="glass rounded-xl border p-4 text-left transition hover:-translate-y-0.5 hover:shadow-glow">
                  <div className="flex items-center justify-between">
                    <span className="font-mono text-base font-semibold">{c.code}</span>
                    <Badge variant="outline">{c.kind === "percent" ? `${c.value}% off` : `KSh ${c.value} off`}</Badge>
                  </div>
                  {c.description && <p className="mt-2 text-xs text-muted-foreground">{c.description}</p>}
                  {c.expires_at && <p className="mt-2 text-[10px] uppercase tracking-wide text-muted-foreground">Expires {new Date(c.expires_at).toLocaleDateString()}</p>}
                </button>
              ))}
            </div>
          </div>
        )}
      </section>
    </SiteLayout>
  );
}

function RewardCard({ icon, title, body, cta }: { icon: React.ReactNode; title: string; body: string; cta?: React.ReactNode }) {
  return (
    <Card className="glass h-full">
      <CardContent className="p-5">
        <div className="grid h-10 w-10 place-items-center rounded-xl bg-primary/10 text-primary">{icon}</div>
        <h3 className="mt-3 text-base font-semibold">{title}</h3>
        <p className="mt-1 text-sm text-muted-foreground">{body}</p>
        {cta && <div className="mt-3 text-sm">{cta}</div>}
      </CardContent>
    </Card>
  );
}