'use client';

import s from './styles.module.scss';
import { Button, Input, Mark, TextArea } from '@shared/ui';
import toast from 'react-hot-toast';
import { Controller, useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

import man from '@public/images/footer-man.png';
import { sendFormFn } from '@shared/api/api.service';

const FormSchema = z.object({
  name: z.string().min(3),
  phone: z.string(),
  message: z.string(),
});
type TForm = z.infer<typeof FormSchema>;

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

export default function FooterForm() {
  const {
    handleSubmit,
    control,
    reset,
    formState: { errors },
  } = useForm<TForm>({
    mode: 'onSubmit',
    reValidateMode: 'onBlur',
    resolver: zodResolver(FormSchema),
    defaultValues,
  });

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

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

  return (
    <form className={s.Form} onSubmit={handleSubmit(onSubmit)}>
      <h2 className={s.Header}>
        Давайте <Mark>обсудим</Mark> ваши задачи
      </h2>
      <Controller
        control={control}
        name={'name'}
        render={({ field }) => (
          <Input
            {...field}
            variant='ghost'
            placeholder={'Ваше имя'}
            fullWidth
          />
        )}
      />
      <Controller
        control={control}
        name={'phone'}
        render={({ field }) => (
          <Input
            {...field}
            variant='ghost'
            placeholder={'+7 999 1234567'}
            fullWidth
          />
        )}
      />
      <Controller
        control={control}
        name={'message'}
        render={({ field }) => (
          <TextArea
            {...field}
            variant='ghost'
            placeholder={'Кратко опишите вашу задачу'}
            fullWidth
            id='story'
            name='story'
            rows={6}
          />
        )}
      />
      <Button className={s.SendBtn} variant='orange' fullWidth>
        Отправить
      </Button>
    </form>
  );
}
