"use client";

import { Suspense, useEffect, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Mail, Lock, AlertCircle } from "lucide-react";
import { AuthCard } from "@/components/auth/AuthCard";
import { AuthTextField } from "@/components/auth/AuthTextField";
import { Button } from "@/components/ui/Button";
import { useAuth } from "@/lib/auth/auth-provider";
import { apiPost, ApiError } from "@/lib/api/client";

function LoginContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirect = searchParams.get("redirect") || "/";
  const { refreshProfile } = useAuth();

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (searchParams.get("error") === "not-admin") {
      setError("That account doesn't have admin access.");
    }
  }, [searchParams]);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);

    if (!email.trim() || !password) {
      setError("Enter your email and password.");
      return;
    }

    setLoading(true);
    try {
      // verifyAdminCredentials() (see lib/db/services/auth.ts) already
      // rejects a correct password on a non-admin account server-side
      // — no separate "sign in, check is_admin, sign back out if not"
      // round-trip needed the way the direct-to-Supabase version did.
      await apiPost("/api/auth/login", { email: email.trim(), password });
      await refreshProfile();
      router.push(redirect);
      router.refresh();
    } catch (err) {
      setLoading(false);
      if (!(err instanceof ApiError)) {
        setError("Something went wrong. Please check your connection and try again.");
        return;
      }
      setError(err.status === 401 ? "Incorrect email or password." : err.message);
    }
  }

  return (
    <AuthCard title="SharedNet Admin" subtitle="Sign in to manage orders, users and packages">
      <form onSubmit={handleSubmit} className="flex flex-col gap-3.5">
        <AuthTextField
          label="Email"
          type="email"
          autoComplete="email"
          icon={Mail}
          placeholder="you@sharednet.pk"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
        <div>
          <AuthTextField
            label="Password"
            type="password"
            autoComplete="current-password"
            icon={Lock}
            placeholder="••••••••"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
          <Link href="/forgot-password" className="mt-2 inline-block text-xs font-semibold text-gold-bright">
            Forgot password?
          </Link>
        </div>

        {error && (
          <div className="flex items-start gap-2 rounded-xl bg-danger/10 px-3.5 py-2.5 text-xs text-danger">
            <AlertCircle size={14} className="mt-0.5 shrink-0" />
            {error}
          </div>
        )}

        <Button type="submit" fullWidth disabled={loading} className="mt-1">
          {loading ? "Signing in…" : "Sign In"}
        </Button>
      </form>

      <p className="mt-6 text-center text-[11px] text-paper/40">
        Admin accounts are created by promoting an existing account — there's no
        self-service sign-up here.
      </p>
    </AuthCard>
  );
}

export default function AdminLoginPage() {
  return (
    <Suspense fallback={null}>
      <LoginContent />
    </Suspense>
  );
}
