"use client";

import OtpInput from "react-otp-input";
import { motion } from "framer-motion";
import { cn } from "@/lib/utils";

interface AuthOtpInputProps {
  value: string;
  onChange: (otp: string) => void;
  onComplete?: (otp: string) => void;
  numInputs?: number;
  error?: boolean;
  success?: boolean;
  disabled?: boolean;
  className?: string;
}

const cellBase =
  "w-11 h-14 sm:w-12 sm:h-14 min-w-[44px] text-center text-2xl font-bold tabular-nums rounded-2xl border-[2.5px] bg-white text-gray-900 shadow-md outline-none caret-[#387E65] selection:bg-sky-200 dark:bg-white dark:text-gray-900 dark:caret-[#387E65]";

export default function AuthOtpInput({
  value,
  onChange,
  onComplete,
  numInputs = 6,
  error = false,
  success = false,
  disabled = false,
  className,
}: AuthOtpInputProps) {
  return (
    <div className={cn("w-full flex justify-center", className)}>
      <OtpInput
        value={value}
        onChange={(otp) => {
          onChange(otp);
          if (otp.length === numInputs) {
            onComplete?.(otp);
          }
        }}
        numInputs={numInputs}
        inputType="number"
        shouldAutoFocus
        skipDefaultStyles
        containerStyle={{
          display: "flex",
          direction: "ltr",
          gap: "0.5rem",
          justifyContent: "center",
          width: "100%",
        }}
        renderInput={(inputProps, index) => {
          const filled = Boolean(inputProps.value);

          return (
            <motion.input
              {...inputProps}
              disabled={disabled}
              animate={
                filled
                  ? { scale: [0.88, 1.1, 1], y: [6, -2, 0], opacity: 1 }
                  : { scale: 1, y: 0, opacity: 1 }
              }
              transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
              className={cn(
                cellBase,
                success
                  ? "border-green-500 shadow-lg ring-2 ring-green-500/35"
                  : error
                    ? "border-red-500 ring-red-500/30"
                    : filled
                      ? "border-[#387E65] shadow-lg ring-2 ring-[#387E65]/25"
                      : "border-gray-500 dark:border-gray-400 shadow-md",
                !success &&
                  !error &&
                  "focus:border-[#387E65] focus:ring-2 focus:ring-[#387E65]/40 focus:shadow-lg",
                disabled && "opacity-50 cursor-not-allowed"
              )}
              inputMode="numeric"
              pattern="[0-9]*"
              autoComplete={index === 0 ? "one-time-code" : "off"}
              aria-label={`رقم ${index + 1} از ${numInputs}`}
            />
          );
        }}
      />
    </div>
  );
}
