"use client";

import { useEffect, useState } from "react";
import styles from "../vip.module.css";
import { LoginForm } from "./LoginForm";
import { AuthForm } from "./AuthForm";

type LoginModalProps = {
  open: boolean;
  onClose: () => void;
  onVerify: (userId: string) => Promise<boolean>;
  onVerifyByEmail?: (email: string, password: string) => Promise<boolean>;
  onSuccess: () => void;
};

export function LoginModal({ open, onClose, onVerify, onVerifyByEmail, onSuccess }: LoginModalProps) {
  const [tab, setTab] = useState<"email" | "legacy">("email");

  useEffect(() => {
    if (open) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => {
      document.body.style.overflow = "";
    };
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [open, onClose]);

  const handleSuccess = () => {
    onClose();
    onSuccess();
  };

  if (!open) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      role="dialog"
      aria-modal="true"
      aria-labelledby="login-modal-title"
    >
      <div
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
        onClick={onClose}
      />
      <div
        className="relative w-full max-w-[400px] rounded-2xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-2xl animate__animated animate__fadeIn animate__faster"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="mb-4 flex items-center justify-between">
          <h2 id="login-modal-title" className={styles.sectionTitle} style={{ margin: 0 }}>
            登录
          </h2>
          <button
            type="button"
            onClick={onClose}
            className="rounded-lg p-2 text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
            aria-label="关闭"
          >
            <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="mb-4 flex gap-2 border-b border-[var(--border)]">
          <button
            type="button"
            onClick={() => setTab("email")}
            className={`pb-2 text-sm font-medium ${tab === "email" ? "border-b-2 border-[var(--primary)] text-[var(--primary)]" : "text-[var(--muted-foreground)]"}`}
          >
            邮箱登录
          </button>
          <button
            type="button"
            onClick={() => setTab("legacy")}
            className={`pb-2 text-sm font-medium ${tab === "legacy" ? "border-b-2 border-[var(--primary)] text-[var(--primary)]" : "text-[var(--muted-foreground)]"}`}
          >
            会员账号恢复
          </button>
        </div>
        {tab === "email" ? (
          <p className={styles.sectionDesc} style={{ marginBottom: "1rem" }}>
            使用邮箱登录，可与 digital / meetup 等站点共享账号
          </p>
        ) : (
          <p className={styles.sectionDesc} style={{ marginBottom: "1rem" }}>
            支持 user_id 或关联 users 的邮箱验证
          </p>
        )}
        {tab === "email" ? (
          <AuthForm onSuccess={handleSuccess} autoFocus />
        ) : (
          <LoginForm
            onVerify={onVerify}
            onVerifyByEmail={onVerifyByEmail}
            onSuccess={handleSuccess}
            autoFocus
          />
        )}
      </div>
    </div>
  );
}
