import { createSignal, Show } from "solid-js";
import { Title } from "@solidjs/meta";
import { useNavigate } from "@solidjs/router";
import { AuthLayout, SocialAuthButtons } from "~/components/auth";
import { Input } from "~/components/ui";
import { Button } from "~/components/ui";
import { login } from "~/lib/auth";

const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

interface FormErrors {
  email?: string;
  password?: string;
}

export default function LoginPage() {
  const navigate = useNavigate();
  const [email, setEmail] = createSignal("");
  const [password, setPassword] = createSignal("");
  const [rememberMe, setRememberMe] = createSignal(false);
  const [errors, setErrors] = createSignal<FormErrors>({});
  const [loading, setLoading] = createSignal(false);
  const [serverError, setServerError] = createSignal("");

  function validate(): boolean {
    const errs: FormErrors = {};
    if (!email().trim()) errs.email = "Email is required";
    else if (!EMAIL_REGEX.test(email())) errs.email = "Invalid email format";
    if (!password()) errs.password = "Password is required";
    setErrors(errs);
    return Object.keys(errs).length === 0;
  }

  async function handleSubmit(e: Event) {
    e.preventDefault();
    setServerError("");
    if (!validate()) return;
    setLoading(true);
    try {
      await login(email(), password(), rememberMe());
      navigate("/dashboard", { replace: true });
    } catch {
      setServerError("Invalid email or password. Please try again.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <AuthLayout>
      <Title>Sign In — ShieldAI</Title>
      <div class="flex flex-col gap-6">
        <div class="text-center">
          <h2 class="text-2xl font-bold text-[var(--color-text-primary)]">
            Welcome back
          </h2>
          <p class="text-sm text-[var(--color-text-secondary)] mt-1">
            Sign in to your account
          </p>
        </div>

        <Show when={serverError()}>
          <div
            class="px-4 py-3 rounded-lg text-sm bg-[var(--color-error-bg)] text-[var(--color-error)] border border-[var(--color-error)]/30"
            role="alert"
          >
            {serverError()}
          </div>
        </Show>

        <form onSubmit={handleSubmit} class="flex flex-col gap-4">
          <Input
            label="Email"
            type="email"
            name="email"
            placeholder="you@example.com"
            value={email()}
            onInput={(e) => setEmail(e.currentTarget.value)}
            error={errors().email}
            required
          />
          <Input
            label="Password"
            type="password"
            name="password"
            placeholder="Enter your password"
            value={password()}
            onInput={(e) => setPassword(e.currentTarget.value)}
            error={errors().password}
            required
          />
          <div class="flex items-center justify-between">
            <label class="flex items-center gap-2 text-sm text-[var(--color-text-secondary)] cursor-pointer">
              <input
                type="checkbox"
                checked={rememberMe()}
                onChange={() => setRememberMe(!rememberMe())}
                class="rounded border-[var(--color-border)] text-[var(--color-brand-primary)] focus:ring-[var(--color-brand-primary)]"
              />
              Remember me
            </label>
            <a
              href="/forgot-password"
              class="text-sm text-[var(--color-brand-primary)] hover:text-[var(--color-brand-primary-light)] transition-colors"
            >
              Forgot password?
            </a>
          </div>
          <Button type="submit" loading={loading()} class="w-full">
            Sign In
          </Button>
        </form>

        <div class="relative">
          <div class="absolute inset-0 flex items-center">
            <div class="w-full border-t border-[var(--color-border)]" />
          </div>
          <div class="relative flex justify-center text-xs uppercase">
            <span class="bg-[var(--gradient-card-start)] px-2 text-[var(--color-text-tertiary)]">
              Or continue with
            </span>
          </div>
        </div>

        <SocialAuthButtons />

        <p class="text-center text-sm text-[var(--color-text-secondary)]">
          Don't have an account?{" "}
          <a
            href="/signup"
            class="text-[var(--color-brand-primary)] hover:text-[var(--color-brand-primary-light)] font-medium transition-colors"
          >
            Sign up
          </a>
        </p>
      </div>
    </AuthLayout>
  );
}
