import { useState, useEffect } from 'react';
import { supabase } from '../lib/supabase';

const VAPID_PUBLIC_KEY = import.meta.env.VITE_VAPID_PUBLIC_KEY;

/**
 * Convert a base64url string to a Uint8Array suitable for
 * PushManager.subscribe({ applicationServerKey }).
 */
function urlB64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
  const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
  const rawData = atob(base64);
  return Uint8Array.from([...rawData].map((c) => c.charCodeAt(0)));
}

/**
 * Hook that manages Web Push subscription state for the current admin user.
 *
 * Returns:
 *   supported  – browser supports Push API
 *   subscribed – a push subscription is active
 *   loading    – async operation in progress
 *   subscribe  – enable push & save subscription to Supabase
 *   unsubscribe – revoke push & remove from Supabase
 */
export function usePushNotifications() {
  const [supported, setSupported] = useState(false);
  const [subscribed, setSubscribed] = useState(false);
  const [loading, setLoading] = useState(false);

  // Detect browser support on mount
  useEffect(() => {
    setSupported('serviceWorker' in navigator && 'PushManager' in window);
  }, []);

  // Sync subscribed state from current SW registration
  useEffect(() => {
    if (!supported) return;
    navigator.serviceWorker.ready.then((reg) => {
      reg.pushManager.getSubscription().then((sub) => setSubscribed(!!sub));
    });
  }, [supported]);

  const subscribe = async () => {
    if (!supported || !VAPID_PUBLIC_KEY) return;
    setLoading(true);
    try {
      const reg = await navigator.serviceWorker.ready;
      const sub = await reg.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlB64ToUint8Array(VAPID_PUBLIC_KEY),
      });

      const {
        data: { user },
      } = await supabase.auth.getUser();

      await supabase.from('push_subscriptions').upsert(
        { user_id: user.id, subscription: sub.toJSON() },
        { onConflict: 'user_id' },
      );

      setSubscribed(true);
    } catch (e) {
      console.error('Push subscribe failed:', e);
    }
    setLoading(false);
  };

  const unsubscribe = async () => {
    setLoading(true);
    try {
      const reg = await navigator.serviceWorker.ready;
      const sub = await reg.pushManager.getSubscription();
      if (sub) await sub.unsubscribe();

      const {
        data: { user },
      } = await supabase.auth.getUser();
      await supabase.from('push_subscriptions').delete().eq('user_id', user.id);

      setSubscribed(false);
    } catch (e) {
      console.error('Push unsubscribe failed:', e);
    }
    setLoading(false);
  };

  return { supported, subscribed, loading, subscribe, unsubscribe };
}
