"use client"

import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { useState } from "react"
import { useAuth } from "@/contexts/AuthContext"
import { Eye, EyeOff, AlertCircle, Loader2, ArrowRight } from "lucide-react"

const formSchema = z.object({
  email: z.string().email("Adresse email invalide"),
  password: z
    .string()
    .min(8, "Le mot de passe doit contenir au moins 8 caractères")
    .max(16, "Le mot de passe doit contenir au plus 12 caractères"),
})

type LoginFormValues = z.infer<typeof formSchema>

interface ApiError extends Error {
  status?: number
}

export function LoginForm({ className, ...props }: React.ComponentPropsWithoutRef<"div">) {
  const { login } = useAuth()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [showPassword, setShowPassword] = useState(false)

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormValues>({ resolver: zodResolver(formSchema) })

  const onSubmit = async (data: LoginFormValues) => {
    setLoading(true)
    setError(null)
    try {
      await login(data.email, data.password)
    } catch (err: unknown) {
      const e = err as ApiError
      if (e?.status === 401 || e?.status === 400 || e?.message === "credentials") {
        setError("Identifiants incorrects. Veuillez réessayer.")
      } else if (e?.status === 500) {
        setError("Erreur serveur. Veuillez réessayer plus tard.")
      } else if (e?.message) {
        setError(e.message)
      } else {
        setError("Une erreur inattendue est survenue.")
      }
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className={cn("flex flex-col gap-8", className)} {...props}>

      {/* En-tête */}
      <div>
        <h2 className="text-2xl font-bold text-gray-900 tracking-tight">Bon retour 👋</h2>
        <p className="mt-1.5 text-sm text-gray-400">
          Connectez-vous pour accéder au tableau de bord
        </p>
      </div>

      {/* Bannière d'erreur */}
      {error && (
        <div className="flex items-start gap-2.5 bg-red-50 border border-red-100 rounded-xl px-4 py-3">
          <AlertCircle className="w-4 h-4 text-red-500 mt-0.5 flex-shrink-0" />
          <p className="text-sm text-red-600">{error}</p>
        </div>
      )}

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-5">

        {/* Email */}
        <div className="space-y-1.5">
          <Label htmlFor="email" className="text-sm font-medium text-gray-700">
            Adresse email
          </Label>
          <Input
            id="email"
            type="email"
            placeholder="vous@exemple.com"
            autoComplete="email"
            className={cn(
              "h-11 rounded-xl bg-gray-50 border-gray-200 text-gray-900 placeholder:text-gray-400 focus:bg-white focus-visible:ring-rose-900/20 focus-visible:border-rose-900 transition-colors",
              errors.email && "border-red-300 bg-red-50 focus-visible:border-red-400 focus-visible:ring-red-200"
            )}
            {...register("email")}
          />
          {errors.email && (
            <p className="flex items-center gap-1 text-xs text-red-500">
              <AlertCircle className="w-3 h-3 flex-shrink-0" />
              {errors.email.message}
            </p>
          )}
        </div>

        {/* Mot de passe */}
        <div className="space-y-1.5">
          <Label htmlFor="password" className="text-sm font-medium text-gray-700">
            Mot de passe
          </Label>
          <div className="relative">
            <Input
              id="password"
              type={showPassword ? "text" : "password"}
              placeholder="••••••••"
              autoComplete="current-password"
              className={cn(
                "h-11 rounded-xl bg-gray-50 border-gray-200 text-gray-900 placeholder:text-gray-400 focus:bg-white focus-visible:ring-rose-900/20 focus-visible:border-rose-900 transition-colors pr-11",
                errors.password && "border-red-300 bg-red-50 focus-visible:border-red-400 focus-visible:ring-red-200"
              )}
              {...register("password")}
            />
            <button
              type="button"
              onClick={() => setShowPassword((v) => !v)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors p-0.5 rounded"
              tabIndex={-1}
              aria-label={showPassword ? "Masquer le mot de passe" : "Afficher le mot de passe"}
            >
              {showPassword
                ? <EyeOff className="w-4 h-4" />
                : <Eye className="w-4 h-4" />
              }
            </button>
          </div>
          {errors.password && (
            <p className="flex items-center gap-1 text-xs text-red-500">
              <AlertCircle className="w-3 h-3 flex-shrink-0" />
              {errors.password.message}
            </p>
          )}
        </div>

        {/* Bouton */}
        <Button
          type="submit"
          disabled={loading}
          className="w-full h-11 rounded-xl text-white font-semibold transition-all duration-150 shadow-sm hover:shadow-md disabled:opacity-60 group"
          style={{ backgroundColor: "#8B0836" }}
          onMouseEnter={e => (e.currentTarget.style.backgroundColor = "#a00a3f")}
          onMouseLeave={e => (e.currentTarget.style.backgroundColor = "#8B0836")}
        >
          {loading ? (
            <span className="flex items-center gap-2">
              <Loader2 className="w-4 h-4 animate-spin" />
              Connexion en cours…
            </span>
          ) : (
            <span className="flex items-center gap-2">
              Se connecter
              <ArrowRight className="w-4 h-4 group-hover:translate-x-0.5 transition-transform" />
            </span>
          )}
        </Button>
      </form>

      {/* Mentions légales */}
      <p className="text-center text-[11px] text-gray-400 leading-relaxed">
        En vous connectant, vous acceptez nos{" "}
        <a href="#" className="text-gray-500 hover:text-gray-800 underline underline-offset-2 transition-colors">
          Conditions d&apos;utilisation
        </a>{" "}
        et notre{" "}
        <a href="#" className="text-gray-500 hover:text-gray-800 underline underline-offset-2 transition-colors">
          Politique de confidentialité
        </a>.
      </p>
    </div>
  )
}
