'use client';

import { useEffect, useRef, useState } from "react";
import Omnizapi, { OmnizapiError } from "@omnizapi/connect";
import type { OmnizapiClient } from "@omnizapi/connect";

interface ConnectButtonProps {
  channelId: string;
  onSuccess?: () => void;
}

export function ConnectButton({ channelId, onSuccess }: ConnectButtonProps) {
  const client = useRef<OmnizapiClient | undefined>(undefined);
  const activeController = useRef<AbortController | undefined>(undefined);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");

  // AbortSignal support is Unreleased. Cleanup does not undo backend changes.
  useEffect(() => () => { activeController.current?.abort(); }, []);

  async function handleConnect() {
    if (activeController.current) return;
    const controller = new AbortController();
    activeController.current = controller;
    setLoading(true);
    setMessage("Connecting...");

    try {
      client.current ??= Omnizapi.newClient({
        publicKey: "your-public-key",
        logo: "https://app.example.com/logo.png",
      });
      const result = await client.current.connect({ channelId, signal: controller.signal });
      if (controller.signal.aborted) return;

      if (!result.success) {
        setMessage(`Connection not completed (${result.reason}).`);
        return;
      }

      // Includes channelId; validate the session/tenant and credentials server-side.
      const response = await fetch("/api/connect-channel", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(result),
        signal: controller.signal,
      });
      if (controller.signal.aborted) return;
      if (!response.ok) {
        setMessage("The backend could not finalize the connection.");
        return;
      }

      setMessage("Channel connected!");
      onSuccess?.();
    } catch (error) {
      if (controller.signal.aborted) return;
      setMessage(error instanceof OmnizapiError
        ? `Connection error (${error.code}). Check the integration before retrying.`
        : "Could not confirm the connection. Check its backend status before retrying.");
    } finally {
      if (activeController.current === controller) activeController.current = undefined;
      if (!controller.signal.aborted) setLoading(false);
    }
  }

  return (
    <div>
      <button type="button" onClick={handleConnect} disabled={loading}>
        {loading ? "Connecting..." : "Connect channel"}
      </button>
      <p role="status">{message}</p>
    </div>
  );
}
