"use client";

import { FormEvent, useEffect, useState } from "react";
import Link from "next/link";
import { Eye, EyeOff, Loader2, Lock, LogIn, MessageSquare, Smartphone, User } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { loginWithPassword } from "@/services/authService";
import { useAuthStore } from "@/stores";

type LoginType = "password" | "phone";

export function LoginForm() {
  const [loginType, setLoginType] = useState<LoginType>("password");
  const [account, setAccount] = useState("");
  const [password, setPassword] = useState("");
  const [phone, setPhone] = useState("");
  const [smsCode, setSmsCode] = useState("");
  const [captcha, setCaptcha] = useState("");
  const [countdown, setCountdown] = useState(0);
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [sendingCode, setSendingCode] = useState(false);
  const [error, setError] = useState("");
  const setSession = useAuthStore((state) => state.setSession);

  useEffect(() => {
    if (countdown <= 0) return;
    const timer = window.setTimeout(() => setCountdown((value) => value - 1), 1000);
    return () => window.clearTimeout(timer);
  }, [countdown]);

  const submitPasswordLogin = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError("");

    if (!account.trim() || !password) {
      const message = "请输入账号和密码";
      setError(message);
      toast.error(message);
      return;
    }

    setLoading(true);
    try {
      const session = await loginWithPassword({ account, password });
      setSession(session);
      toast.success("登录成功");
      const params = new URLSearchParams(window.location.search);
      window.location.href = params.get("redirect") || "/central-config/user/employee";
    } catch (caught) {
      const message = caught instanceof Error ? caught.message : "登录失败，请稍后重试";
      setError(message);
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

  const submitPhoneLogin = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const message = "后端暂未提供手机号登录接口，请先使用密码登录";
    setError(message);
    toast.info(message);
  };

  const sendSmsCode = async () => {
    setError("");
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      const message = "请输入正确的手机号";
      setError(message);
      toast.error(message);
      return;
    }

    setSendingCode(true);
    window.setTimeout(() => {
      setSendingCode(false);
      setCountdown(60);
      toast.info("短信接口暂未接入，已保留倒计时交互");
    }, 500);
  };

  return (
    <div className="rounded-xl border border-white/25 bg-white/95 p-6 shadow-2xl backdrop-blur-md sm:p-8 dark:border-gray-700/40 dark:bg-gray-900/95">
      <div className="mb-6 grid grid-cols-2 rounded-lg bg-gray-100 p-1 text-sm dark:bg-gray-800">
        <button
          type="button"
          className={`flex min-h-10 items-center justify-center gap-2 rounded-md transition ${
            loginType === "password" ? "bg-white text-emerald-700 shadow-sm dark:bg-gray-950 dark:text-emerald-300" : "text-gray-600 dark:text-gray-300"
          }`}
          onClick={() => {
            setError("");
            setLoginType("password");
          }}
        >
          <Lock className="h-4 w-4" />
          密码登录
        </button>
        <button
          type="button"
          className={`flex min-h-10 items-center justify-center gap-2 rounded-md transition ${
            loginType === "phone" ? "bg-white text-emerald-700 shadow-sm dark:bg-gray-950 dark:text-emerald-300" : "text-gray-600 dark:text-gray-300"
          }`}
          onClick={() => {
            setError("");
            setLoginType("phone");
          }}
        >
          <Smartphone className="h-4 w-4" />
          手机登录
        </button>
      </div>

      {error ? (
        <div className="mb-4 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700 dark:border-red-900 dark:bg-red-950/60 dark:text-red-200">
          {error}
        </div>
      ) : null}

      {loginType === "password" ? (
        <form className="space-y-4" onSubmit={submitPasswordLogin}>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200">
            用户名
            <span className="relative mt-2 block">
              <User className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
              <input
                className="h-11 w-full rounded-lg border border-gray-200 bg-white pl-10 pr-3 text-sm outline-none transition focus:border-emerald-500 focus:ring-2 focus:ring-emerald-100 disabled:bg-gray-100 dark:border-gray-700 dark:bg-gray-950 dark:focus:ring-emerald-900"
                value={account}
                onChange={(event) => setAccount(event.target.value)}
                placeholder="请输入用户名"
                autoComplete="username"
                disabled={loading}
              />
            </span>
          </label>

          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200">
            密码
            <span className="relative mt-2 block">
              <Lock className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
              <input
                className="h-11 w-full rounded-lg border border-gray-200 bg-white pl-10 pr-10 text-sm outline-none transition focus:border-emerald-500 focus:ring-2 focus:ring-emerald-100 disabled:bg-gray-100 dark:border-gray-700 dark:bg-gray-950 dark:focus:ring-emerald-900"
                type={showPassword ? "text" : "password"}
                value={password}
                onChange={(event) => setPassword(event.target.value)}
                placeholder="请输入密码"
                autoComplete="current-password"
                disabled={loading}
              />
              <button
                type="button"
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 transition hover:text-gray-700 dark:hover:text-gray-200"
                onClick={() => setShowPassword((value) => !value)}
                disabled={loading}
                aria-label={showPassword ? "隐藏密码" : "显示密码"}
              >
                {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </span>
          </label>

          <Button
            type="submit"
            className="flex h-11 w-full items-center justify-center gap-2 rounded-lg bg-emerald-600 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-70 dark:bg-emerald-700 dark:hover:bg-emerald-800"
            disabled={loading}
          >
            {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <LogIn className="h-4 w-4" />}
            {loading ? "登录中..." : "登录"}
          </Button>

          <div className="text-center text-sm text-gray-500 dark:text-gray-300">
            还没有账号？
            <Link className="font-medium text-emerald-700 transition hover:text-emerald-800 dark:text-emerald-300" href="/register">
              立即注册
            </Link>
          </div>
        </form>
      ) : (
        <form className="space-y-4" onSubmit={submitPhoneLogin}>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200">
            手机号
            <span className="relative mt-2 block">
              <Smartphone className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
              <input
                className="h-11 w-full rounded-lg border border-gray-200 bg-white pl-10 pr-3 text-sm outline-none transition focus:border-emerald-500 focus:ring-2 focus:ring-emerald-100 dark:border-gray-700 dark:bg-gray-950 dark:focus:ring-emerald-900"
                value={phone}
                onChange={(event) => setPhone(event.target.value)}
                placeholder="请输入手机号"
                maxLength={11}
              />
            </span>
          </label>

          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200">
            短信验证码
            <span className="mt-2 flex flex-col gap-2 sm:flex-row">
              <span className="relative flex-1">
                <MessageSquare className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                <input
                  className="h-11 w-full rounded-lg border border-gray-200 bg-white pl-10 pr-3 text-sm outline-none transition focus:border-emerald-500 focus:ring-2 focus:ring-emerald-100 dark:border-gray-700 dark:bg-gray-950 dark:focus:ring-emerald-900"
                  value={smsCode}
                  onChange={(event) => setSmsCode(event.target.value)}
                  placeholder="请输入验证码"
                  maxLength={6}
                />
              </span>
              <Button
                type="button"
                className="flex h-11 items-center justify-center rounded-lg border border-emerald-200 bg-white px-4 text-sm text-emerald-700 hover:bg-emerald-50 disabled:opacity-70 sm:min-w-[120px] dark:border-emerald-900 dark:bg-gray-950 dark:text-emerald-300"
                onClick={sendSmsCode}
                disabled={sendingCode || countdown > 0}
              >
                {sendingCode ? <Loader2 className="h-4 w-4 animate-spin" /> : countdown > 0 ? `${countdown}秒后重试` : "发送验证码"}
              </Button>
            </span>
          </label>

          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200">
            图形验证码
            <input
              className="mt-2 h-11 w-full rounded-lg border border-gray-200 bg-white px-3 text-sm outline-none transition focus:border-emerald-500 focus:ring-2 focus:ring-emerald-100 dark:border-gray-700 dark:bg-gray-950 dark:focus:ring-emerald-900"
              value={captcha}
              onChange={(event) => setCaptcha(event.target.value)}
              placeholder="请输入图形验证码"
            />
          </label>

          <Button
            type="submit"
            className="flex h-11 w-full items-center justify-center gap-2 rounded-lg bg-emerald-600 text-sm font-medium text-white transition hover:bg-emerald-700 dark:bg-emerald-700 dark:hover:bg-emerald-800"
          >
            <LogIn className="h-4 w-4" />
            登录
          </Button>
        </form>
      )}
    </div>
  );
}
