'use client'

import { useState } from 'react'
import { Mail, Send, Check, AlertCircle } from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
import { Input, Button } from 'antd'
import { useForm, Controller } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { newsletterSchema, type NewsletterData } from '@/lib/validation-schemas'
import { showToast } from '@/lib/toast-config'

export function Newsletter() {
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [focusedField, setFocusedField] = useState<'email' | null>(null)

  const {
    control,
    handleSubmit,
    formState: { errors, touchedFields },
    reset,
    watch,
  } = useForm<NewsletterData>({
    resolver: zodResolver(newsletterSchema),
    mode: 'onChange',
    defaultValues: {
      email: '',
      name: '',
    },
  })

  const emailValue = watch('email')

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

      const result = await response.json()

      if (response.ok) {
        showToast.success('Successfully subscribed to newsletter!')
        reset()
      } else {
        showToast.error(result.error || 'Failed to subscribe. Please try again.')
      }
    } catch (error) {
      showToast.error('An error occurred. Please try again later.')
      console.error('Newsletter subscription error:', error)
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="bg-gradient-to-r from-red-500/10 to-blue-600/10 border border-gray-200 dark:border-gray-700 rounded-2xl p-8 overflow-visible">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        whileInView={{ opacity: 1, y: 0 }}
        viewport={{ once: true }}
        transition={{ duration: 0.5 }}
      >
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-5">
          {/* Email Field */}
          <div className="relative">
            <motion.div
              initial={false}
              animate={{
                scale: focusedField === 'email' ? 1.01 : 1,
              }}
              transition={{ duration: 0.2 }}
            >
              <Controller
                name="email"
                control={control}
                render={({ field }) => (
                  <div className="relative">
                    <Input
                      {...field}
                      type="email"
                      size="large"
                      placeholder="your@email.com"
                      status={errors.email ? 'error' : ''}
                      onFocus={() => setFocusedField('email')}
                      onBlur={() => setFocusedField(null)}
                      prefix={
                        <Mail className={`w-4 h-4 transition-colors duration-200 ${
                          focusedField === 'email' 
                            ? 'text-blue-600 dark:text-blue-400' 
                            : 'text-gray-400 dark:text-gray-500'
                        }`} />
                      }
                      suffix={
                        <AnimatePresence mode="wait">
                          {emailValue && !errors.email && touchedFields.email && (
                            <motion.div
                              initial={{ scale: 0, opacity: 0 }}
                              animate={{ scale: 1, opacity: 1 }}
                              exit={{ scale: 0, opacity: 0 }}
                              transition={{ duration: 0.2 }}
                            >
                              <Check className="w-4 h-4 text-green-500" />
                            </motion.div>
                          )}
                        </AnimatePresence>
                      }
                      className={`
                        newsletter-input
                        ${focusedField === 'email' ? 'ring-2 ring-blue-500/20 dark:ring-blue-400/20' : ''}
                        ${errors.email ? 'ring-2 ring-red-500/50' : ''}
                      `}
                      aria-label="Email address"
                      aria-required="true"
                      aria-invalid={!!errors.email}
                      aria-describedby={errors.email ? 'email-error' : undefined}
                      autoComplete="email"
                    />
                  </div>
                )}
              />
            </motion.div>

            <AnimatePresence mode="wait">
              {errors.email && touchedFields.email && (
                <motion.div
                  id="email-error"
                  initial={{ opacity: 0, y: -10, height: 0 }}
                  animate={{ opacity: 1, y: 0, height: 'auto' }}
                  exit={{ opacity: 0, y: -10, height: 0 }}
                  transition={{ duration: 0.2 }}
                  className="flex items-center gap-1 mt-2 text-sm text-red-500 dark:text-red-400"
                >
                  <AlertCircle className="w-3 h-3 flex-shrink-0" />
                  <span>{errors.email.message}</span>
                </motion.div>
              )}
            </AnimatePresence>
          </div>

          {/* Submit Button */}
          <motion.div
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
          >
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              loading={isSubmitting}
              disabled={isSubmitting || Object.keys(errors).length > 0}
              icon={<Send className="w-4 h-4" />}
              className="w-full h-12 font-semibold transition-all duration-300 flex items-center justify-center"
              iconPosition="end"
              aria-label={isSubmitting ? 'Subscribing to newsletter' : 'Subscribe to newsletter'}
            >
              {isSubmitting ? 'Subscribing...' : 'Subscribe'}
            </Button>
          </motion.div>
        </form>
      </motion.div>
    </div>
  )
}

