"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useLanguage } from "@/contexts/LanguageContext";
import { useAuth } from "@/contexts/AuthContext";
import { forgotPassword } from "@/lib/api/auth";
import { ApiError } from "@/lib/api";
import { toast } from "sonner";

type Mode = "login" | "register" | "forgot";

export default function Auth() {
  const { t } = useLanguage();
  const { login, register, logout, user } = useAuth();
  const router = useRouter();
  const [mode, setMode] = useState<Mode>("login");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [name, setName] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (user) router.replace("/");
  }, [user, router]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      if (mode === "login") {
        const profile = await login(email, password);
        if (profile.role === "admin") {
          logout();
          toast.error(t("auth.admin_not_allowed"));
          return;
        }
        toast.success(t("auth.login_success"));
        router.push("/");
      } else if (mode === "register") {
        const profile = await register(email, password, name);
        if (profile) {
          toast.success(t("auth.register_success"));
          router.push("/");
        } else {
          toast.success(t("auth.confirm_email"));
          router.push("/connexion");
        }
      } else {
        await forgotPassword(email);
        toast.success(t("auth.forgot_sent"));
        setMode("login");
        setEmail("");
      }
    } catch (err) {
      const msg = err instanceof ApiError ? err.message : t("auth.error");
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center py-12 px-4">
      <div className="w-full max-w-sm">
        <h1 className="font-serif text-3xl text-center mb-2">
          {mode === "login" ? t("auth.login") : mode === "register" ? t("auth.register") : t("auth.forgot_title")}
        </h1>
        <p className="text-sm text-muted-foreground text-center mb-8">
          {mode === "login"
            ? t("auth.login_subtitle")
            : mode === "register"
            ? t("auth.register_subtitle")
            : t("auth.forgot_subtitle")}
        </p>

        <form onSubmit={handleSubmit} className="space-y-4">
          {mode === "register" && (
            <div>
              <Label htmlFor="name">{t("auth.name")}</Label>
              <Input
                id="name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="mt-1"
                required
                minLength={2}
              />
            </div>
          )}
          <div>
            <Label htmlFor="email">{t("auth.email")}</Label>
            <Input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="mt-1"
              required
            />
          </div>
          {mode !== "forgot" && (
            <div>
              <div className="flex items-center justify-between mb-1">
                <Label htmlFor="password">{t("auth.password")}</Label>
                {mode === "login" && (
                  <Button
                    type="button"
                    variant="link"
                    className="h-auto p-0 text-xs text-muted-foreground hover:text-primary"
                    onClick={() => { setMode("forgot"); setPassword(""); }}
                  >
                    {t("auth.forgot_link")}
                  </Button>
                )}
              </div>
              <Input
                id="password"
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                minLength={8}
              />
            </div>
          )}
          <Button type="submit" className="w-full" size="lg" disabled={loading}>
            {loading
              ? t("auth.loading")
              : mode === "login"
              ? t("auth.login")
              : mode === "register"
              ? t("auth.register")
              : t("auth.forgot_send")}
          </Button>
        </form>

        {mode === "forgot" ? (
          <p className="text-center text-sm text-muted-foreground mt-6">
            <Button
              type="button"
              variant="link"
              onClick={() => setMode("login")}
              className="text-primary hover:underline font-medium"
            >
              {t("auth.back_to_login")}
            </Button>
          </p>
        ) : (
          <p className="text-center text-sm text-muted-foreground mt-6">
            {mode === "login" ? t("auth.no_account") : t("auth.has_account")}{" "}
            <Button
              type="button"
              variant="link"
              onClick={() => setMode(mode === "login" ? "register" : "login")}
              className="text-primary hover:underline font-medium"
            >
              {mode === "login" ? t("auth.register") : t("auth.login")}
            </Button>
          </p>
        )}
      </div>
    </div>
  );
}
