import { FormEvent, useState } from "react";
import { ApiError } from "../api/client";
import { useAuth } from "../auth/AuthContext";
import { AuthShell } from "../components/AuthShell";
import { Button, Field, Input } from "../components/ui";
import { safeGetItem, safeSetItem } from "../lib/safeStorage";

export function AuthPage() {
  const { login, register } = useAuth();
  const [mode, setMode] = useState<"login" | "register">("login");
  const [tenantId, setTenantId] = useState(() => safeGetItem("haixun.tenant_id") || "default");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [error, setError] = useState("");
  const [submitting, setSubmitting] = useState(false);

  async function submit(event: FormEvent) {
    event.preventDefault();
    setError("");
    setSubmitting(true);
    try {
      const normalizedTenantId = tenantId.trim() || "default";
      safeSetItem("haixun.tenant_id", normalizedTenantId);
      if (mode === "login") {
        await login(normalizedTenantId, email, password);
      } else {
        await register(normalizedTenantId, email, password, displayName);
      }
    } catch (err) {
      setError(toAuthErrorMessage(err, mode));
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <AuthShell>
      <form className="page-grid" onSubmit={submit}>
        <p className="muted" style={{ margin: 0 }}>
          {mode === "login" ? "登入後就能管理 Threads 帳號、發文庫存與找 TA 任務。" : "建立島民帳號，開始設定你的巡樓工作台。"}
        </p>
        {mode === "register" ? (
          <Field label="顯示名稱">
            <Input value={displayName} onChange={(e) => setDisplayName(e.target.value)} placeholder="例如：Daniel" />
          </Field>
        ) : null}
        <Field label="Email">
          <Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required placeholder="you@example.com" />
        </Field>
        <Field label="密碼">
          <Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} />
        </Field>
        {error ? <p className="error-text">{error}</p> : null}
        <div className="button-row">
          <Button type="submit" variant="primary" disabled={submitting}>
            {submitting ? "處理中" : mode === "login" ? "登入" : "註冊"}
          </Button>
          <Button type="button" variant="ghost" onClick={() => setMode(mode === "login" ? "register" : "login")}>
            {mode === "login" ? "我要註冊" : "已有帳號，去登入"}
          </Button>
        </div>
      </form>
    </AuthShell>
  );
}

function toAuthErrorMessage(error: unknown, mode: "login" | "register") {
  if (error instanceof TypeError) {
    return "連不上伺服器，請確認後端服務是否已啟動。";
  }
  if (error instanceof ApiError) {
    const message = error.message.toLowerCase();
    if (error.status === 401 || message.includes("invalid email or password")) {
      return "Email 或密碼不正確，請再確認一次。";
    }
    if (message.includes("already") || message.includes("duplicate")) {
      return "這個 Email 已經註冊過，請改用登入。";
    }
    if (message.includes("password") && (message.includes("least") || message.includes("min"))) {
      return "密碼至少需要 8 個字元。";
    }
    if (message.includes("email")) {
      return "請輸入有效的 Email。";
    }
    if (message.includes("tenant_id")) {
      return "登入環境設定缺少 tenant，請重新整理後再試一次。";
    }
    if (message.includes("required") || message.includes("not set") || message.includes("missing")) {
      return "資料沒有填完整，請確認 Email 與密碼。";
    }
    if (error.status >= 500) {
      return "伺服器暫時無法處理，請稍後再試。";
    }
  }
  return mode === "login" ? "登入失敗，請檢查資料後再試一次。" : "註冊失敗，請檢查資料後再試一次。";
}
