"use client";

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

const roles = ["系统管理员", "数据管理员", "项目负责人", "试验管理员", "种质管理员", "田间调查员", "生信管理员", "实验员"];

export default function RegisterPage() {
  const [form, setForm] = useState({
    account: "",
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
    password: "",
    confirmPassword: "",
    institute: "",
    role: "",
  });
  const [showPwd, setShowPwd] = useState(false);
  const [loading, setLoading] = useState(false);
  const [done, setDone] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const setSession = useAuthStore((state) => state.setSession);

  const setField = (key: keyof typeof form, value: string) => setForm((s) => ({ ...s, [key]: value }));

  const validate = () => {
    const e: Record<string, string> = {};
    if (!form.account.trim()) e.account = "请填写账号";
    if (!form.firstName.trim()) e.firstName = "请填写名";
    if (!form.lastName.trim()) e.lastName = "请填写姓";
    if (!form.email.trim() || !/\S+@\S+\.\S+/.test(form.email)) e.email = "请填写有效邮箱";
    if (!form.password || form.password.length < 6) e.password = "密码至少6位";
    if (form.password !== form.confirmPassword) e.confirmPassword = "两次密码不一致";
    if (!form.institute.trim()) e.institute = "请填写机构";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!validate()) return;

    setLoading(true);
    try {
      const session = await registerAccount({
        account: form.account.trim(),
        name: `${form.lastName.trim()}${form.firstName.trim()}`,
        email: form.email.trim(),
        phone: form.phone.trim() || null,
        password: form.password,
      });
      if (typeof window !== "undefined") {
        localStorage.setItem("user_profile_extras", JSON.stringify({ institute: form.institute.trim(), role: form.role || "试验管理员" }));
      }
      setSession(session);
      setDone(true);
      toast.success("注册成功");
      setTimeout(() => {
        window.location.href = "/dashboard";
      }, 900);
    } catch (caught) {
      const message = caught instanceof Error ? caught.message : "注册失败，请稍后重试";
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

  const fieldClass = "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";

  return (
    <main className="relative flex min-h-screen items-center justify-center overflow-hidden px-4 py-6">
      <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-xl">
        <div className="rounded-3xl border border-white/30 bg-white/15 p-8 shadow-[0_8px_48px_rgba(0,0,0,0.28)] backdrop-blur-2xl">
          <div className="mb-6 flex items-center gap-3">
            <Link href="/login" className="text-white/60 transition hover:text-white"><ArrowLeft className="h-4 w-4" /></Link>
            <div className="grid h-10 w-10 place-items-center rounded-xl bg-gradient-to-br from-green-400 to-emerald-600 shadow-lg"><Sprout className="h-5 w-5 text-white" /></div>
            <div><h1 className="text-base text-white">注册账号</h1><p className="text-xs text-white/60">麦麦数据标准化服务-BrApi</p></div>
          </div>

          {done ? (
            <div className="flex flex-col items-center gap-3 py-8"><div className="grid h-14 w-14 place-items-center rounded-full bg-green-500/30"><Check className="h-7 w-7 text-green-300" /></div><p className="text-sm text-white">注册成功，正在进入系统...</p></div>
          ) : (
            <form onSubmit={submit} className="grid grid-cols-2 gap-3">
              <Field icon={<User className="h-3.5 w-3.5" />} label="账号 *" value={form.account} onChange={(v) => setField("account", v)} error={errors.account} className="col-span-2" inputClass={fieldClass} placeholder="登录账号" />
              <Field icon={<User className="h-3.5 w-3.5" />} label="姓 *" value={form.lastName} onChange={(v) => setField("lastName", v)} error={errors.lastName} inputClass={fieldClass} placeholder="如 Li" />
              <Field icon={<User className="h-3.5 w-3.5" />} label="名 *" value={form.firstName} onChange={(v) => setField("firstName", v)} error={errors.firstName} inputClass={fieldClass} placeholder="如 Wei" />
              <Field icon={<Mail className="h-3.5 w-3.5" />} label="邮箱 *" value={form.email} onChange={(v) => setField("email", v)} error={errors.email} className="col-span-2" inputClass={fieldClass} placeholder="your@email.com" />
              <Field icon={<Building2 className="h-3.5 w-3.5" />} label="所属机构 *" value={form.institute} onChange={(v) => setField("institute", v)} error={errors.institute} className="col-span-2" inputClass={fieldClass} placeholder="如 中国农业科学院" />
              <Field icon={<Building2 className="h-3.5 w-3.5" />} label="手机号" value={form.phone} onChange={(v) => setField("phone", v)} inputClass={fieldClass} placeholder="选填" />
              <div>
                <label className="mb-1.5 block text-xs text-white/80">角色</label>
                <select value={form.role} onChange={(e) => setField("role", e.target.value)} className="w-full rounded-xl border border-white/25 bg-white/15 px-3 py-2.5 text-sm text-white outline-none focus:border-green-300/80">
                  <option value="" className="text-slate-800">请选择（选填）</option>
                  {roles.map((r) => <option key={r} value={r} className="text-slate-800">{r}</option>)}
                </select>
              </div>

              <div>
                <label className="mb-1.5 block text-xs text-white/80">密码 *</label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-white/45" />
                  <input type={showPwd ? "text" : "password"} value={form.password} onChange={(e) => setField("password", e.target.value)} className={`${fieldClass} pr-10`} placeholder="至少6位" />
                  <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-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}</button>
                </div>
                {errors.password ? <p className="mt-1 text-[11px] text-red-300">{errors.password}</p> : null}
              </div>

              <Field icon={<Lock className="h-3.5 w-3.5" />} label="确认密码 *" type={showPwd ? "text" : "password"} value={form.confirmPassword} onChange={(v) => setField("confirmPassword", v)} error={errors.confirmPassword} inputClass={fieldClass} placeholder="再次输入" />

              <button disabled={loading} className="col-span-2 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.35)" : "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" />注册中...</> : "创建账号"}
              </button>

              <p className="col-span-2 mt-2 text-center text-xs text-white/70">已有账号？<Link href="/login" className="ml-1 text-green-300 hover:text-green-200">返回登录</Link></p>
            </form>
          )}
        </div>
      </section>
    </main>
  );
}

function Field({
  icon,
  label,
  value,
  onChange,
  placeholder,
  error,
  inputClass,
  className,
  type = "text",
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  onChange: (value: string) => void;
  placeholder: string;
  inputClass: string;
  error?: string;
  className?: string;
  type?: string;
}) {
  return (
    <div className={className}>
      <label className="mb-1.5 block text-xs text-white/80">{label}</label>
      <div className="relative">
        <span className="absolute left-3 top-1/2 -translate-y-1/2 text-white/45">{icon}</span>
        <input type={type} value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} className={inputClass} />
      </div>
      {error ? <p className="mt-1 text-[11px] text-red-300">{error}</p> : null}
    </div>
  );
}
