"use client";

import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { signIn } from "next-auth/react";
import { Phone, KeyRound, Loader2 } from "lucide-react";
import Logo from "@/components/Logo";
import Button from "@/components/ui/Button";
import { cn } from "@/lib/cn";

export default function LoginForm() {
  const router = useRouter();
  const sp = useSearchParams();
  const callbackUrl = sp.get("callbackUrl") || "/";

  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  const [countdown, setCountdown] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [sending, setSending] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const phoneValid = /^1[3-9]\d{9}$/.test(phone);
  const codeValid = /^\d{6}$/.test(code);

  const sendOtp = async () => {
    if (!phoneValid) {
      setError("请输入有效的中国大陆手机号");
      return;
    }
    setError(null);
    setSending(true);
    try {
      const res = await fetch("/api/auth/send-otp", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ phone }),
      });
      const data = await res.json();
      if (!data.ok) throw new Error(data.error?.message || "发送失败");
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((c) => {
          if (c <= 1) {
            clearInterval(timer);
            return 0;
          }
          return c - 1;
        });
      }, 1000);
    } catch (e) {
      setError(e instanceof Error ? e.message : "发送失败");
    } finally {
      setSending(false);
    }
  };

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!phoneValid || !codeValid) {
      setError("请检查手机号和验证码");
      return;
    }
    setError(null);
    setSubmitting(true);
    try {
      const result = await signIn("phone-otp", {
        phone,
        code,
        redirect: false,
      });
      if (result?.error) {
        setError("验证码错误或已失效");
      } else {
        router.push(callbackUrl);
        router.refresh();
      }
    } catch {
      setError("登录失败，请重试");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="min-h-[calc(100vh-128px)] flex items-center justify-center px-4 py-10">
      <div className="w-full max-w-md">
        {/* Logo */}
        <div className="text-center mb-8">
          <Logo size="lg" href={null} />
          <p className="font-label text-[10px] tracking-[0.4em] uppercase text-purple-300/80 mt-3">
            Sign in to Vote
          </p>
        </div>

        {/* 表单 */}
        <form
          onSubmit={handleLogin}
          className="bg-elevated/60 backdrop-blur-md border border-white/10 rounded-2xl p-6 sm:p-8 space-y-4 shadow-card"
        >
          {/* 手机号 */}
          <div>
            <label className="block font-label text-[10px] tracking-widest uppercase text-white/55 mb-2">
              手机号
            </label>
            <div className="relative">
              <Phone
                size={14}
                className="absolute left-3.5 top-1/2 -translate-y-1/2 text-white/35"
              />
              <input
                type="tel"
                inputMode="numeric"
                autoComplete="tel"
                placeholder="138 0000 0000"
                value={phone}
                maxLength={11}
                onChange={(e) =>
                  setPhone(e.target.value.replace(/\D/g, "").slice(0, 11))
                }
                className="w-full h-11 pl-10 pr-3 rounded-lg bg-surface border border-white/10 text-white placeholder-white/30 focus:outline-none focus:border-purple-500 focus:shadow-[0_0_16px_rgba(139,92,246,0.25)] transition-all"
              />
            </div>
          </div>

          {/* 验证码 */}
          <div>
            <label className="block font-label text-[10px] tracking-widest uppercase text-white/55 mb-2">
              验证码
            </label>
            <div className="flex gap-2">
              <div className="relative flex-1">
                <KeyRound
                  size={14}
                  className="absolute left-3.5 top-1/2 -translate-y-1/2 text-white/35"
                />
                <input
                  type="text"
                  inputMode="numeric"
                  autoComplete="one-time-code"
                  placeholder="6 位验证码"
                  value={code}
                  maxLength={6}
                  onChange={(e) =>
                    setCode(e.target.value.replace(/\D/g, "").slice(0, 6))
                  }
                  className="w-full h-11 pl-10 pr-3 rounded-lg bg-surface border border-white/10 text-white placeholder-white/30 focus:outline-none focus:border-purple-500 focus:shadow-[0_0_16px_rgba(139,92,246,0.25)] transition-all tracking-widest"
                />
              </div>
              <button
                type="button"
                disabled={!phoneValid || countdown > 0 || sending}
                onClick={sendOtp}
                className={cn(
                  "h-11 px-4 rounded-lg font-display text-xs tracking-widest uppercase border transition-all whitespace-nowrap",
                  countdown > 0
                    ? "bg-white/5 border-white/10 text-white/30"
                    : "bg-purple-500/10 border-purple-500/40 text-purple-300 hover:bg-purple-500/15 disabled:opacity-50",
                )}
              >
                {sending ? (
                  <Loader2 size={14} className="animate-spin" />
                ) : countdown > 0 ? (
                  `${countdown}s`
                ) : (
                  "发送"
                )}
              </button>
            </div>
          </div>

          {/* 错误提示 */}
          {error && (
            <div className="px-3 py-2 rounded-lg bg-pink-500/10 border border-pink-500/30 text-pink-300 text-xs">
              {error}
            </div>
          )}

          {process.env.NODE_ENV !== "production" && (
            <div className="px-3 py-2 rounded-lg bg-purple-500/8 border border-purple-500/25 text-[11px] text-purple-300/80">
              开发环境：万能验证码 <b className="text-white">123456</b>
            </div>
          )}

          <Button
            type="submit"
            variant="primary"
            size="lg"
            className="w-full"
            disabled={!phoneValid || !codeValid}
            loading={submitting}
          >
            登录 / 注册
          </Button>

          <p className="text-[11px] text-white/40 text-center leading-relaxed">
            未注册手机号将自动创建账号
            <br />
            登录即表示同意{" "}
            <Link href="/terms" className="text-purple-300 hover:underline">
              用户协议
            </Link>{" "}
            和{" "}
            <Link href="/privacy" className="text-purple-300 hover:underline">
              隐私协议
            </Link>
          </p>
        </form>

        {/* 其他登录方式 · 待开通 */}
        <div className="mt-6 text-center">
          <p className="font-label text-[10px] tracking-widest text-white/35 uppercase mb-3">
            ── 其他登录方式（即将上线）──
          </p>
          <div className="flex justify-center gap-3">
            <button
              disabled
              className="w-11 h-11 rounded-full bg-white/5 border border-white/10 flex items-center justify-center text-white/30 cursor-not-allowed text-[10px] font-display tracking-wider"
              aria-label="微信登录（即将上线）"
              title="微信登录（即将上线）"
            >
              WX
            </button>
            <button
              disabled
              className="w-11 h-11 rounded-full bg-white/5 border border-white/10 flex items-center justify-center text-white/30 cursor-not-allowed text-[10px] font-display tracking-wider"
              aria-label="QQ 登录（即将上线）"
              title="QQ 登录（即将上线）"
            >
              QQ
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
