"use client";

import { useEffect, useState, type FormEvent } from "react";

import {
  getApiSession,
  loginApiSession,
  logoutApiSession,
} from "./api-client";

interface CaseAuthControlProps {
  authenticated: boolean;
  onAuthenticatedChange: (authenticated: boolean) => void;
}

export function CaseAuthControl({
  authenticated,
  onAuthenticatedChange,
}: CaseAuthControlProps) {
  const [apiAccessKey, setApiAccessKey] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isChecking, setIsChecking] = useState(true);
  const [message, setMessage] = useState("");

  useEffect(() => {
    let isCurrent = true;
    getApiSession()
      .then((session) => {
        if (!isCurrent) return;
        onAuthenticatedChange(session.authenticated);
        setMessage(session.authenticated ? "已登录" : "");
      })
      .catch(() => {
        if (!isCurrent) return;
        onAuthenticatedChange(false);
        setMessage("登录状态检查失败");
      })
      .finally(() => {
        if (isCurrent) setIsChecking(false);
      });
    return () => {
      isCurrent = false;
    };
  }, [onAuthenticatedChange]);

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const trimmed = apiAccessKey.trim();
    if (!trimmed) {
      setMessage("请输入访问密钥。");
      return;
    }

    setIsSubmitting(true);
    setMessage("");
    try {
      const session = await loginApiSession(trimmed);
      onAuthenticatedChange(session.authenticated);
      if (session.authenticated) {
        setApiAccessKey("");
        setMessage("已登录");
      } else {
        setMessage(session.error ?? "访问密钥无效或已失效");
      }
    } catch (error) {
      onAuthenticatedChange(false);
      setMessage(error instanceof Error ? error.message : "登录失败");
    } finally {
      setIsSubmitting(false);
    }
  }

  async function logout() {
    setIsSubmitting(true);
    setMessage("");
    try {
      await logoutApiSession();
      onAuthenticatedChange(false);
      setMessage("已退出登录。");
    } catch (error) {
      setMessage(error instanceof Error ? error.message : "退出登录失败");
    } finally {
      setIsSubmitting(false);
    }
  }

  if (authenticated) {
    return (
      <div className="api-session-control" aria-label="访问密钥登录状态">
        <span className="status-pill pass">已登录</span>
        <button
          className="secondary-button"
          disabled={isSubmitting}
          onClick={logout}
          type="button"
        >
          退出
        </button>
        {message && message !== "已登录" ? <small>{message}</small> : null}
      </div>
    );
  }

  return (
    <form className="api-session-control" onSubmit={submit}>
      <label className="api-key-field">
        <span>访问密钥</span>
        <input
          autoComplete="current-password"
          disabled={isChecking || isSubmitting}
          onChange={(event) => setApiAccessKey(event.target.value)}
          type="password"
          value={apiAccessKey}
        />
      </label>
      <button disabled={isChecking || isSubmitting} type="submit">
        {isSubmitting ? "登录中..." : "确认登录"}
      </button>
      {message ? <small>{message}</small> : null}
    </form>
  );
}
