'use client';

import s from './styles.module.scss';
import { clsx } from 'clsx';
import { Button, PhoneInput } from '@shared/ui';
import { z } from 'zod';
import { Controller, useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import toast from 'react-hot-toast';
import { sendFormFn } from '@shared/api/api.service';
import { isValidPhoneNumber } from 'libphonenumber-js/min';

type AdvancedPhoneInputProps = {
  containerClassName?: string;
};

const FormSchema = z.object({
  phone: z.string().refine(isValidPhoneNumber, 'Некорректный номер телефона'),
});
type TForm = z.infer<typeof FormSchema>;

const defaultValues = {
  phone: '',
};

export default function AdvancedPhoneInput({
  containerClassName,
}: AdvancedPhoneInputProps) {
  const {
    handleSubmit,
    control,
    reset,
    clearErrors,
    formState: { errors },
  } = useForm<TForm>({
    resolver: zodResolver(FormSchema),
    defaultValues,
  });

  const onSubmit = async (data: TForm) => {
    const payload = {
      ...data,
      form: 'offer-request-form-desktop',
    };

    try {
      await sendFormFn(payload);
      toast.success('Заявка на консультацию принята');
      reset(defaultValues);
    } catch (e) {
      toast.error('Ошибка при отправке заявки...', {
        duration: 3000,
      });
    }
  };

  return (
    <form
      className={clsx(containerClassName, s.Container)}
      onSubmit={handleSubmit(onSubmit)}
    >
      <Controller
        control={control}
        name={'phone'}
        render={({ field }) => (
          <PhoneInput
            {...field}
            className={s.Phone}
            placeholder={'+7 (999) 123-45-67'}
            onChange={(e) => {
              clearErrors('phone');
              field.onChange(e);
            }}
            error={errors && errors.phone?.message}
            errorTextColor={'#ff9191'}
          />
        )}
      />
      <Button className={s.Button} variant='orange'>
        Отправить заявку
      </Button>
    </form>
  );
}
