"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { motion } from "framer-motion";
import { Mail, Lock, User, Loader2, Zap, Globe, CheckCircle } from "lucide-react";
import { signIn } from "next-auth/react";
import { toast } from "sonner";

export default function RegisterPage() {
  const router = useRouter();
  const [form, setForm] = useState({ name: "", email: "", password: "", confirm: "" });
  const [isLoading, setIsLoading] = useState(false);
  const [isGoogleLoading, setIsGoogleLoading] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setForm((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    if (form.password !== form.confirm) {
      toast.error("Password tidak sama!");
      return;
    }
    if (form.password.length < 8) {
      toast.error("Password minimal 8 karakter");
      return;
    }
    setIsLoading(true);
    try {
      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: form.name, email: form.email, password: form.password }),
      });
      const data = await res.json();
      if (!res.ok) {
        toast.error(data.error ?? "Gagal mendaftar");
        return;
      }
      toast.success("Akun berhasil dibuat! Silakan masuk.");
      await signIn("credentials", {
        email: form.email,
        password: form.password,
        redirect: false,
      });
      router.push("/dashboard");
    } finally {
      setIsLoading(false);
    }
  };

  const handleGoogle = async () => {
    setIsGoogleLoading(true);
    await signIn("google", { callbackUrl: "/dashboard" });
  };

  const passwordStrength = (pwd: string) => {
    if (!pwd) return 0;
    if (pwd.length < 6) return 1;
    if (pwd.length < 8) return 2;
    if (/[A-Z]/.test(pwd) && /[0-9]/.test(pwd)) return 4;
    return 3;
  };
  const strength = passwordStrength(form.password);
  const strengthColors = ["", "bg-rose-500", "bg-orange-500", "bg-amber-500", "bg-emerald-500"];
  const strengthLabels = ["", "Lemah", "Cukup", "Kuat", "Sangat Kuat"];

  return (
    <div className="min-h-screen flex items-center justify-center p-4 bg-gradient-to-br from-indigo-950 via-zinc-950 to-violet-950">
      <div className="fixed inset-0 -z-10">
        <div className="absolute top-1/4 -left-20 w-96 h-96 bg-indigo-600/20 rounded-full blur-3xl" />
        <div className="absolute bottom-1/4 -right-20 w-96 h-96 bg-violet-600/20 rounded-full blur-3xl" />
      </div>

      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="w-full max-w-md"
      >
        <div className="glass border border-white/15 rounded-3xl p-8 text-white">
          {/* Logo */}
          <div className="text-center mb-8">
            <div className="w-14 h-14 gradient-brand rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-xl">
              <Zap className="w-7 h-7 text-white" fill="white" />
            </div>
            <h1 className="text-2xl font-bold">Daftar ke QuizB</h1>
            <p className="text-white/60 text-sm mt-1">Gratis selamanya — mulai belajar sekarang!</p>
          </div>

          {/* Google */}
          <button
            onClick={handleGoogle}
            disabled={isGoogleLoading}
            className="w-full flex items-center justify-center gap-3 py-3.5 bg-white text-zinc-900 font-semibold rounded-2xl hover:bg-white/90 transition-all mb-6 disabled:opacity-70"
          >
            {isGoogleLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : <Globe className="w-5 h-5" />}
            Daftar dengan Google
          </button>

          <div className="flex items-center gap-4 mb-6">
            <div className="flex-1 h-px bg-white/15" />
            <span className="text-white/40 text-xs font-medium">atau</span>
            <div className="flex-1 h-px bg-white/15" />
          </div>

          {/* Form */}
          <form onSubmit={handleRegister} className="space-y-4">
            <div className="relative">
              <User className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40" />
              <input
                name="name"
                type="text"
                placeholder="Nama Lengkap"
                value={form.name}
                onChange={handleChange}
                required
                className="w-full pl-11 pr-4 py-3.5 bg-white/10 border border-white/15 rounded-2xl text-white placeholder:text-white/40 focus:outline-none focus:border-indigo-400 transition-colors text-sm"
              />
            </div>
            <div className="relative">
              <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40" />
              <input
                name="email"
                type="email"
                placeholder="Email"
                value={form.email}
                onChange={handleChange}
                required
                className="w-full pl-11 pr-4 py-3.5 bg-white/10 border border-white/15 rounded-2xl text-white placeholder:text-white/40 focus:outline-none focus:border-indigo-400 transition-colors text-sm"
              />
            </div>
            <div>
              <div className="relative">
                <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40" />
                <input
                  name="password"
                  type="password"
                  placeholder="Password (min. 8 karakter)"
                  value={form.password}
                  onChange={handleChange}
                  required
                  className="w-full pl-11 pr-4 py-3.5 bg-white/10 border border-white/15 rounded-2xl text-white placeholder:text-white/40 focus:outline-none focus:border-indigo-400 transition-colors text-sm"
                />
              </div>
              {form.password && (
                <div className="mt-2 flex items-center gap-2">
                  <div className="flex-1 h-1.5 bg-white/10 rounded-full overflow-hidden">
                    <div
                      className={`h-full rounded-full transition-all ${strengthColors[strength]}`}
                      style={{ width: `${(strength / 4) * 100}%` }}
                    />
                  </div>
                  <span className="text-xs text-white/50">{strengthLabels[strength]}</span>
                </div>
              )}
            </div>
            <div className="relative">
              <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40" />
              <input
                name="confirm"
                type="password"
                placeholder="Konfirmasi Password"
                value={form.confirm}
                onChange={handleChange}
                required
                className="w-full pl-11 pr-4 py-3.5 bg-white/10 border border-white/15 rounded-2xl text-white placeholder:text-white/40 focus:outline-none focus:border-indigo-400 transition-colors text-sm"
              />
              {form.confirm && form.confirm === form.password && (
                <CheckCircle className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-emerald-400" />
              )}
            </div>

            <button
              type="submit"
              disabled={isLoading}
              className="w-full flex items-center justify-center gap-2 py-3.5 gradient-brand rounded-2xl font-semibold hover:opacity-90 transition-opacity disabled:opacity-70 shadow-lg shadow-indigo-500/25"
            >
              {isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : null}
              Buat Akun Gratis
            </button>
          </form>

          <p className="text-center text-white/60 text-sm mt-6">
            Sudah punya akun?{" "}
            <Link href="/login" className="text-indigo-400 font-semibold hover:underline">
              Masuk Sekarang
            </Link>
          </p>
        </div>
      </motion.div>
    </div>
  );
}
