"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { LogIn } from "lucide-react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { AuthProvider, useAuth } from "@/components/auth";
import { login } from "@/lib/api";

const schema = z.object({
  email: z.string().email(),
  password: z.string().min(8)
});

type LoginForm = z.infer<typeof schema>;

function LoginPanel() {
  const router = useRouter();
  const auth = useAuth();
  const form = useForm<LoginForm>({
    resolver: zodResolver(schema),
    defaultValues: { email: "admin@schubamed.de", password: "" }
  });

  async function onSubmit(values: LoginForm) {
    const result = await login(values.email, values.password);
    auth.setToken(result.access_token);
    router.push("/dashboard");
  }

  return (
    <main className="flex min-h-screen items-center justify-center bg-background px-4 py-10">
      <section className="w-full max-w-md rounded-lg border border-border bg-surface p-8 shadow-soft">
        <div className="mb-8">
          <p className="text-sm font-medium text-primary">Validation Suite</p>
          <h1 className="mt-2 text-3xl font-semibold text-text">Anmelden</h1>
          <p className="mt-3 text-sm leading-6 text-text-light">Sicherer Zugriff auf Atlas Workspace.</p>
        </div>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-5">
          <label className="block">
            <span className="text-sm font-medium text-text">E-Mail</span>
            <input
              type="email"
              className="mt-2 h-12 w-full rounded-lg border border-border bg-white px-4 outline-none transition focus:border-primary"
              {...form.register("email")}
            />
          </label>
          <label className="block">
            <span className="text-sm font-medium text-text">Passwort</span>
            <input
              type="password"
              className="mt-2 h-12 w-full rounded-lg border border-border bg-white px-4 outline-none transition focus:border-primary"
              {...form.register("password")}
            />
          </label>
          <button
            type="submit"
            className="flex h-12 w-full items-center justify-center gap-2 rounded-lg bg-primary px-5 font-semibold text-white shadow-soft transition hover:bg-primary-dark"
          >
            <LogIn className="h-5 w-5" />
            Einloggen
          </button>
        </form>
      </section>
    </main>
  );
}

export default function LoginPage() {
  return (
    <AuthProvider>
      <LoginPanel />
    </AuthProvider>
  );
}
