import { useEffect, useRef, useState } from 'react';
import { usePage, usePoll } from '@inertiajs/react';
import { configureEcho, echo } from '@laravel/echo-react';
import type { ChannelAuthorizationCallback } from 'pusher-js';

/** How the browser connects: the `realtime` prop rutatiina/realtime shares. */
export type RealtimeClient = {
  broadcaster: 'reverb' | 'pusher';
  key: string | null;
  cluster: string | null;
  host: string | null;
  port: number | null;
  scheme: string;
  /** The signed-in user's private channel. */
  channel: string;
};

let configured: string | null = null;

function xsrfToken(): string {
  const cookie = document.cookie
    .split('; ')
    .find((value) => value.startsWith('XSRF-TOKEN='));
  return cookie ? decodeURIComponent(cookie.slice('XSRF-TOKEN='.length)) : '';
}

function connect(client: RealtimeClient): void {
  const signature = JSON.stringify(client);
  if (configured === signature) return;
  configured = signature;

  const tls = client.scheme === 'https';
  configureEcho({
    broadcaster: client.broadcaster,
    key: client.key ?? '',
    ...(client.cluster ? { cluster: client.cluster } : {}),
    ...(client.host
      ? {
          wsHost: client.host,
          wsPort: client.port ?? (tls ? 443 : 80),
          wssPort: client.port ?? 443,
        }
      : {}),
    forceTLS: tls,
    enabledTransports: ['ws', 'wss'],
    // Channel authorization with the session, like the app's other requests.
    authorizer: (channel: { name: string }) => ({
      authorize: (socketId: string, callback: ChannelAuthorizationCallback) => {
        fetch('/broadcasting/auth', {
          method: 'POST',
          credentials: 'same-origin',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'X-XSRF-TOKEN': xsrfToken(),
          },
          body: JSON.stringify({
            socket_id: socketId,
            channel_name: channel.name,
          }),
        })
          .then((response) => {
            if (!response.ok)
              throw new Error(
                `Channel authorization failed (${response.status})`,
              );
            return response.json();
          })
          .then((data) => callback(null, data))
          .catch((error: Error) => callback(error, null));
      },
    }),
  });
}

/**
 * Runs `callback` when the server signals one of `events` to the signed-in user
 * (Realtime::signal() in PHP). Returns whether the page is connected: without
 * rutatiina/realtime, or while the connection is down, it is not, and the page should
 * keep polling (usePollUnlessLive).
 */
export function useRealtime<T = Record<string, unknown>>(
  events: string | string[],
  callback: (payload: T) => void,
): boolean {
  const client = usePage().props.realtime as RealtimeClient | null | undefined;
  const [connected, setConnected] = useState(false);
  const handler = useRef(callback);
  const names = (Array.isArray(events) ? events : [events]).join(',');

  useEffect(() => {
    handler.current = callback;
  });

  useEffect(() => {
    if (!client?.key) {
      setConnected(false);
      return;
    }

    connect(client);
    const instance = echo();
    const channel = instance.private(client.channel);
    const listener = (payload: T) => handler.current(payload);
    const list = names.split(',');
    list.forEach((event) => channel.listen(`.${event}`, listener));

    setConnected(instance.connectionStatus() === 'connected');
    const stop = instance.connector.onConnectionChange((status) =>
      setConnected(status === 'connected'),
    );

    return () => {
      list.forEach((event) => channel.stopListening(`.${event}`, listener));
      stop();
    };
    // The client is compared by value: shared props are new objects on every visit.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [JSON.stringify(client), names]);

  return connected;
}

/**
 * Inertia's usePoll, paused while real-time updates are connected.
 */
export function usePollUnlessLive(
  live: boolean,
  interval: number,
  only: string[],
): void {
  const { start, stop } = usePoll(interval, { only }, { autoStart: false });

  useEffect(() => {
    if (live) stop();
    else start();
    return stop;
  }, [live, start, stop]);
}
