import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { LogIn, UserPlus, Loader2 } from "lucide-react";
import { useAuthStore } from "../stores/authStore";
import { useProfileStore } from "../stores/profileStore";
import { ApiError } from "../lib/apiClient";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Card, CardContent } from "../components/ui/card";
import { PageHeader } from "../components/PageHeader";

const schema = z.object({
  email: z.string().email("Email invalide"),
  password: z.string().min(8, "8 caractères minimum"),
  username: z
    .string()
    .min(3, "3 caractères minimum")
    .regex(/^[a-zA-Z0-9_.-]+$/, "Lettres, chiffres, . _ - uniquement")
    .optional()
    .or(z.literal("")),
});

type FormValues = z.infer<typeof schema>;

const ERROR_MESSAGES: Record<string, string> = {
  email_taken: "Cet email est déjà utilisé.",
  username_taken: "Ce pseudo est déjà pris.",
  invalid_credentials: "Email ou mot de passe incorrect.",
};

export default function Auth() {
  const navigate = useNavigate();
  const [mode, setMode] = useState<"login" | "register">("login");
  const [serverError, setServerError] = useState<string | null>(null);
  const { login, register: registerAccount } = useAuthStore();
  const activeProfile = useProfileStore((s) => s.activeProfile);

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<FormValues>({ resolver: zodResolver(schema) });

  const onSubmit = async (values: FormValues) => {
    setServerError(null);
    try {
      if (mode === "login") {
        await login(values.email, values.password);
      } else {
        await registerAccount({
          email: values.email,
          password: values.password,
          username: values.username || undefined,
          // Prefer the username as public display name (the local profile name
          // defaults to "Moi" and would be identical for everyone).
          displayName: values.username || activeProfile?.name,
        });
      }
      navigate("/settings");
    } catch (err) {
      const code = err instanceof ApiError ? err.message : "request_failed";
      setServerError(
        ERROR_MESSAGES[code] ||
          "Une erreur est survenue. Vérifiez votre connexion.",
      );
    }
  };

  return (
    <div className="p-5 space-y-5 relative z-10">
      <PageHeader
        title={mode === "login" ? "Connexion" : "Créer un compte"}
        back
      />

      <p className="text-sm text-muted-foreground px-2">
        {mode === "login"
          ? "Connectez-vous pour synchroniser vos parties entre vos appareils."
          : `Créez un compte pour sauvegarder et synchroniser le profil « ${activeProfile?.name ?? ""} ».`}
      </p>

      <Card className="border-0 shadow-lg bg-background/90 backdrop-blur-md">
        <CardContent className="p-5">
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            <div className="space-y-1">
              <label className="text-sm font-bold px-1">Email</label>
              <Input
                type="email"
                autoComplete="email"
                placeholder="vous@exemple.fr"
                className="h-12"
                {...register("email")}
              />
              {errors.email && (
                <p className="text-xs text-destructive px-1">
                  {errors.email.message}
                </p>
              )}
            </div>

            {mode === "register" && (
              <div className="space-y-1">
                <label className="text-sm font-bold px-1">
                  Pseudo (optionnel)
                </label>
                <Input
                  autoComplete="username"
                  placeholder="pour vos futurs amis"
                  className="h-12"
                  {...register("username")}
                />
                {errors.username && (
                  <p className="text-xs text-destructive px-1">
                    {errors.username.message}
                  </p>
                )}
              </div>
            )}

            <div className="space-y-1">
              <label className="text-sm font-bold px-1">Mot de passe</label>
              <Input
                type="password"
                autoComplete={
                  mode === "login" ? "current-password" : "new-password"
                }
                placeholder="••••••••"
                className="h-12"
                {...register("password")}
              />
              {errors.password && (
                <p className="text-xs text-destructive px-1">
                  {errors.password.message}
                </p>
              )}
            </div>

            {serverError && (
              <p className="text-sm text-destructive font-medium bg-destructive/10 rounded-xl p-3">
                {serverError}
              </p>
            )}

            <Button
              type="submit"
              disabled={isSubmitting}
              className="w-full h-14 rounded-[1.5rem] font-black text-lg shadow-lg"
            >
              {isSubmitting ? (
                <Loader2 className="w-5 h-5 mr-2 animate-spin" />
              ) : mode === "login" ? (
                <LogIn className="w-5 h-5 mr-2" />
              ) : (
                <UserPlus className="w-5 h-5 mr-2" />
              )}
              {mode === "login" ? "Se connecter" : "Créer le compte"}
            </Button>
          </form>
        </CardContent>
      </Card>

      <button
        onClick={() => {
          setServerError(null);
          setMode(mode === "login" ? "register" : "login");
        }}
        className="w-full text-center text-sm font-bold text-primary py-2"
      >
        {mode === "login"
          ? "Pas encore de compte ? Créez-en un"
          : "Déjà un compte ? Connectez-vous"}
      </button>
    </div>
  );
}
