/**
 * OtpLogin — CodeStep.
 *
 * 6-digit OTP code entry step of the OTP login flow. Calls back to the shell
 * for verify + back navigation. Presentational.
 */

'use client';

import { Controller, type UseFormReturn } from 'react-hook-form';
import { OtpInput } from '@/components/ui/domain/OtpInput';
import { Button } from '@/components/ui/primitives/Button';
import { FormField } from '@/components/ui/primitives/FormField';
import { useT } from '@/lib/i18n/react';

export interface CodeStepValues {
  code: string;
}

export interface CodeStepProps {
  form: UseFormReturn<CodeStepValues>;
  onSubmit: (values: CodeStepValues) => void | Promise<void>;
  verifying: boolean;
  onBack: () => void;
}

export function CodeStep({ form, onSubmit, verifying, onBack }: CodeStepProps) {
  const t = useT('auth_flow');
  const tCommon = useT('common');

  return (
    <form
      onSubmit={form.handleSubmit((v) => void onSubmit(v))}
      className="flex flex-col gap-4"
      noValidate
    >
      <FormField
        label={t('code_label')}
        required
        error={form.formState.errors.code?.message}
        htmlFor="login-code-1"
      >
        <Controller
          control={form.control}
          name="code"
          render={({ field }) => (
            <OtpInput
              id="login-code"
              value={field.value ?? ''}
              onChange={field.onChange}
              onComplete={(code) => {
                field.onChange(code);
                void form.handleSubmit((values) => onSubmit(values))();
              }}
              invalid={!!form.formState.errors.code}
              disabled={verifying}
              getDigitAriaLabel={(index) =>
                t('otp_digit_label').replace('{index}', String(index + 1))
              }
            />
          )}
        />
      </FormField>

      <Button type="submit" variant="primary" size="lg" loading={verifying} className="w-full">
        {t('verify')}
      </Button>

      <Button type="button" variant="ghost" size="sm" className="w-full" onClick={onBack}>
        {tCommon('back')}
      </Button>
    </form>
  );
}
