'use client';

import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '@/lib/cn';

interface InputErrorMessageProps {
  message: string | undefined;
  className?: string;
  describedBy: string;
}

const containerVariants = {
  initial: { opacity: 0, x: -10 },
  animate: {
    opacity: 1,
    x: 0,
    transition: {
      duration: 0.3,
      when: 'beforeChildren',
      staggerChildren: 0.1,
    },
  },
  exit: { opacity: 0, x: -10, transition: { duration: 0.2 } },
} as const;

const iconVariants = {
  initial: { pathLength: 0, opacity: 0 },
  animate: {
    pathLength: 1,
    opacity: 1,
    transition: {
      pathLength: { duration: 0.6, ease: 'easeInOut' },
      opacity: { duration: 0.2 },
    },
  },
} as const;

const textVariants = {
  initial: { opacity: 0, x: -5 },
  animate: {
    opacity: 1,
    x: 0,
    transition: { duration: 0.3 },
  },
} as const;

export const InputErrorMessage = ({ message, className, describedBy }: InputErrorMessageProps) => {
  return (
    <AnimatePresence mode="wait">
      {message && (
        <motion.div
          variants={containerVariants}
          initial="initial"
          animate="animate"
          exit="exit"
          className={cn('mt-1 flex items-center gap-0.75 text-red-500', className)}
        >
          <svg
            fill="none"
            viewBox="0 0 24 24"
            strokeWidth="1.5"
            stroke="currentColor"
            className="size-5 shrink-0"
          >
            <motion.path
              variants={iconVariants}
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M12 9v3.75m9-.75a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 3.75h.008v.008H12v-.008Z"
            />
          </svg>
          <motion.p
            variants={textVariants}
            className="text-xs"
            role="alert"
            aria-live="polite"
            id={describedBy}
          >
            {message}
          </motion.p>
        </motion.div>
      )}
    </AnimatePresence>
  );
};
