import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { apiUrl } from "@/lib/api";

type LoginFormValues = {
  email: string;
  password: string;
};

export function LoginForm() {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<LoginFormValues>({
    defaultValues: {
      email: "admin@example.com",
      password: "",
    },
  });
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const loggedIn = localStorage.getItem("adminLoggedIn") === "true";
    if (loggedIn) {
      window.location.href = "/dashboard";
    }
  }, []);

  async function onSubmit(values: LoginFormValues) {
    setMessage(null);
    setError(null);

    try {
      const response = await fetch(apiUrl("/api/login"), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(values),
      });

      const data = await response.json();
      if (!response.ok) {
        setError(data.message ?? "Login failed.");
        return;
      }

      localStorage.setItem("adminLoggedIn", "true");
      window.location.href = "/dashboard";
    } catch (err) {
      setError("Unable to connect to the login server. Make sure it is running.");
    }
  }

  return (
    <section className="mx-auto max-w-lg rounded-3xl border border-border bg-background/90 p-8 shadow-soft sm:p-10">
      <div className="mb-8">
        <p className="text-sm uppercase tracking-[0.25em] text-muted-foreground">Member login</p>
        <h2 className="mt-3 text-3xl font-semibold text-foreground">Sign in to your account</h2>
        <p className="mt-2 text-sm text-muted-foreground">
          Use the seeded admin <strong>admin@example.com</strong> with password <strong>AdminPass2026!</strong>.
        </p>
      </div>

      <form className="space-y-6" onSubmit={handleSubmit(onSubmit)}>
        <label className="block text-sm font-medium text-foreground">
          Email
          <input
            type="email"
            placeholder="you@example.com"
            {...register("email", { required: "Email is required." })}
            className="mt-2 w-full rounded-xl border border-input bg-background px-4 py-3 text-sm text-foreground outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/20"
          />
          {errors.email && <p className="mt-2 text-xs text-destructive">{errors.email.message}</p>}
        </label>

        <label className="block text-sm font-medium text-foreground">
          Password
          <input
            type="password"
            placeholder="••••••••"
            {...register("password", { required: "Password is required." })}
            className="mt-2 w-full rounded-xl border border-input bg-background px-4 py-3 text-sm text-foreground outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/20"
          />
          {errors.password && <p className="mt-2 text-xs text-destructive">{errors.password.message}</p>}
        </label>

        <button
          type="submit"
          disabled={isSubmitting}
          className="inline-flex w-full items-center justify-center rounded-2xl bg-primary px-5 py-3 text-sm font-semibold text-primary-foreground transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-70"
        >
          {isSubmitting ? "Signing in..." : "Sign in"}
        </button>
      </form>

      {message && <p className="mt-5 rounded-2xl border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-800">{message}</p>}
      {error && <p className="mt-5 rounded-2xl border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">{error}</p>}
    </section>
  );
}
