"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Eye, EyeOff, ShieldCheck } from "lucide-react";

export default function LoginPage() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [logoUrl, setLogoUrl] = useState("");
  const router = useRouter();

  useEffect(() => {
    fetch("/api/settings")
      .then(res => res.json())
      .then(json => {
        if (json.success && json.data.logo_url) {
          setLogoUrl(json.data.logo_url);
        }
      });
  }, []);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setLoading(true);

    try {
      const res = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password }),
      });

      const data = await res.json();

      if (data.success) {
        router.push("/admin/dashboard");
        router.refresh();
      } else {
        setError(data.error || "Invalid username or password.");
      }
    } catch (err) {
      setError("Could not reach the server. Try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="h-screen bg-slate-50 text-[#044f54] flex flex-col items-center justify-center p-6 relative overflow-hidden select-none font-sans">
      {/* Scanline overlay */}
      <div className="absolute inset-0 pointer-events-none bg-[repeating-linear-gradient(0deg,transparent,transparent_2px,rgba(4,79,84,0.03) 2px,rgba(4,79,84,0.03) 4px)]"></div>
      
      <div className="z-10 w-full max-w-md animate-in fade-in zoom-in duration-500">
        <div className="bg-white border border-[#044f54]/20 p-8 rounded-lg shadow-2xl relative overflow-hidden">
          <div className="absolute top-0 right-0 p-1 opacity-10">
            <div className="w-4 h-4 border-t border-r border-[#044f54]"></div>
          </div>
          
          <div className="text-center mb-10">
            {logoUrl ? (
              <img src={logoUrl} alt="Logo" className="h-20 w-auto object-contain mx-auto mb-6" />
            ) : (
              <div className="w-20 h-20 bg-[#044f54] text-white rounded flex items-center justify-center mx-auto mb-6 shadow-xl shadow-[#044f54]/20 border border-white/10 relative overflow-hidden group">
                <div className="absolute inset-0 bg-white/5 opacity-0 group-hover:opacity-100 transition-opacity animate-pulse"></div>
                <ShieldCheck size={40} className="relative z-10" />
              </div>
            )}
            <h1 className="text-2xl font-semibold tracking-tight text-[#044f54]">Sign in</h1>
            <p className="text-sm text-[#044f54]/55 mt-2">Admin dashboard — use your RMS credentials.</p>
          </div>

          {error && (
            <div className="mb-8 p-4 bg-red-50 text-red-800 border border-red-100 rounded-lg text-sm text-center animate-in shake duration-300">
              {error}
            </div>
          )}

          <form onSubmit={handleLogin} className="space-y-6">
            <div className="space-y-1.5">
              <label className="text-sm font-medium text-[#044f54]/80" htmlFor="login-username">
                Username
              </label>
              <div className="relative">
                <input
                  id="login-username"
                  type="text"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  className="w-full px-4 py-3 bg-slate-50 border border-[#044f54]/10 rounded-lg text-sm focus:border-[#044f54]/40 focus:ring-2 focus:ring-[#044f54]/10 outline-none transition-all text-[#044f54]"
                  placeholder="Enter your username"
                  autoComplete="username"
                  required
                />
              </div>
            </div>
            
            <div className="space-y-1.5">
              <label className="text-sm font-medium text-[#044f54]/80" htmlFor="login-password">
                Password
              </label>
              <div className="relative">
                <input
                  id="login-password"
                  type={showPassword ? "text" : "password"}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="w-full px-4 py-3 bg-slate-50 border border-[#044f54]/10 rounded-lg text-sm focus:border-[#044f54]/40 focus:ring-2 focus:ring-[#044f54]/10 outline-none transition-all pr-12 text-[#044f54]"
                  placeholder="Enter your password"
                  autoComplete="current-password"
                  required
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-[#044f54]/30 hover:text-[#044f54] transition-colors"
                >
                  {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                </button>
              </div>
            </div>

            <button
              type="submit"
              disabled={loading}
              className="w-full bg-[#044f54] text-white font-semibold py-3.5 rounded-lg text-sm shadow-lg shadow-[#044f54]/20 hover:bg-[#044f54]/90 disabled:opacity-50 transition-all flex items-center justify-center gap-2"
            >
              {loading ? (
                <>
                  <span className="inline-block w-4 h-4 border-2 border-white/25 border-t-white rounded-full animate-spin" aria-hidden />
                  Signing in…
                </>
              ) : (
                "Login"
              )}
            </button>
          </form>
        </div>
        
        <p className="mt-10 text-center text-xs text-[#044f54]/40">
          Encrypted HTTPS session
        </p>
      </div>
    </div>
  );
}
