import { useEffect, useState } from "react";
import axios from "./axios";
import Echo, { Broadcaster } from "laravel-echo";
import Pusher from "pusher-js";

// Define window type extension for Pusher, if necessary
declare global {
  interface Window {
    Pusher: typeof Pusher;
  }
}

if (typeof window !== "undefined") {
  window.Pusher = Pusher;
}

type EchoInstance = Echo<keyof Broadcaster> | undefined;

interface AuthorizeCallback {
  (error: any, data: any): void;
}

interface Channel {
  name: string;
}

// You can replace `string` with any other specific type for token if needed
const useEcho = (token?: string) => {
  const [echoInstance, setEchoInstance] = useState<EchoInstance>();

  useEffect(() => {
    // Ensure port env vars are numbers (they may come as strings from process.env)
    const wsPort = process.env.NEXT_PUBLIC_APP_REVERB_WSHPORT
      ? Number(process.env.NEXT_PUBLIC_APP_REVERB_WSHPORT)
      : undefined;
    const wssPort = process.env.NEXT_PUBLIC_APP_REVERB_WSSHPORT
      ? Number(process.env.NEXT_PUBLIC_APP_REVERB_WSSHPORT)
      : undefined;

    // We are going to create the Echo instance here...
    const echo = new Echo({
      broadcaster: "reverb",
      key: process.env.NEXT_PUBLIC_APP_REVERB_KEY,
      authorizer: (channel: Channel) => {
        return {
          authorize: (socketId: string, callback: AuthorizeCallback) => {
            axios
              .post(
                "broadcasting/authorize",
                {
                  socket_id: socketId,
                  channel_name: channel.name,
                },
                {
                  headers: {
                    Authorization: `Bearer ${token}`,
                    "X-Websocket": true,
                  },
                }
              )
              .then((response: { data: any }) => {
                callback(null, response.data);
              })
              .catch((error: any) => {
                callback(error, error);
              });
          },
        };
      },
      wsHost: process.env.NEXT_PUBLIC_APP_REVERB_HOST,
      wsPort,
      wssPort,
      forceTLS: process.env.NEXT_PUBLIC_APP_REVERB_FORCETLS === "false" ? false : true,
      enabledTransports: ["ws", "wss"],
    });
    setEchoInstance(echo);
  }, [token]);

  return echoInstance;
};

export default useEcho;
