"use client";

import { useState, FormEvent } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { Spinner, inputCls, btnPrimary, Field } from "@/components/ui";

export default function LoginPage() {
  const [email, setEmail] = useState("admin@macsoft.co.ke");
  const [password, setPassword] = useState("admin123");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError("");
    try {
      const res = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Login failed");
      router.push("/dashboard");
      router.refresh();
    } catch (err) {
      setError((err as Error).message);
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen flex-col justify-center bg-gradient-to-br from-[#0b1e3f] via-[#12305f] to-[#0b1e3f] px-4 py-10">
      <div className="mx-auto w-full max-w-md">
        <div className="mb-6 text-center">
          <Image src="/logo.png" alt="Macsoft ERP" width={160} height={160} className="mx-auto rounded-2xl bg-white/95 p-2 shadow-xl" priority />
          <h1 className="mt-5 text-2xl font-bold text-white">Welcome back</h1>
          <p className="mt-1 text-sm text-blue-200">Sign in to your Macsoft ERP workspace</p>
        </div>

        <form onSubmit={submit} className="rounded-2xl bg-white p-6 shadow-2xl sm:p-8">
          {error && (
            <div className="mb-4 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-700">{error}</div>
          )}
          <div className="space-y-4">
            <Field label="Email address">
              <input type="email" className={inputCls} value={email} onChange={(e) => setEmail(e.target.value)} required autoComplete="email" />
            </Field>
            <Field label="Password">
              <input type="password" className={inputCls} value={password} onChange={(e) => setPassword(e.target.value)} required autoComplete="current-password" />
            </Field>
            <button type="submit" disabled={loading} className={`${btnPrimary} w-full py-2.5`}>
              {loading && <Spinner className="h-4 w-4 text-white" />}
              {loading ? "Signing in…" : "Sign in"}
            </button>
          </div>
          <div className="mt-5 rounded-lg bg-slate-50 px-3 py-2.5 text-center text-xs text-slate-500">
            Demo credentials — <span className="font-semibold text-slate-700">admin@macsoft.co.ke</span> /{" "}
            <span className="font-semibold text-slate-700">admin123</span>
          </div>
        </form>
        <p className="mt-6 text-center text-xs text-blue-300/70">
          © {new Date().getFullYear()} Macsoft Ltd · Payroll · HR · Invoicing · M-Pesa
        </p>
      </div>
    </div>
  );
}
