"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useState } from "react";
import { Eye, EyeOff, KeyRound, Loader2, LogIn, ShieldCheck, User } from "lucide-react";
import { api } from "@/lib/client";
import { Button, ErrorNote, Input } from "@/components/ui";

function LoginForm() {
  const router = useRouter();
  const params = useSearchParams();
  const next = params.get("next") || "/admin";
  const [identifier, setIdentifier] = useState("admin@ispdigital.net");
  const [password, setPassword] = useState("Admin@123");
  const [show, setShow] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const submit = async (event: React.FormEvent) => {
    event.preventDefault();
    setBusy(true);
    setError(null);
    try {
      const result = await api<{ redirect: string }>("/api/auth/login", { method: "POST", json: { identifier, password } });
      router.replace(next && next !== "/admin" ? next : result.redirect || "/admin");
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Login failed");
      setBusy(false);
    }
  };

  return (
    <form onSubmit={submit} className="glass-strong animate-fade-up w-full rounded-3xl p-6 sm:p-8">
      <div className="mb-6 flex items-center gap-3">
        <span className="grid h-12 w-12 place-items-center rounded-2xl bg-gradient-to-br from-brand-500 to-cyan-400 text-base font-bold text-ink-950">IS</span>
        <div>
          <h1 className="text-lg font-bold text-slate-50">ISP DIGITAL</h1>
          <p className="text-xs text-slate-400">Billing · MikroTik · Support automation</p>
        </div>
      </div>

      <h2 className="text-base font-semibold text-slate-100">Sign in to your account</h2>
      <p className="mt-1 text-xs text-slate-500">Staff, managers and customers use the same secure gateway.</p>

      <div className="mt-5 space-y-4">
        <div>
          <label className="label">Email or username</label>
          <div className="relative">
            <User className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500" />
            <Input value={identifier} onChange={(e) => setIdentifier(e.target.value)} className="pl-9" autoComplete="username" required />
          </div>
        </div>
        <div>
          <label className="label">Password</label>
          <div className="relative">
            <KeyRound className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500" />
            <Input
              type={show ? "text" : "password"}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="pl-9 pr-10"
              autoComplete="current-password"
              required
            />
            <button type="button" onClick={() => setShow((v) => !v)} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300">
              {show ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </button>
          </div>
        </div>

        <ErrorNote message={error} />

        <Button type="submit" size="lg" className="w-full" loading={busy} icon={!busy ? <LogIn className="h-4 w-4" /> : <Loader2 className="h-4 w-4 animate-spin" />}>
          {busy ? "Verifying…" : "Sign in"}
        </Button>
      </div>

      <div className="mt-6 rounded-xl border border-white/8 bg-white/4 p-3 text-[11px] leading-relaxed text-slate-400">
        <p className="mb-1 flex items-center gap-1.5 font-semibold text-slate-300">
          <ShieldCheck className="h-3.5 w-3.5 text-emerald-400" /> Demo credentials
        </p>
        <p>Staff — admin@ispdigital.net / Admin@123 (also: superadmin@, manager@, support@)</p>
        <p className="mt-1">Customer portal — karim0001@customer.ispdigital.net / Pass@1001</p>
      </div>
    </form>
  );
}

export default function LoginPage() {
  return (
    <main className="flex min-h-screen items-center justify-center px-4 py-10">
      <div className="w-full max-w-md">
        <Suspense fallback={<div className="skeleton h-96 w-full rounded-3xl" />}>
          <LoginForm />
        </Suspense>
        <p className="mt-6 text-center text-[11px] text-slate-600">Protected by session hardening, rate limiting and audit logging.</p>
      </div>
    </main>
  );
}
