"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";

export default function AuthPage() {
  const [mode, setMode] = useState<"login" | "register">("login");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const router = useRouter();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      const res = await fetch(`/api/${mode}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password }),
      });

      if (!res.ok) {
        const msg = await res.text();
        throw new Error(msg || "Something went wrong");
      }

      const data = await res.json();
      localStorage.setItem("token", data.token);
      localStorage.setItem("username", data.username);
      router.push("/landing");
    } catch (err: unknown) {
      setError((err as Error).message ?? "Failed to authenticate");
    } finally {
      setLoading(false);
    }
  };

  return (
    <main className="relative flex min-h-screen items-center justify-center p-6">
      {/* Foreground content */}
      <div className="w-full max-w-sm space-y-8">
        <h1 className="text-center text-5xl sm:text-6xl md:text-7xl font-bold text-white drop-shadow-lg">
          FeedMee
        </h1>

        <Card className="glass-panel">
          <CardHeader className="text-center">
            <CardTitle className="text-xl font-semibold text-white">
              {mode === "login" ? "Login" : "Register"}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid gap-2">
                <Label htmlFor="username" className="text-white">
                  Username
                </Label>
                <Input
                  id="username"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  required
                  className="bg-white/60 text-black"
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="password" className="text-white">
                  Password
                </Label>
                <Input
                  id="password"
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  className="bg-white/60 text-black"
                />
              </div>
              <Button
                type="submit"
                className="btn-brand w-full"
                disabled={loading}
              >
                {loading
                  ? "Please wait…"
                  : mode === "login"
                  ? "Login"
                  : "Register"}
              </Button>
            </form>

            {error && (
              <p className="mt-3 text-sm text-red-400 text-center" role="alert">
                {error}
              </p>
            )}

            <p className="mt-4 text-sm text-center text-white">
              {mode === "login" ? (
                <>
                  Don&apos;t have an account?{" "}
                  <button
                    type="button"
                    className="text-blue-300 hover:underline"
                    onClick={() => setMode("register")}
                  >
                    Register
                  </button>
                </>
              ) : (
                <>
                  Already have an account?{" "}
                  <button
                    type="button"
                    className="text-blue-300 hover:underline"
                    onClick={() => setMode("login")}
                  >
                    Login
                  </button>
                </>
              )}
            </p>
          </CardContent>
        </Card>
      </div>
    </main>
  );
}
