import { isPlatformBrowser } from "@angular/common";
import { Component, inject, Input, PLATFORM_ID } from "@angular/core";
import Omnizapi, { OmnizapiError } from "@omnizapi/connect";
import type { OmnizapiClient } from "@omnizapi/connect";

@Component({
  selector: "app-connect",
  standalone: true,
  template: `
    <button type="button" (click)="handleConnect()" [disabled]="loading">
      {{ loading ? "Connecting..." : "Connect channel" }}
    </button>
    <p role="status">{{ message }}</p>
  `,
})
export class ConnectComponent {
  @Input() channelId = "";

  loading = false;
  message = "";

  private readonly platformId = inject(PLATFORM_ID);
  private client: OmnizapiClient | undefined;

  async handleConnect() {
    if (!isPlatformBrowser(this.platformId) || this.loading) return;
    this.loading = true;
    this.message = "Connecting...";

    try {
      this.client ??= Omnizapi.newClient({ publicKey: "your-public-key" });
      const result = await this.client.connect({ channelId: this.channelId });

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

      const response = await fetch("/api/connect-channel", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(result),
      });
      if (!response.ok) {
        this.message = "The backend could not finalize the connection.";
        return;
      }

      this.message = "Channel connected!";
    } catch (error) {
      this.message = error instanceof OmnizapiError
        ? `Connection error (${error.code}). Check the integration before retrying.`
        : "Could not confirm the connection. Check its backend status before retrying.";
    } finally {
      this.loading = false;
    }
  }
}
