'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { isAxiosError } from 'axios';
import {
  AlertCircle,
  ArrowRight,
  Clock,
  Eye,
  EyeOff,
  Loader2,
  LockKeyhole,
  Mail,
} from 'lucide-react';
import { z } from 'zod';

import { login } from '@/lib/api';
import { siteConfig } from '@/lib/site';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

const loginSchema = z.object({
  email: z
    .string()
    .min(1, 'L’adresse e-mail est requise.')
    .email('Adresse e-mail invalide.'),
  password: z
    .string()
    .min(1, 'Le mot de passe est requis.')
    .min(8, 'Le mot de passe doit contenir au moins 8 caractères.'),
  remember: z.boolean().default(false),
});

type LoginFormValues = z.infer<typeof loginSchema>;

export function LoginForm() {
  const router = useRouter();
  const [showPassword, setShowPassword] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [authError, setAuthError] = useState<string | null>(null);
  const [sessionExpiree, setSessionExpiree] = useState(false);
  const [redirectPath, setRedirectPath] = useState('/dashboard');

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);

    setSessionExpiree(params.get('session') === 'expiree');

    const redirect = params.get('redirect');
    if (redirect?.startsWith('/') && !redirect.startsWith('//')) {
      setRedirectPath(redirect);
    }
  }, []);

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors },
  } = useForm<LoginFormValues>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      email: '',
      password: '',
      remember: false,
    },
  });

  const remember = watch('remember');

  async function onSubmit(values: LoginFormValues) {
    setIsSubmitting(true);
    setAuthError(null);
    setSessionExpiree(false);

    try {
      await login({
        email: values.email,
        password: values.password,
        remember: values.remember,
      });
      router.push(redirectPath);
    } catch (error) {
      if (isAxiosError(error)) {
        const message =
          error.response?.data?.message ??
          'Identifiants incorrects. Veuillez réessayer.';
        setAuthError(message);
      } else {
        setAuthError('Une erreur est survenue. Veuillez réessayer.');
      }
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <div className="animate-fade-up">
      {/* Anneau dégradé autour de la carte */}
      <div className="rounded-[26px] bg-gradient-to-b from-brand-400/40 via-white/[0.06] to-transparent p-[1.5px]">
        <div className="auth-card relative overflow-hidden rounded-[24.5px] border border-white/[0.08] p-7 sm:p-9">
          <div
            className="auth-hairline absolute inset-x-8 top-0 h-px"
            aria-hidden
          />

          <div className="space-y-2">
            <span className="inline-flex items-center gap-2 rounded-full border border-brand-400/20 bg-brand-500/15 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.12em] text-brand-200">
              <LockKeyhole className="h-3.5 w-3.5" strokeWidth={2.2} />
              Espace sécurisé
            </span>

            <h2 className="text-[28px] font-bold leading-tight tracking-tight text-white">
              Bon retour parmi nous.
            </h2>
            <p className="text-sm text-white/45">
              Connectez-vous pour accéder à votre coffre-fort numérique.
            </p>
          </div>

          {sessionExpiree && (
            <p className="mt-6 flex items-start gap-2.5 rounded-xl border border-amber-400/25 bg-amber-400/10 px-3.5 py-2.5 text-sm text-amber-200">
              <Clock className="mt-0.5 h-4 w-4 shrink-0" />
              Session expirée. Veuillez vous reconnecter.
            </p>
          )}

          <form onSubmit={handleSubmit(onSubmit)} className="mt-7 space-y-5">
            <div className="space-y-2">
              <Label
                htmlFor="email"
                className="text-xs font-semibold uppercase tracking-wide text-white/40"
              >
                Adresse e-mail
              </Label>
              <div className="group relative">
                <Mail
                  className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-white/35 transition-colors group-focus-within:text-brand-300"
                  strokeWidth={1.9}
                />
                <Input
                  id="email"
                  type="email"
                  autoComplete="email"
                  placeholder="nom@garage.fr"
                  className="auth-field h-12 rounded-xl pl-11 text-sm transition-all focus-visible:ring-2 focus-visible:ring-brand-400/30 focus-visible:ring-offset-0"
                  aria-invalid={!!errors.email}
                  {...register('email')}
                />
              </div>
              {errors.email && (
                <p className="text-xs font-medium text-rose-300">
                  {errors.email.message}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <Label
                  htmlFor="password"
                  className="text-xs font-semibold uppercase tracking-wide text-white/40"
                >
                  Mot de passe
                </Label>
                <button
                  type="button"
                  className="text-xs font-semibold text-brand-300 transition-colors hover:text-brand-200"
                >
                  Mot de passe oublié ?
                </button>
              </div>
              <div className="group relative">
                <LockKeyhole
                  className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-white/35 transition-colors group-focus-within:text-brand-300"
                  strokeWidth={1.9}
                />
                <Input
                  id="password"
                  type={showPassword ? 'text' : 'password'}
                  autoComplete="current-password"
                  placeholder="••••••••"
                  className="auth-field h-12 rounded-xl pl-11 pr-11 text-sm transition-all focus-visible:ring-2 focus-visible:ring-brand-400/30 focus-visible:ring-offset-0"
                  aria-invalid={!!errors.password}
                  {...register('password')}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword((prev) => !prev)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-white/40 transition-colors hover:bg-white/10 hover:text-brand-200"
                  aria-label={
                    showPassword
                      ? 'Masquer le mot de passe'
                      : 'Afficher le mot de passe'
                  }
                >
                  {showPassword ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </button>
              </div>
              {errors.password && (
                <p className="text-xs font-medium text-rose-300">
                  {errors.password.message}
                </p>
              )}
            </div>

            <label
              htmlFor="remember"
              className="flex cursor-pointer items-center gap-2.5 text-sm text-white/50"
            >
              <Checkbox
                id="remember"
                checked={remember}
                onCheckedChange={(checked) =>
                  setValue('remember', checked === true)
                }
                className="h-[18px] w-[18px] rounded-md border-white/25 bg-white/5 shadow-none data-[state=checked]:border-brand-400 data-[state=checked]:bg-brand-500"
              />
              Rester connecté sur cet appareil
            </label>

            {authError && (
              <p className="flex items-start gap-2.5 rounded-xl border border-rose-400/25 bg-rose-500/10 px-3.5 py-2.5 text-sm font-medium text-rose-200">
                <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
                {authError}
              </p>
            )}

            <Button
              type="submit"
              className="brand-gradient group h-12 w-full rounded-xl text-[15px] font-semibold shadow-brand transition-all hover:shadow-brand-lg hover:brightness-110"
              disabled={isSubmitting}
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="animate-spin" />
                  Connexion en cours…
                </>
              ) : (
                <>
                  Se connecter
                  <ArrowRight className="transition-transform duration-200 group-hover:translate-x-1" />
                </>
              )}
            </Button>
          </form>

          <div className="mt-7 flex items-center gap-3">
            <span className="h-px flex-1 bg-white/10" />
            <span className="text-[10px] font-semibold uppercase tracking-[0.14em] text-white/30">
              NF Z42-020
            </span>
            <span className="h-px flex-1 bg-white/10" />
          </div>

          <p className="mt-4 text-center text-xs text-white/40">
            Édité par{' '}
            <span className="font-semibold text-white/70">
              {siteConfig.editor}
            </span>
            {' · '}
            <a
              href={siteConfig.siteUrl}
              className="font-medium text-brand-300 hover:underline"
              target="_blank"
              rel="noopener noreferrer"
            >
              {siteConfig.siteHost}
            </a>
          </p>
        </div>
      </div>
    </div>
  );
}
