"use client";

import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useAuthContext } from "@/hooks/auth-context";

export default function LoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [remember, setRemember] = useState(true);
  const [error, setError] = useState("");
  const { checkSession, login, loading } = useAuthContext();
  const [checking, setChecking] = useState(true);

  useEffect(() => {
    let active = true;
    async function runCheckSession() {
      try {
        const user = await checkSession();
        if (!active) return;

        if (user) {
          router.replace("/");
          return;
        }
      } finally {
        if (active) setChecking(false);
      }
    }
    runCheckSession();
    return () => {
      active = false;
    };
  }, [router, checkSession]);

  function validate() {
    if (!email.trim()) return "Email is required";
    if (!email.includes("@")) return "Enter a valid email";
    if (!password) return "Password is required";
    return "";
  }

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const validationError = validate();
    if (validationError) {
      setError(validationError);
      return;
    }
    setError("");
    const result = await login({ email, password, remember });

    if (!result.ok) {
      setError(result.error || "Login failed");
      return;
    }

    router.replace("/");
  }

  return (
    <div className="mx-auto max-w-sm space-y-4">
      <div className="flex items-center gap-2">
        <img
          src="/icons/navbar-settings.png"
          alt=""
          className="h-7 w-7 rounded-lg object-cover"
        />
        <h1 className="text-2xl font-semibold">Login</h1>
      </div>
      {checking ? (
        <div className="panel panel-accent p-4 text-muted">
          Checking session...
        </div>
      ) : null}
      <form
        onSubmit={onSubmit}
        className="space-y-3 panel panel-accent p-4"
      >
        <label className="block text-sm text-muted">
          Email
          <input
            type="email"
            className="mt-1 w-full input-base px-3 py-2 text-sm"
            value={email}
            onChange={e => setEmail(e.target.value)}
            autoComplete="email"
            required
            disabled={loading || checking}
          />
        </label>
        <label className="block text-sm text-muted">
          Password
          <input
            type="password"
            className="mt-1 w-full input-base px-3 py-2 text-sm"
            value={password}
            onChange={e => setPassword(e.target.value)}
            autoComplete="current-password"
            required
            disabled={loading || checking}
          />
        </label>
        <div className="flex items-center justify-between text-sm text-muted">
          <label className="flex items-center gap-2">
            <input
              type="checkbox"
              className="h-4 w-4 rounded border-accent-weak bg-input"
              checked={remember}
              onChange={e => setRemember(e.target.checked)}
              disabled={loading || checking}
            />
            Remember me
          </label>
          <a
            href="#"
            onClick={e => e.preventDefault()}
            className="text-[color:var(--color-accent)]"
          >
            Forgot password?
          </a>
        </div>
        {error ? <div className="text-sm text-red-400">{error}</div> : null}
        <button
          type="submit"
          disabled={loading || checking}
          className="w-full rounded-lg btn-accent px-3 py-2 text-sm font-semibold disabled:opacity-60"
        >
          {loading ? "Signing in..." : "Sign in"}
        </button>
        <div className="text-center text-sm text-muted">
          No account?{" "}
          <a href="/register" className="text-[color:var(--color-accent)]">
            Register
          </a>
        </div>
      </form>
    </div>
  );
}
