'use client';

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

type ConsultationProps = {
  pageName?: string;
  disableExpert?: boolean;
} & TExpert;

const FormSchema = z.object({
  name: z
    .string()
    .min(3, { message: 'Поле должно содержать не менее 3-х букв' })
    .regex(/^[A-Za-zА-Яа-яЁё]+(?:[ '-][A-Za-zА-Яа-яЁё]+)*$/, {
      message: 'Поле содержит некорректные символы',
    }),
  phone: z.string().refine(isValidPhoneNumber, 'Некорректный номер телефона'),
});

type TForm = z.infer<typeof FormSchema>;

const defaultValues = {
  name: '',
  phone: '',
};

function Consultation({
  pageName = 'noname-form',
  name,
  position,
  photo,
  disableExpert = false,
}: ConsultationProps) {
  const {
    handleSubmit,
    control,
    reset,
    clearErrors,
    formState: { errors },
  } = useForm<TForm>({
    mode: 'onSubmit',
    reValidateMode: 'onBlur',
    resolver: zodResolver(FormSchema),
    defaultValues,
  });

  const onSubmit = async (data: TForm) => {
    const payload = {
      ...data,
      form: pageName,
    };

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

  return (
    <section className={s.Consultation}>
      <div className={s.Container}>
        <div className={s.Block}>
          <h3 className={s.Header}>Бесплатная консультация специалиста</h3>
          <form className={s.Form} onSubmit={handleSubmit(onSubmit)}>
            <Controller
              control={control}
              name={'name'}
              render={({ field }) => (
                <Input
                  {...field}
                  placeholder='Имя'
                  variant={'ghost'}
                  fullWidth
                  onChange={(e) => {
                    clearErrors('name');
                    field.onChange(e);
                  }}
                  error={errors && errors.name?.message}
                />
              )}
            />
            <Controller
              control={control}
              name={'phone'}
              render={({ field }) => (
                <PhoneInput
                  {...field}
                  placeholder={'+7 999 123-45-67'}
                  variant={'ghost'}
                  fullWidth
                  onChange={(e) => {
                    clearErrors('phone');
                    field.onChange(e);
                  }}
                  error={errors && errors.phone?.message}
                />
              )}
            />
            <Button variant={'white'} fullWidth>
              Записаться
            </Button>
          </form>
        </div>
        {disableExpert ? (
          <div />
        ) : (
          <div className={s.Sidebar}>
            <Image src={photo} alt={`${position} - ${name}`} />
            <p className={s.Title}>{name}</p>
            <p className={s.Description}>{position}</p>
          </div>
        )}
      </div>
    </section>
  );
}

export { Consultation };
