"use client";

import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";

type ApiResponse = {
  ok: boolean;
  error?: {
    message?: string;
  };
};

export function GatewayBindForm({
  labels,
}: {
  labels: {
    title: string;
    body: string;
    userIdLabel: string;
    userIdHint: string;
    tokenLabel: string;
    tokenHint: string;
    submit: string;
    submitting: string;
    invalidUserId: string;
    invalidToken: string;
    success: string;
  };
}) {
  const router = useRouter();
  const [gatewayUserId, setGatewayUserId] = useState("");
  const [gatewayAccessToken, setGatewayAccessToken] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();

  function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const userId = Number(gatewayUserId.trim());
    const accessToken = gatewayAccessToken.trim();

    if (!Number.isInteger(userId) || userId <= 0) {
      setError(labels.invalidUserId);
      setSuccess(null);
      return;
    }
    if (!accessToken) {
      setError(labels.invalidToken);
      setSuccess(null);
      return;
    }

    startTransition(async () => {
      setError(null);
      setSuccess(null);

      try {
        const response = await fetch("/api/auth/gateway-bind", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            gateway_user_id: userId,
            gateway_access_token: accessToken,
          }),
        });
        const payload = (await response.json()) as ApiResponse;

        if (!response.ok || !payload.ok) {
          setError(payload.error?.message ?? labels.invalidToken);
          return;
        }

        setSuccess(labels.success);
        router.refresh();
      } catch (requestError) {
        setError(requestError instanceof Error ? requestError.message : labels.invalidToken);
      }
    });
  }

  return (
    <div className="gateway-bind-stack">
      <div className="section-heading compact">
        <h2>{labels.title}</h2>
        <p>{labels.body}</p>
      </div>
      <form className="auth-form" onSubmit={handleSubmit}>
        <label className="field-label" htmlFor="gateway-user-id">
          {labels.userIdLabel}
        </label>
        <input
          className="text-input"
          id="gateway-user-id"
          inputMode="numeric"
          onChange={(event) => setGatewayUserId(event.target.value)}
          placeholder="123"
          type="text"
          value={gatewayUserId}
        />
        <p className="field-hint">{labels.userIdHint}</p>

        <label className="field-label" htmlFor="gateway-access-token">
          {labels.tokenLabel}
        </label>
        <input
          className="text-input"
          id="gateway-access-token"
          onChange={(event) => setGatewayAccessToken(event.target.value)}
          placeholder="access_token"
          spellCheck={false}
          type="password"
          value={gatewayAccessToken}
        />
        <p className="field-hint">{labels.tokenHint}</p>

        {error ? <div className="status-banner status-banner-error">{error}</div> : null}
        {success ? <div className="status-banner">{success}</div> : null}

        <button className="button button-dark" disabled={isPending} type="submit">
          {isPending ? labels.submitting : labels.submit}
        </button>
      </form>
    </div>
  );
}
