"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { AlertCircle, Eye, EyeOff, Loader2, Lock, Mail } from "lucide-react";
import { useRouter } from "next/navigation";
import { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { getApiBaseUrl } from "@/lib/api";
import { authErrorMessage, loginWithApi } from "@/lib/auth-api";
import { cn } from "@/lib/utils";

const loginSchema = z.object({
  email: z
    .string()
    .min(1, "L'e-mail est requis")
    .email("Adresse e-mail invalide"),
  password: z.string().min(1, "Le mot de passe est requis"),
});

type LoginValues = z.infer<typeof loginSchema>;

export function LoginForm() {
  const router = useRouter();
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [showPassword, setShowPassword] = useState(false);
  const [errorKey, setErrorKey] = useState(0);
  const formRef = useRef<HTMLFormElement>(null);

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<LoginValues>({
    resolver: zodResolver(loginSchema),
    defaultValues: { email: "", password: "" },
  });

  async function onSubmit(data: LoginValues) {
    setSubmitError(null);
    if (!getApiBaseUrl()) {
      setSubmitError(
        "URL de l'API manquante : ajoutez NEXT_PUBLIC_APP_API_URL dans .env.local."
      );
      setErrorKey((k) => k + 1);
      return;
    }
    try {
      const user = await loginWithApi({
        email: data.email,
        password: data.password,
      });
      const roleId = Number(user.role_id);
      const destination = roleId === 3 ? "/user" : "/admin";
      router.push(destination);
      router.refresh();
    } catch (err) {
      setSubmitError(authErrorMessage(err));
      setErrorKey((k) => k + 1);
    }
  }

  return (
    <form
      ref={formRef}
      onSubmit={handleSubmit(onSubmit)}
      className="space-y-5"
      noValidate
    >
      {/* Champ e-mail */}
      <div className="animate-fade-in-up space-y-1.5 delay-200">
        <Label
          htmlFor="email"
          className="text-sm font-medium text-foreground/80"
        >
          Adresse e-mail
        </Label>
        <div className="relative">
          <Mail className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground transition-colors" />
          <Input
            id="email"
            type="email"
            autoComplete="email"
            placeholder="vous@exemple.fr"
            aria-invalid={errors.email ? "true" : "false"}
            className={cn(
              "h-11 pl-10 transition-all duration-200",
              "focus:ring-2 focus:ring-primary/20 focus:border-primary",
              errors.email && "border-destructive focus:ring-destructive/20"
            )}
            {...register("email")}
          />
        </div>
        {errors.email && (
          <p
            className="animate-fade-in flex items-center gap-1.5 text-xs text-destructive"
            role="alert"
          >
            <AlertCircle className="h-3.5 w-3.5 shrink-0" />
            {errors.email.message}
          </p>
        )}
      </div>

      {/* Champ mot de passe */}
      <div className="animate-fade-in-up space-y-1.5 delay-300">
        <div className="flex items-center justify-between">
          <Label
            htmlFor="password"
            className="text-sm font-medium text-foreground/80"
          >
            Mot de passe
          </Label>
          <button
            type="button"
            onClick={(e) => e.preventDefault()}
            className="text-xs text-muted-foreground transition-colors hover:text-primary focus:outline-none"
            tabIndex={-1}
          >
            Mot de passe oublié ?
          </button>
        </div>
        <div className="relative">
          <Lock className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            id="password"
            type={showPassword ? "text" : "password"}
            autoComplete="current-password"
            placeholder="••••••••"
            aria-invalid={errors.password ? "true" : "false"}
            className={cn(
              "h-11 pl-10 pr-11 transition-all duration-200",
              "focus:ring-2 focus:ring-primary/20 focus:border-primary",
              errors.password && "border-destructive focus:ring-destructive/20"
            )}
            {...register("password")}
          />
          <button
            type="button"
            onClick={() => setShowPassword((v) => !v)}
            aria-label={
              showPassword ? "Masquer le mot de passe" : "Afficher le mot de passe"
            }
            className="absolute right-3 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40"
          >
            {showPassword ? (
              <EyeOff className="h-4 w-4" />
            ) : (
              <Eye className="h-4 w-4" />
            )}
          </button>
        </div>
        {errors.password && (
          <p
            className="animate-fade-in flex items-center gap-1.5 text-xs text-destructive"
            role="alert"
          >
            <AlertCircle className="h-3.5 w-3.5 shrink-0" />
            {errors.password.message}
          </p>
        )}
      </div>

      {/* Erreur de soumission */}
      {submitError && (
        <div
          key={errorKey}
          className="animate-shake flex items-start gap-2.5 rounded-lg border border-destructive/30 bg-destructive/8 px-4 py-3"
          role="alert"
        >
          <AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-destructive" />
          <p className="text-sm text-destructive">{submitError}</p>
        </div>
      )}

      {/* Bouton de connexion */}
      <div className="animate-fade-in-up delay-400 pt-1">
        <Button
          type="submit"
          className={cn(
            "relative h-11 w-full overflow-hidden text-sm font-semibold",
            "bg-primary transition-all duration-200",
            "hover:bg-primary/90 hover:shadow-lg hover:shadow-primary/25",
            "active:scale-[0.98]",
            isSubmitting && "cursor-not-allowed opacity-80"
          )}
          disabled={isSubmitting}
        >
          {isSubmitting ? (
            <span className="flex items-center gap-2">
              <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
              Connexion en cours…
            </span>
          ) : (
            <span className="flex items-center gap-2">
              Se connecter
            </span>
          )}
        </Button>
      </div>

      {/* Séparateur informatif */}
      <div className="animate-fade-in delay-500 flex items-center gap-3 pt-1">
        <div className="h-px flex-1 bg-border/60" />
        <span className="text-xs text-muted-foreground">accès sécurisé</span>
        <div className="h-px flex-1 bg-border/60" />
      </div>
    </form>
  );
}
