"use client";

import Link from "next/link";
import { FormEvent, useState } from "react";
import { ArrowRight, Eye, EyeOff, Loader2, Lock, Mail, Sprout } from "lucide-react";
import { toast } from "sonner";
import mainPageBg from "../../../../assets/main_page.png";
import { loginWithPassword } from "@/services/authService";
import { useAuthStore } from "@/stores";

const APP_NAME = "麦麦数据标准化服务-BrApi";

export default function LoginPage() {
  const [account, setAccount] = useState("");
  const [password, setPassword] = useState("");
  const [showPwd, setShowPwd] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const setSession = useAuthStore((state) => state.setSession);

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!account.trim() || !password) {
      const message = "请填写账号和密码";
      setError(message);
      toast.error(message);
      return;
    }

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

  return (
    <main className="relative flex min-h-screen items-center justify-center overflow-hidden px-4 py-8 lg:justify-end lg:pr-16">
      <div className="absolute inset-0 bg-cover bg-no-repeat" style={{ backgroundImage: `url(${mainPageBg.src})`, backgroundPosition: "32% center" }} />
      <div className="absolute inset-0 bg-gradient-to-br from-black/30 via-transparent to-black/20" />

      <section className="relative z-10 w-full max-w-md">
        <div className="rounded-3xl border border-white/35 bg-white/15 p-8 shadow-[0_8px_48px_rgba(0,0,0,0.28)] backdrop-blur-2xl">
          <div className="mb-7 flex flex-col items-center">
            <div className="mb-3 grid h-14 w-14 place-items-center rounded-2xl bg-gradient-to-br from-green-400 to-emerald-600 shadow-lg">
              <Sprout className="h-7 w-7 text-white" />
            </div>
            <h1 className="text-xl text-white" style={{ textShadow: "0 1px 8px rgba(0,0,0,0.4)" }}>{APP_NAME}</h1>
            <p className="mt-1 text-xs text-white/70">Integrating Breeding Data with BrAPI</p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="mb-1.5 block text-xs text-white/85">用户名</label>
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-white/50" />
                <input value={account} onChange={(e) => setAccount(e.target.value)} placeholder="请输入用户名" className="w-full rounded-xl border border-white/25 bg-white/15 py-2.5 pl-10 pr-4 text-sm text-white placeholder:text-white/45 outline-none transition focus:border-green-300/80" />
              </div>
            </div>

            <div>
              <label className="mb-1.5 block text-xs text-white/85">密码</label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-white/50" />
                <input type={showPwd ? "text" : "password"} value={password} onChange={(e) => setPassword(e.target.value)} placeholder="请输入密码" className="w-full rounded-xl border border-white/25 bg-white/15 py-2.5 pl-10 pr-10 text-sm text-white placeholder:text-white/45 outline-none transition focus:border-green-300/80" />
                <button type="button" onClick={() => setShowPwd((v) => !v)} className="absolute right-3 top-1/2 -translate-y-1/2 text-white/45 hover:text-white/75">
                  {showPwd ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>

            {error ? <p className="rounded-lg bg-red-500/10 px-3 py-2 text-center text-xs text-red-200">{error}</p> : null}

            <button disabled={loading} className="mt-2 flex w-full items-center justify-center gap-2 rounded-xl py-2.5 text-sm text-white transition" style={{ background: loading ? "rgba(52,211,153,0.4)" : "linear-gradient(135deg,#10b981,#059669)", boxShadow: loading ? "none" : "0 4px 16px rgba(16,185,129,0.4)" }}>
              {loading ? <><Loader2 className="h-4 w-4 animate-spin" />登录中...</> : <><ArrowRight className="h-4 w-4" />登录</>}
            </button>
          </form>

          <div className="my-5 flex items-center gap-3">
            <div className="h-px flex-1 bg-white/15" />
            <span className="text-xs text-white/50">还没有账号？</span>
            <div className="h-px flex-1 bg-white/15" />
          </div>

          <Link href="/register" className="block w-full rounded-xl border border-white/25 py-2.5 text-center text-sm text-white/85 transition hover:text-white">注册新账号</Link>
        </div>
      </section>
    </main>
  );
}
