"use client";

import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useState, type FormEvent } from "react";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardBody, CardFooter, CardHeader } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { ROUTES } from "@/config/routes.config";

interface LoginResponse {
  success: boolean;
  data?: { user: { role: string } };
  message?: string;
  code?: string;
}

export function LoginForm({ admin = false }: { admin?: boolean }) {
  const router = useRouter();
  const params = useSearchParams();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const queryError = params.get("error");
  const nextParam = params.get("next");
  const initialError =
    queryError === "suspended"
      ? "Your account is suspended. Please contact support."
      : queryError
        ? "We could not sign you in. Please try again."
        : null;

  const [serverError, setServerError] = useState<string | null>(initialError);

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);
    setServerError(null);
    setSubmitting(true);

    try {
      const res = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });
      const json = (await res.json()) as LoginResponse;
      if (!res.ok || !json.success) {
        if (json.code === "SUSPENDED_ACCOUNT") {
          setServerError(
            json.message ??
              "Your account is suspended. Please contact support.",
          );
        } else if (json.code === "VALIDATION_ERROR") {
          setServerError(json.message ?? "Please check your input.");
        } else {
          setServerError(json.message ?? "Invalid email or password.");
        }
        return;
      }
      const role = json.data?.user.role ?? "user";
      const isAdminRole = role === "admin" || role === "super_admin";

      if (admin && !isAdminRole) {
        setServerError(
          "You do not have administrator access. Please use the regular sign-in page.",
        );
        return;
      }

      const safeNext = nextParam && nextParam.startsWith("/") ? nextParam : null;
      const target = admin
        ? safeNext ?? ROUTES.adminHome
        : safeNext ?? ROUTES.dashboard;
      router.replace(target);
      router.refresh();
    } catch {
      setServerError("Network error. Please try again.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <Card>
      <CardHeader>
        <h1 className="text-xl font-semibold tracking-tight text-foreground">
          {admin ? "Admin sign in" : "Sign in"}
        </h1>
        <p className="mt-1 text-sm text-muted">
          {admin
            ? "Use your administrator credentials."
            : "Welcome back. Please enter your details."}
        </p>
      </CardHeader>
      <CardBody>
        <form className="space-y-4" onSubmit={handleSubmit} noValidate>
          {serverError ? <Alert tone="error">{serverError}</Alert> : null}
          <Input
            label="Email"
            type="email"
            name="email"
            autoComplete="email"
            required
            value={email}
            onChange={(e) => {
              setEmail(e.target.value);
              setError(null);
            }}
            error={error ?? undefined}
            placeholder="you@example.com"
          />
          <Input
            label="Password"
            type="password"
            name="password"
            autoComplete={admin ? "current-password" : "current-password"}
            required
            value={password}
            onChange={(e) => {
              setPassword(e.target.value);
              setError(null);
            }}
            placeholder="••••••••"
          />
          <div className="flex items-center justify-between text-sm">
            <Link
              href={ROUTES.forgotPassword}
              className="text-primary hover:text-primary-hover"
            >
              Forgot password?
            </Link>
            {!admin ? (
              <Link
                href={ROUTES.register}
                className="text-primary hover:text-primary-hover"
              >
                Create an account
              </Link>
            ) : null}
          </div>
          <Button type="submit" fullWidth isLoading={submitting}>
            {submitting ? "Signing in…" : "Sign in"}
          </Button>
        </form>
      </CardBody>
      <CardFooter>
        <div className="space-y-3 w-full">
          <div className="relative">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-border" />
            </div>
            <div className="relative flex justify-center text-xs uppercase">
              <span className="bg-surface px-2 text-muted">Or</span>
            </div>
          </div>
          <p className="text-xs text-muted text-center">
            Google sign-in is disabled by default. Set
            <code className="mx-1 rounded bg-surface-muted px-1 py-0.5">
              AUTH_GOOGLE_ENABLED=true
            </code>
            and provide Google credentials in <code>.env</code>.
          </p>
        </div>
      </CardFooter>
    </Card>
  );
}
