'use client';

import * as React from 'react';
import { OTPInput, OTPInputContext } from 'input-otp';
import { MinusIcon } from 'lucide-react';

import { cn } from '../../shared/utils';

/**
 * Segmented input for one-time passwords and verification codes.
 *
 * @description
 * Splits the input into individual slots to facilitate digit-by-digit entry
 * of verification codes. Built on the `input-otp` library.
 *
 * @ai-rules
 * 1. `maxLength` on the root must match the total number of `<InputOTPSlot>` components.
 * 2. Use `<InputOTPGroup>` to cluster slots and `<InputOTPSeparator>` for visual dividers (e.g., "123-456").
 * 3. Connect to React Hook Form via `<FormControl>` — treat `value`/`onChange` same as a regular input.
 */
function InputOTP({
  className,
  containerClassName,
  ...props
}: React.ComponentProps<typeof OTPInput> & {
  containerClassName?: string;
}) {
  return (
    <OTPInput
      data-slot="input-otp"
      containerClassName={cn('flex items-center gap-2 has-disabled:opacity-50', containerClassName)}
      className={cn('disabled:cursor-not-allowed', className)}
      {...props}
    />
  );
}

function InputOTPGroup({ className, ...props }: React.ComponentProps<'div'>) {
  return (
    <div
      data-slot="input-otp-group"
      className={cn('flex items-center gap-1', className)}
      {...props}
    />
  );
}

function InputOTPSlot({
  index,
  className,
  size = 'md',
  ...props
}: React.ComponentProps<'div'> & {
  index: number;
  /**
   * Size variant — matches the form component sizing scale.
   * - `sm`: 32×32px slot, text-sm
   * - `md`: 40×40px slot, text-base — **default**
   * - `lg`: 48×48px slot, text-lg
   */
  size?: 'sm' | 'md' | 'lg';
}) {
  const inputOTPContext = React.useContext(OTPInputContext);
  const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {};

  const sizeClasses = {
    sm: 'h-8 w-8 text-sm',
    md: 'h-10 w-10 text-base',
    lg: 'h-12 w-12 text-lg',
  };

  return (
    <div
      data-slot="input-otp-slot"
      data-active={isActive}
      className={cn(
        'data-[active=true]:border-primary data-[active=true]:ring-primary/20 data-[active=true]:aria-invalid:ring-destructive/20 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive relative flex items-center justify-center border border-border rounded-[var(--radius)] bg-background transition-all outline-none data-[active=true]:z-10 data-[active=true]:ring-2',
        sizeClasses[size],
        className
      )}
      {...props}
    >
      {char}
      {hasFakeCaret && (
        <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
          <div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
        </div>
      )}
    </div>
  );
}

function InputOTPSeparator({ ...props }: React.ComponentProps<'div'>) {
  return (
    <div data-slot="input-otp-separator" role="separator" {...props}>
      <MinusIcon />
    </div>
  );
}

export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };
