"use client";

import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import { Eye, EyeOff, Loader2, LockKeyhole, ShieldCheck, User } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import Logo from "@/components/ppdb/Logo";

export default function AdminLogin({ onSuccess }: { onSuccess: (username: string) => void }) {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [show, setShow] = useState(false);
  const [loading, setLoading] = useState(false);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await fetch("/api/admin/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password }),
      });
      const json = await res.json();
      if (!res.ok) {
        toast.error(json.error || "Gagal login.");
        return;
      }
      toast.success(`Selamat bertugas, ${json.username}!`);
      onSuccess(json.username);
    } catch {
      toast.error("Terjadi kesalahan jaringan.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="relative flex min-h-screen flex-col items-center justify-center overflow-hidden bg-gradient-to-br from-[#4a121c] via-[#5d1420] to-[#3a0e15] px-4 py-12">
      <div className="pointer-events-none absolute inset-0 bg-dots opacity-30" />
      <div className="animate-blob pointer-events-none absolute -top-24 -left-20 size-96 bg-[#7B1E28]/70 blur-2xl" />
      <div className="animate-blob pointer-events-none absolute -bottom-24 -right-16 size-96 bg-[#D4A017]/20 blur-3xl [animation-delay:-5s]" />

      <motion.div
        initial={{ opacity: 0, y: 28, scale: 0.97 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        transition={{ duration: 0.45, type: "spring", stiffness: 120, damping: 18 }}
        className="relative w-full max-w-md"
      >
        <div className="rounded-[2rem] border border-yellow-500/20 bg-white/95 p-8 shadow-2xl backdrop-blur">
          <div className="flex flex-col items-center text-center">
            <motion.div
              initial={{ rotate: -8, scale: 0.9 }}
              animate={{ rotate: 0, scale: 1 }}
              transition={{ delay: 0.15, type: "spring", stiffness: 200 }}
            >
              <Logo size={64} />
            </motion.div>
            <h1 className="mt-4 text-xl font-extrabold text-[#4a1520]">Panitia PPDB</h1>
            <p className="mt-1 text-sm text-muted-foreground">
              Masuk untuk mengelola pendaftaran siswa baru
            </p>
          </div>

          <form onSubmit={submit} className="mt-7 space-y-4">
            <div className="space-y-1.5">
              <Label htmlFor="username" className="text-sm font-semibold text-[#4a1520]">
                Username
              </Label>
              <div className="relative">
                <User className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  id="username"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  placeholder="username panitia"
                  autoComplete="username"
                  required
                  className="h-11 rounded-xl pl-9"
                />
              </div>
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="password" className="text-sm font-semibold text-[#4a1520]">
                Password
              </Label>
              <div className="relative">
                <LockKeyhole className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  id="password"
                  type={show ? "text" : "password"}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="password"
                  autoComplete="current-password"
                  required
                  className="h-11 rounded-xl pl-9 pr-10"
                />
                <button
                  type="button"
                  onClick={() => setShow((s) => !s)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-[#7B1E28]"
                  aria-label={show ? "Sembunyikan password" : "Tampilkan password"}
                >
                  {show ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
                </button>
              </div>
            </div>
            <Button
              type="submit"
              disabled={loading}
              className="h-12 w-full rounded-xl bg-gradient-to-r from-[#7B1E28] to-[#a32838] text-base font-bold text-white shadow-lg shadow-[#7B1E28]/25"
            >
              {loading ? <Loader2 className="size-5 animate-spin" /> : <ShieldCheck className="size-5" />}
              {loading ? "Memeriksa…" : "Masuk Dashboard"}
            </Button>
          </form>

          <p className="mt-5 rounded-xl bg-amber-50 border border-amber-200 px-4 py-2.5 text-center text-xs leading-relaxed text-amber-800">
            Akun bawaan: <b>admin</b> / <b>admin123</b> — segera ganti password di menu
            <b> Pengaturan</b> setelah masuk.
          </p>
        </div>

        <p className="mt-6 text-center text-xs text-white/50">
          © {new Date().getFullYear()} SMK Al Aitaam — Sistem PPDB Online
        </p>
      </motion.div>
    </div>
  );
}
