"use client";

import React, { Suspense, useState, useTransition } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { z } from "zod";
import { toast } from "sonner";
import { authClient } from "@/lib/auth/client";
import { cn } from "@/lib/utils";
import { Eye, EyeOff, Loader2, AlertCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

// ---------------------------------------------------------------------------
// Validation schema
// ---------------------------------------------------------------------------
const loginSchema = z.object({
  email: z.string().email("Please enter a valid email address"),
  password: z.string().min(1, "Password is required"),
});

type LoginFormValues = z.infer<typeof loginSchema>;
type FieldErrors = Partial<Record<keyof LoginFormValues, string>>;

// ---------------------------------------------------------------------------
// CubeAdmin logo (duplicated from sidebar so this page is self-contained)
// ---------------------------------------------------------------------------
function CubeIcon({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 32 32"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      className={className}
      aria-hidden="true"
    >
      <polygon points="16,4 28,10 16,16 4,10" fill="#059669" opacity="0.9" />
      <polygon points="4,10 16,16 16,28 4,22" fill="#047857" opacity="0.95" />
      <polygon points="28,10 16,16 16,28 28,22" fill="#10b981" opacity="0.85" />
      <polyline
        points="4,10 16,4 28,10 16,16 4,10"
        stroke="#34d399"
        strokeWidth="0.75"
        strokeLinejoin="round"
        fill="none"
        opacity="0.6"
      />
      <line
        x1="16" y1="16" x2="16" y2="28"
        stroke="#34d399"
        strokeWidth="0.75"
        opacity="0.4"
      />
    </svg>
  );
}

// ---------------------------------------------------------------------------
// Form field component
// ---------------------------------------------------------------------------
interface FormFieldProps {
  id: string;
  label: string;
  type?: string;
  value: string;
  onChange: (value: string) => void;
  error?: string;
  placeholder?: string;
  autoComplete?: string;
  disabled?: boolean;
  children?: React.ReactNode; // for additional elements (e.g., show/hide button)
  className?: string;
}

function FormField({
  id,
  label,
  type = "text",
  value,
  onChange,
  error,
  placeholder,
  autoComplete,
  disabled,
  children,
  className,
}: FormFieldProps) {
  return (
    <div className="flex flex-col gap-1.5">
      <Label htmlFor={id} className="text-xs font-medium text-zinc-300">
        {label}
      </Label>
      <div className={cn("relative", className)}>
        <Input
          id={id}
          type={type}
          value={value}
          onChange={(e) => onChange((e.target as HTMLInputElement).value)}
          placeholder={placeholder}
          autoComplete={autoComplete}
          disabled={disabled}
          aria-invalid={!!error}
          aria-describedby={error ? `${id}-error` : undefined}
          className={cn(
            "h-9 bg-zinc-900/60 border-zinc-800 text-zinc-100 placeholder:text-zinc-600 focus-visible:border-emerald-500/50 focus-visible:ring-emerald-500/20",
            children && "pr-10",
            error &&
              "border-red-500/50 focus-visible:border-red-500/50 focus-visible:ring-red-500/20"
          )}
        />
        {children}
      </div>
      {error && (
        <p
          id={`${id}-error`}
          className="flex items-center gap-1 text-xs text-red-400"
          role="alert"
        >
          <AlertCircle className="h-3 w-3 flex-shrink-0" />
          {error}
        </p>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Login page
// ---------------------------------------------------------------------------
function LoginPageInner() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get("callbackUrl") ?? "/dashboard";

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
  const [globalError, setGlobalError] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();

  function validate(): LoginFormValues | null {
    const result = loginSchema.safeParse({ email, password });
    if (!result.success) {
      const errors: FieldErrors = {};
      for (const issue of result.error.issues) {
        const field = issue.path[0] as keyof LoginFormValues;
        if (!errors[field]) errors[field] = issue.message;
      }
      setFieldErrors(errors);
      return null;
    }
    setFieldErrors({});
    return result.data;
  }

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setGlobalError(null);

    const values = validate();
    if (!values) return;

    startTransition(async () => {
      try {
        const { error } = await authClient.signIn.email({
          email: values.email,
          password: values.password,
        });

        if (error) {
          // Map common Better Auth error codes to friendly messages
          const message = mapAuthError(error.code ?? error.message ?? "");
          setGlobalError(message);
          return;
        }

        toast.success("Signed in successfully");
        router.push(callbackUrl);
        router.refresh();
      } catch (err) {
        setGlobalError("An unexpected error occurred. Please try again.");
        console.error("[login] Unexpected error:", err);
      }
    });
  }

  return (
    <div className="flex min-h-screen flex-col items-center justify-center bg-zinc-950 px-4">
      {/* Background grid pattern */}
      <div
        className="pointer-events-none fixed inset-0 bg-[size:32px_32px] opacity-[0.02]"
        style={{
          backgroundImage:
            "linear-gradient(to right, #ffffff 1px, transparent 1px), linear-gradient(to bottom, #ffffff 1px, transparent 1px)",
        }}
        aria-hidden="true"
      />

      {/* Subtle radial glow */}
      <div
        className="pointer-events-none fixed inset-0 flex items-center justify-center"
        aria-hidden="true"
      >
        <div className="h-[500px] w-[500px] rounded-full bg-emerald-500/5 blur-3xl" />
      </div>

      {/* Card */}
      <div className="relative z-10 w-full max-w-sm">
        {/* Logo + branding */}
        <div className="mb-8 flex flex-col items-center gap-3">
          <div className="flex h-14 w-14 items-center justify-center rounded-xl bg-zinc-900 ring-1 ring-white/[0.08]">
            <CubeIcon className="h-9 w-9" />
          </div>
          <div className="text-center">
            <h1 className="text-xl font-semibold tracking-tight text-zinc-100">
              CubeAdmin
            </h1>
            <p className="mt-0.5 text-xs text-zinc-500">
              Minecraft Server Management
            </p>
          </div>
        </div>

        {/* Form card */}
        <div className="rounded-xl bg-zinc-900/50 p-6 ring-1 ring-white/[0.08] backdrop-blur-sm">
          <div className="mb-5">
            <h2 className="text-base font-semibold text-zinc-100">
              Sign in to your account
            </h2>
            <p className="mt-1 text-xs text-zinc-500">
              Enter your credentials to access the admin panel
            </p>
          </div>

          {/* Global error banner */}
          {globalError && (
            <div
              className="mb-4 flex items-start gap-2.5 rounded-lg bg-red-500/10 px-3 py-2.5 ring-1 ring-red-500/20"
              role="alert"
              aria-live="assertive"
            >
              <AlertCircle className="mt-0.5 h-4 w-4 flex-shrink-0 text-red-400" />
              <p className="text-xs text-red-300">{globalError}</p>
            </div>
          )}

          <form onSubmit={handleSubmit} noValidate className="flex flex-col gap-4">
            {/* Email */}
            <FormField
              id="email"
              label="Email address"
              type="email"
              value={email}
              onChange={setEmail}
              error={fieldErrors.email}
              placeholder="admin@example.com"
              autoComplete="email"
              disabled={isPending}
            />

            {/* Password */}
            <FormField
              id="password"
              label="Password"
              type={showPassword ? "text" : "password"}
              value={password}
              onChange={setPassword}
              error={fieldErrors.password}
              placeholder="••••••••"
              autoComplete="current-password"
              disabled={isPending}
            >
              <button
                type="button"
                onClick={() => setShowPassword((v) => !v)}
                className="absolute right-2.5 top-1/2 -translate-y-1/2 rounded text-zinc-500 transition-colors hover:text-zinc-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/50"
                aria-label={showPassword ? "Hide password" : "Show password"}
                tabIndex={-1}
              >
                {showPassword ? (
                  <EyeOff className="h-3.5 w-3.5" />
                ) : (
                  <Eye className="h-3.5 w-3.5" />
                )}
              </button>
            </FormField>

            {/* Forgot password */}
            <div className="flex justify-end">
              <Link
                href="/forgot-password"
                className="text-xs text-zinc-500 transition-colors hover:text-zinc-300 focus-visible:outline-none focus-visible:underline"
              >
                Forgot password?
              </Link>
            </div>

            {/* Submit */}
            <Button
              type="submit"
              disabled={isPending}
              className="mt-1 h-9 w-full bg-emerald-600 text-white hover:bg-emerald-500 focus-visible:ring-emerald-500/50 disabled:opacity-60 border-0 font-medium"
            >
              {isPending ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Signing in…
                </>
              ) : (
                "Sign in"
              )}
            </Button>
          </form>
        </div>

        {/* Footer */}
        <p className="mt-6 text-center text-[11px] text-zinc-600">
          CubeAdmin &mdash; Secure server management
        </p>
      </div>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense>
      <LoginPageInner />
    </Suspense>
  );
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function mapAuthError(code: string): string {
  const normalised = code.toLowerCase();

  if (
    normalised.includes("invalid_credentials") ||
    normalised.includes("invalid credentials") ||
    normalised.includes("user_not_found") ||
    normalised.includes("incorrect password") ||
    normalised.includes("wrong password")
  ) {
    return "Invalid email or password. Please check your credentials and try again.";
  }

  if (normalised.includes("account_not_found")) {
    return "No account found with this email address.";
  }

  if (
    normalised.includes("email_not_verified") ||
    normalised.includes("email not verified")
  ) {
    return "Please verify your email address before signing in.";
  }

  if (
    normalised.includes("too_many_requests") ||
    normalised.includes("rate_limit")
  ) {
    return "Too many sign-in attempts. Please wait a few minutes before trying again.";
  }

  if (
    normalised.includes("account_disabled") ||
    normalised.includes("user_banned")
  ) {
    return "Your account has been disabled. Please contact your administrator.";
  }

  return "Sign in failed. Please try again or contact your administrator.";
}
