import { createFileRoute } from "@tanstack/react-router";
import { useMutation } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { useState } from "react";
import { toast } from "sonner";
import { Send, BellRing } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { adminBroadcastPush } from "@/lib/push.functions";
import { adminUpsertBanner } from "@/lib/banners.functions";

export const Route = createFileRoute("/admin/push")({
  head: () => ({
    meta: [
      { title: "Push Notifications — Billsline Admin" },
      { name: "description", content: "Send Billsline push notifications and announcements to installed app users." },
    ],
  }),
  component: PushCenter,
});

function PushCenter() {
  const send = useServerFn(adminBroadcastPush);
  const saveBanner = useServerFn(adminUpsertBanner);
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");
  const [url, setUrl] = useState("/app");
  const [userId, setUserId] = useState("");
  const [asBanner, setAsBanner] = useState(false);

  const mut = useMutation({
    mutationFn: async () => {
      const res = await send({ data: { title, body, url: url || "/app", ...(userId ? { userId } : {}) } });
      if (asBanner && !userId) {
        await saveBanner({
          data: {
            title,
            subtitle: body.slice(0, 200),
            cta_label: "Learn more",
            variant: "gradient" as const,
            audience: "all" as const,
            is_active: true,
            sort_order: 0,
            placement: ["home"],
          },
        });
      }
      return res;
    },
    onSuccess: (r) => {
      toast.success(
        `In-app message delivered to ${r.recipients} user(s) · push sent to ${r.sent} device(s)` +
          (asBanner && !userId ? " · banner published" : ""),
      );
      setTitle("");
      setBody("");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  return (
    <div className="max-w-2xl space-y-4">
      <div className="flex items-center gap-2">
        <BellRing className="h-5 w-5 text-primary" />
        <h2 className="text-lg font-bold">Notification & message center</h2>
      </div>
      <p className="text-sm text-muted-foreground">
        Every customer receives this as an in-app notification (bell icon), plus a push alert on devices that
        allow notifications. Optionally publish the same message as a homepage banner. Every send is audited.
      </p>

      <div className="space-y-3 rounded-2xl bg-card p-4 shadow-card">
        <div className="space-y-1.5">
          <Label htmlFor="push-title">Title</Label>
          <Input id="push-title" value={title} maxLength={80} onChange={(e) => setTitle(e.target.value)}
            placeholder="Cashback weekend is live" />
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="push-body">Message</Label>
          <Textarea id="push-body" value={body} maxLength={300} rows={3} onChange={(e) => setBody(e.target.value)}
            placeholder="Earn extra cashback on every data purchase this weekend." />
        </div>
        <div className="grid gap-3 sm:grid-cols-2">
          <div className="space-y-1.5">
            <Label htmlFor="push-url">Open link</Label>
            <Input id="push-url" value={url} onChange={(e) => setUrl(e.target.value)} placeholder="/app/data" />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="push-user">Single user ID (optional)</Label>
            <Input id="push-user" value={userId} onChange={(e) => setUserId(e.target.value.trim())}
              placeholder="Leave blank to send to everyone" />
          </div>
        </div>

        <div className="flex items-center justify-between rounded-xl bg-muted/50 p-3">
          <div>
            <p className="text-sm font-medium">Also publish as homepage banner</p>
            <p className="text-xs text-muted-foreground">
              {userId ? "Unavailable for single-user messages" : "Shows on every customer's home screen"}
            </p>
          </div>
          <Switch checked={asBanner && !userId} disabled={!!userId} onCheckedChange={setAsBanner} />
        </div>

        <Button
          className="w-full"
          disabled={mut.isPending || title.trim().length < 2 || body.trim().length < 2}
          onClick={() => mut.mutate()}
        >
          <Send className="mr-2 h-4 w-4" />
          {mut.isPending ? "Sending…" : "Send to all users"}
        </Button>
      </div>
    </div>
  );
}
