'use client'

import { useState, useEffect } from 'react'
import { useNotification } from '@/components/providers/notification-provider'

export default function ContactPage() {
  const { showNotification } = useNotification()
  const [mounted, setMounted] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    service: '',
    message: ''
  })

  const [errors, setErrors] = useState({
    name: '',
    email: '',
    service: '',
    message: ''
  })

  useEffect(() => {
    setMounted(true)
  }, [])

  const validateField = (name: string, value: string) => {
    switch (name) {
      case 'name':
        return value.length < 2 || value.length > 50 
          ? 'Name must be between 2 and 50 characters' 
          : ''
      case 'email':
        return !/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)
          ? 'Please enter a valid email address'
          : ''
      case 'service':
        return !value ? 'Please select a service' : ''
      case 'message':
        return value.length < 10 
          ? 'Message must be at least 10 characters long'
          : value.length > 1000
          ? 'Message must not exceed 1000 characters'
          : ''
      default:
        return ''
    }
  }

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value } = e.target
    setFormData(prev => ({ ...prev, [name]: value }))
    setErrors(prev => ({ ...prev, [name]: validateField(name, value) }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    const newErrors = {
      name: validateField('name', formData.name),
      email: validateField('email', formData.email),
      service: validateField('service', formData.service),
      message: validateField('message', formData.message)
    }
    
    setErrors(newErrors)

    if (Object.values(newErrors).some(error => error)) {
      showNotification('Please correct the errors before submitting.', 'error')
      return
    }

    setIsSubmitting(true)

    try {
      const response = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      })

      const data = await response.json()

      if (data.success) {
        showNotification('Message sent successfully!', 'success')
        setFormData({ name: '', email: '', service: '', message: '' })
      } else {
        showNotification(data.message || 'Failed to send message.', 'error')
      }
    } catch (error) {
      showNotification('An error occurred. Please try again.', 'error')
    } finally {
      setIsSubmitting(false)
    }
  }

  if (!mounted) {
    return null
  }

  return (
    <div className="bg-white">
      <div className="max-w-7xl mx-auto px-6 py-24 lg:px-8">
        <div className="mx-auto max-w-2xl text-center">
          <h1 className="text-4xl font-bold tracking-tight text-gray-900 sm:text-5xl">
            Contact Us
          </h1>
          <p className="mt-6 text-lg leading-8 text-gray-600">
            Ready to elevate your financial strategy? Let's discuss how we can help you achieve your goals.
          </p>
        </div>
        
        <div className="mt-16 max-w-xl mx-auto">
          <form onSubmit={handleSubmit} className="rounded-2xl bg-gray-50 p-10">
            <div className="grid grid-cols-1 gap-y-6">
              <div>
                <label htmlFor="name" className="block text-sm font-medium text-gray-900">
                  Name
                </label>
                <input
                  type="text"
                  name="name"
                  id="name"
                  value={formData.name}
                  onChange={handleChange}
                  className={`mt-2 block w-full rounded-md border-0 px-3.5 py-2 text-gray-900 shadow-sm ring-1 ring-inset ${
                    errors.name ? 'ring-red-500' : 'ring-gray-300'
                  } placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-blue-800 sm:text-sm sm:leading-6`}
                />
                {errors.name && (
                  <p className="mt-1 text-sm text-red-600">{errors.name}</p>
                )}
              </div>

              <div>
                <label htmlFor="email" className="block text-sm font-medium text-gray-900">
                  Email
                </label>
                <input
                  type="email"
                  name="email"
                  id="email"
                  value={formData.email}
                  onChange={handleChange}
                  className={`mt-2 block w-full rounded-md border-0 px-3.5 py-2 text-gray-900 shadow-sm ring-1 ring-inset ${
                    errors.email ? 'ring-red-500' : 'ring-gray-300'
                  } placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-blue-800 sm:text-sm sm:leading-6`}
                />
                {errors.email && (
                  <p className="mt-1 text-sm text-red-600">{errors.email}</p>
                )}
              </div>

              <div>
                <label htmlFor="service" className="block text-sm font-medium text-gray-900">
                  Service
                </label>
                <select
                  name="service"
                  id="service"
                  value={formData.service}
                  onChange={handleChange}
                  className={`mt-2 block w-full rounded-md border-0 px-3.5 py-2 text-gray-900 shadow-sm ring-1 ring-inset ${
                    errors.service ? 'ring-red-500' : 'ring-gray-300'
                  } focus:ring-2 focus:ring-inset focus:ring-blue-800 sm:text-sm sm:leading-6`}
                >
                  <option value="">Select a service</option>
                  <option value="Accounting Services">Accounting Services</option>
                  <option value="Tax Services">Tax Services</option>
                  <option value="Financial Analysis">Financial Analysis</option>
                  <option value="Business Consulting">Business Consulting</option>
                </select>
                {errors.service && (
                  <p className="mt-1 text-sm text-red-600">{errors.service}</p>
                )}
              </div>

              <div>
                <label htmlFor="message" className="block text-sm font-medium text-gray-900">
                  Message
                </label>
                <textarea
                  name="message"
                  id="message"
                  rows={4}
                  value={formData.message}
                  onChange={handleChange}
                  className={`mt-2 block w-full rounded-md border-0 px-3.5 py-2 text-gray-900 shadow-sm ring-1 ring-inset ${
                    errors.message ? 'ring-red-500' : 'ring-gray-300'
                  } placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-blue-800 sm:text-sm sm:leading-6`}
                />
                {errors.message && (
                  <p className="mt-1 text-sm text-red-600">{errors.message}</p>
                )}
                <p className="mt-1 text-sm text-gray-500">
                  {formData.message.length}/1000 characters
                </p>
              </div>

              <div>
                <button
                  type="submit"
                  disabled={isSubmitting || Object.values(errors).some(error => error)}
                  className="block w-full rounded-md bg-blue-800 px-3.5 py-2.5 text-center text-sm font-semibold text-white shadow-sm hover:bg-blue-700 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-800 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isSubmitting ? 'Sending...' : 'Send Message'}
                </button>
              </div>
            </div>
          </form>
        </div>

        <div className="mt-10 flex flex-col items-center gap-4 text-base text-gray-600">
          <p>Serving clients nationwide from Santa Fe, New Mexico headquarters</p>
        </div>
      </div>
    </div>
  )
}
