"use client";

import { useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import {
  subscribeToPush,
  unsubscribeFromPush,
  sendTestNotification,
} from "@/app/settings/push-actions";

function urlBase64ToUint8Array(base64String: string): Uint8Array<ArrayBuffer> {
  const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
  const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
  const raw = atob(base64);
  const buf = new Uint8Array(raw.length);
  for (let i = 0; i < raw.length; i++) buf[i] = raw.charCodeAt(i);
  return buf;
}

export function PushOptIn({ vapidKey }: { vapidKey: string }) {
  const [status, setStatus] = useState<"idle" | "subscribed" | "denied" | "unsupported">("idle");
  const [endpoint, setEndpoint] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();
  const [testSent, setTestSent] = useState(false);

  if (!vapidKey) return null;
  if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
    return (
      <p className="text-sm text-muted-foreground">
        Push notifications not supported in this browser.
      </p>
    );
  }

  async function subscribe() {
    try {
      const registration = await navigator.serviceWorker.ready;
      const sub = await registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(vapidKey),
      });
      const json = sub.toJSON() as { endpoint: string; keys: { p256dh: string; auth: string } };
      startTransition(async () => {
        await subscribeToPush(json, navigator.userAgent);
        setEndpoint(json.endpoint);
        setStatus("subscribed");
      });
    } catch {
      setStatus("denied");
    }
  }

  async function unsubscribe() {
    if (!endpoint) return;
    const registration = await navigator.serviceWorker.ready;
    const sub = await registration.pushManager.getSubscription();
    if (sub) await sub.unsubscribe();
    startTransition(async () => {
      await unsubscribeFromPush(endpoint);
      setEndpoint(null);
      setStatus("idle");
    });
  }

  function sendTest() {
    startTransition(async () => {
      await sendTestNotification();
      setTestSent(true);
      setTimeout(() => setTestSent(false), 3000);
    });
  }

  if (status === "denied") {
    return (
      <p className="text-sm text-destructive">
        Notification permission denied. Enable it in browser settings.
      </p>
    );
  }

  if (status === "subscribed") {
    return (
      <div className="flex items-center gap-3">
        <span className="text-sm text-green-600 dark:text-green-400">
          Push notifications enabled
        </span>
        <Button size="sm" variant="outline" onClick={sendTest} disabled={isPending}>
          {testSent ? "Sent!" : "Send test"}
        </Button>
        <Button size="sm" variant="destructive" onClick={unsubscribe} disabled={isPending}>
          Disable
        </Button>
      </div>
    );
  }

  return (
    <Button size="sm" onClick={subscribe} disabled={isPending}>
      Enable push notifications
    </Button>
  );
}
