'use client'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Textarea } from '@/components/ui/textarea'
import { z } from 'zod'
import { useForm, Controller } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import * as React from 'react'
import { CustomInput } from '@/components/ui/CustomInput'
import { motion, AnimatePresence } from 'framer-motion'
import { useScopedI18n } from '@/locales/client'

const APIURL = '/api/send-form'

export const createContactFormSchema = (t: ReturnType<typeof useScopedI18n>) =>
  z.object({
    firstName: z
      .string()
      .min(2, t('errors.firstName.min'))
      .max(50, t('errors.firstName.max'))
      .regex(
        /^[a-zA-Zа-яА-ЯёЁіІїЇєЄґҐ]+(?:[ '-][a-zA-Zа-яА-ЯёЁіІїЇєЄґҐ]+)*$/,
        t('errors.firstName.regex')
      ),
    email: z
      .string()
      .min(6, t('errors.email.min'))
      .max(100, t('errors.email.max'))
      .regex(
        /^[a-zA-Z0-9](?!.*[._-]{2})[a-zA-Z0-9._-]*[a-zA-Z0-9]@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
        t('errors.email.regex')
      )
      .refine((val) => {
        const [local, domain] = val.split('@')
        if (!domain || !local) return false
        const startsOrEndsWithSpecial = /^[._-]|[._-]$/
        return !startsOrEndsWithSpecial.test(local)
      }, {
        message: t('errors.email.startsEnds'),
      }),
    phone: z.string().optional(),
    content: z
      .string()
      .min(1, t('errors.content.required'))
      .max(300, t('errors.content.max')),
    consent: z.boolean().refine((val) => val === true, {
      message: t('errors.consent'),
    }),
  })

// тип выводим из конкретного вызова схемы
// ВАЖНО: вытаскиваем тип из результата вызова функции
export type ContactFormSchema = ReturnType<typeof createContactFormSchema>
export type ContactFormValues = z.infer<ContactFormSchema>

export const ContactForm = () => {
  const t = useScopedI18n('contactForm')

  const {
    register,
    control,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
  } = useForm<ContactFormValues>({
    resolver: zodResolver(createContactFormSchema(t)),
    defaultValues: {
      firstName: '',
      email: '',
      content: '',
      consent: false,
    },
    
  })

  const onSubmit = async (data: ContactFormValues) => {
    try {
      const response = await fetch(APIURL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })

      if (!response.ok) {
        throw new Error('Failed to submit form')
      }

      console.log('Form successfully sent')
      reset({
        firstName: '',
        email: '',
        content: '',
        consent: false,
      }, {
        keepErrors: false,
      })
    } catch (error) {
      console.error('Submission error:', error)
    }
  }


  return (
    <div className="flex flex-col">
      <div className="subheadline-medium text-grey-50">{t('title')}</div>

      <AnimatePresence>
        <motion.form layout onSubmit={handleSubmit(onSubmit)} className="overflow-hidden">
          <div className="mt-5">
            <CustomInput
              labelClass="uppercase"
              label={t('labels.firstName')}
              placeholder={t('placeholders.firstName')}
              {...register('firstName')}
              hasError={!!errors.firstName}
              errorMessage={errors.firstName?.message}
            />
          </div>

          <div className="mt-5">
            <CustomInput
              labelClass="uppercase"
              label={t('labels.email')}
              placeholder={t('placeholders.email')}
              {...register('email')}
              hasError={!!errors.email}
              errorMessage={errors.email?.message}
            />
          </div>

          <div className="mt-5">
            <Controller
              name="content"
              control={control}
              render={({ field }) => (
                <Textarea
                  labelClass="uppercase"
                  label={t('labels.content')}
                  placeholder={t('placeholders.content')}
                  {...field}
                  hasError={!!errors.content}
                  errorMessage={errors.content?.message}
                  className="min-h-[140px] resize-none"
                />
              )}
            />
          </div>

          <div className="mt-5 pl-1">
            <Controller
              name="consent"
              control={control}
              render={({ field }) => (
                <Checkbox
                  label={t('labels.consent')}
                  checked={field.value}
                  onCheckedChange={field.onChange}
                  onBlur={field.onBlur}
                  name={field.name}
                  hasError={!!errors.consent}
                  errorMessage={errors.consent?.message}
                  ref={field.ref}
                />
              )}
            />
          </div>

          <div className="mt-5">
            <Button type="submit" variant="primary" disabled={isSubmitting}>
              {isSubmitting ? t('submitButton.submitting') : t('submitButton.text')}
            </Button>
          </div>
        </motion.form>
      </AnimatePresence>
    </div>
  )
}
