'use client';

import type { RefObject } from 'react';
import type { UseFormReturn } from 'react-hook-form';
import { Button } from '@/components/ui/primitives/Button';
import { CountryCodeSelect } from '@/components/ui/primitives/CountryCodeSelect';
import { FormField } from '@/components/ui/primitives/FormField';
import { Input } from '@/components/ui/primitives/Input';
import { Icon } from '@/components/ui/icons/Icon';
import { useT } from '@/lib/i18n/react';

export interface PhoneStepValues {
  phone: string;
}

export interface PhoneStepProps {
  form: UseFormReturn<PhoneStepValues>;
  onSubmit: (values: PhoneStepValues) => void | Promise<void>;
  sending: boolean;
  recaptchaContainerRef: RefObject<HTMLDivElement | null>;
  countryCode: string;
  onCountryCodeChange: (code: string) => void;
}

interface SharedPhoneStepProps extends PhoneStepProps {
  inputId: string;
  layout: 'inline' | 'stacked';
}

export function SharedPhoneStep({
  form,
  onSubmit,
  sending,
  recaptchaContainerRef,
  countryCode,
  onCountryCodeChange,
  inputId,
  layout,
}: SharedPhoneStepProps) {
  const t = useT('auth_flow');
  const field = (
    <FormField
      label={t('phone_label')}
      required
      error={form.formState.errors.phone?.message}
      htmlFor={inputId}
    >
      <div className="flex items-center gap-2" dir="ltr">
        <CountryCodeSelect value={countryCode} onChange={onCountryCodeChange} />
        <Input
          id={inputId}
          type="tel"
          dir="ltr"
          autoComplete="tel"
          placeholder={t('phone_placeholder')}
          className="flex-1"
          {...form.register('phone')}
        />
      </div>
    </FormField>
  );
  const submitButton = (
    <Button
      type="submit"
      variant="primary"
      size="lg"
      loading={sending}
      iconStart={<Icon name="Phone" size="sm" />}
      className={layout === 'inline' ? 'w-full md:w-auto' : 'w-full'}
    >
      {t('send_code')}
    </Button>
  );

  return (
    <form
      onSubmit={form.handleSubmit((values) => void onSubmit(values))}
      className="flex flex-col gap-4"
      noValidate
    >
      {layout === 'inline' ? (
        <div className="flex flex-col gap-4 md:flex-row md:items-end md:gap-3">
          <div className="flex-1">{field}</div>
          {submitButton}
        </div>
      ) : (
        <>
          {field}
          {submitButton}
        </>
      )}
      <div ref={recaptchaContainerRef} />
    </form>
  );
}
