'use client';
import React from 'react';
import { Button } from '@/shared/ui/button';
import { ContactFormValues, contactSchema } from '../lib/data';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import Swal from 'sweetalert2';

const ContactForm = () => {
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting },
  } = useForm<ContactFormValues>({
    resolver: zodResolver(contactSchema),
  });

  const onSubmit = async (data: ContactFormValues) => {
    const res = await fetch('/api/send-to-bot', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });

    if (!res.ok) {
      Swal.fire({
        icon: 'error',
        title: 'Ошибка',
        text: 'Сообщение не может быть отправлено. Пожалуйста, попробуйте позже',
        confirmButtonColor: '#60ae3f',
      });
      return;
    }

    Swal.fire({
      icon: 'success',
      title: 'Заявка отправлена',
      text: 'Спасибо! Мы свяжемся с вами в ближайшее время',
      confirmButtonColor: '#60ae3f',
    });

    reset();
  };

  return (
    <div className="my-[15px]">
      <form onSubmit={handleSubmit(onSubmit)} noValidate>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          <div className="flex flex-col">
            <input
              {...register('name')}
              className="py-[12px] px-[18px] bg-muted-foreground rounded-sm outline-none text-[14px] font-medium text-accent"
              type="text"
              placeholder="Ваше имя"
            />
            {errors.name && (
              <span className="text-red-500 font-medium text-[12px]">
                {errors.name.message}
              </span>
            )}
          </div>
          <div className="flex flex-col">
            <input
              {...register('email')}
              className="py-[12px] px-[18px] bg-muted-foreground rounded-sm outline-none text-[14px] font-medium text-accent"
              type="email"
              placeholder="Ваш email"
            />
            {errors.email && (
              <span className="text-red-500 font-medium text-[12px]">
                {errors.email.message}
              </span>
            )}
          </div>
          <div className="flex flex-col">
            <input
              {...register('phone')}
              className="py-[12px] px-[18px] bg-muted-foreground rounded-sm outline-none text-[14px] font-medium text-accent appearance-none [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
              type="number"
              placeholder="Телефон"
            />
            {errors.phone && (
              <span className="text-red-500 font-medium text-[12px]">
                {errors.phone.message}
              </span>
            )}
          </div>
          <div className="flex flex-col">
            <input
              {...register('company')}
              className="py-[12px] px-[18px] bg-muted-foreground rounded-sm outline-none text-[14px] font-medium text-accent"
              type="text"
              placeholder="Компания"
            />
            {errors.company && (
              <span className="text-red-500 font-medium text-[12px]">
                {errors.company.message}
              </span>
            )}
          </div>
          <div className="flex flex-col md:col-span-2">
            <textarea
              rows={5}
              {...register('message')}
              className="py-[12px] px-[18px] bg-muted-foreground rounded-sm outline-none text-[14px] font-medium text-accent resize-none"
              placeholder="Написать сообщение"
            />
            {errors.message && (
              <span className="text-red-500 font-medium text-[12px]">
                {errors.message.message}
              </span>
            )}
          </div>
        </div>
        <div className="mt-[10px] flex justify-end items-center">
          <Button
            variant="secondary"
            size="lg"
            type="submit"
            disabled={isSubmitting}
          >
            {isSubmitting ? 'Отправка...' : 'Отправить сообщение'}
          </Button>
        </div>
      </form>
    </div>
  );
};

export default ContactForm;
