import React, { useState } from 'react';
import { Mail, Phone, MapPin, Send, CheckCircle, AlertTriangle, Loader2 } from 'lucide-react';
import './Contact.css';

export default function Contact() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    company: '',
    service: 'cyber-strategy',
    message: ''
  });

  const [errors, setErrors] = useState({});
  const [status, setStatus] = useState({ type: null, message: null });
  const [loading, setLoading] = useState(false);

  const validateField = (name, value) => {
    let error = '';
    if (!value.trim()) {
      error = 'This field is required';
    } else if (name === 'email') {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(value)) {
        error = 'Please enter a valid email address';
      }
    } else if (name === 'name' && value.trim().length < 2) {
      error = 'Name must be at least 2 characters long';
    }
    return error;
  };

  const handleBlur = (e) => {
    const { name, value } = e.target;
    const error = validateField(name, value);
    setErrors(prev => ({ ...prev, [name]: error }));
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Validate all fields
    const newErrors = {};
    Object.keys(formData).forEach(key => {
      if (key !== 'company') { // company is optional
        const error = validateField(key, formData[key]);
        if (error) newErrors[key] = error;
      }
    });

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      setStatus({ type: 'error', message: 'Please fill in all required fields correctly.' });
      return;
    }

    setLoading(true);
    setStatus({ type: 'loading', message: 'Sending your request...' });

    try {
      const response = await fetch('https://formspree.io/f/xgobzdqo?wq', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(formData)
      });

      if (response.ok) {
        setStatus({
          type: 'success',
          message: 'Thank you! Your request has been sent to info@cynomos.com. We will contact you within 24 hours.'
        });
        setFormData({
          name: '',
          email: '',
          company: '',
          service: 'cyber-strategy',
          message: ''
        });
      } else {
        throw new Error('Server error submitting form');
      }
    } catch (err) {
      setStatus({
        type: 'error',
        message: 'Sorry, there was an error sending your request. Please email us directly at info@cynomos.com'
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="contact-page">
      {/* Contact Hero */}
      <section className="contact-hero section">
        <div className="container animate-fade-in-up">
          <span className="section-label">Get In Touch</span>
          <h1 className="section-title">Book a Security Evaluation</h1>
          <p className="section-description">
            Take the first step towards securing your codebase, cloud, and client data. Let's arrange a technical scope review.
          </p>
        </div>
      </section>

      {/* Main Form/Details split */}
      <section className="section section-alt form-section">
        <div className="container grid grid-2 contact-grid">
          {/* Details column */}
          <div className="contact-details-panel">
            <h3>Contact Information</h3>
            <p className="panel-subtext">Reach out to us directly or fill out the form, and a cybersecurity engineer will get back to you.</p>
            
            <div className="detail-cards-stack">
              <div className="detail-row-card">
                <div className="detail-icon-circle">
                  <Mail size={20} />
                </div>
                <div>
                  <h4>Email Us</h4>
                  <p><a href="mailto:info@cynomos.com">info@cynomos.com</a></p>
                </div>
              </div>

              <div className="detail-row-card">
                <div className="detail-icon-circle">
                  <Phone size={20} />
                </div>
                <div>
                  <h4>Call Us</h4>
                  <p><a href="tel:+918485984065">+91-8485984065</a></p>
                </div>
              </div>

              <div className="detail-row-card">
                <div className="detail-icon-circle">
                  <MapPin size={20} />
                </div>
                <div>
                  <h4>Headquarters</h4>
                  <p>San Francisco, CA (Remote-First Operations)</p>
                </div>
              </div>
            </div>
          </div>

          {/* Form column */}
          <div className="contact-form-panel">
            {status.message && (
              <div className={`form-feedback-banner ${status.type}`}>
                {status.type === 'success' && <CheckCircle size={20} />}
                {status.type === 'error' && <AlertTriangle size={20} />}
                {status.type === 'loading' && <Loader2 className="spinner" size={20} />}
                <span>{status.message}</span>
              </div>
            )}

            <form onSubmit={handleSubmit} className="evaluation-form">
              <div className="form-group-row grid grid-2">
                <div className="form-group">
                  <label htmlFor="name">Your Name *</label>
                  <input
                    type="text"
                    id="name"
                    name="name"
                    value={formData.name}
                    onChange={handleChange}
                    onBlur={handleBlur}
                    placeholder="John Doe"
                    className={errors.name ? 'error' : ''}
                    disabled={loading}
                  />
                  {errors.name && <span className="field-error">{errors.name}</span>}
                </div>

                <div className="form-group">
                  <label htmlFor="email">Work Email *</label>
                  <input
                    type="email"
                    id="email"
                    name="email"
                    value={formData.email}
                    onChange={handleChange}
                    onBlur={handleBlur}
                    placeholder="john@company.com"
                    className={errors.email ? 'error' : ''}
                    disabled={loading}
                  />
                  {errors.email && <span className="field-error">{errors.email}</span>}
                </div>
              </div>

              <div className="form-group">
                <label htmlFor="company">Organization / Company (Optional)</label>
                <input
                  type="text"
                  id="company"
                  name="company"
                  value={formData.company}
                  onChange={handleChange}
                  placeholder="Acme Corp"
                  disabled={loading}
                />
              </div>

              <div className="form-group">
                <label htmlFor="service">Primary Area of Interest *</label>
                <select
                  id="service"
                  name="service"
                  value={formData.service}
                  onChange={handleChange}
                  disabled={loading}
                >
                  <option value="cyber-strategy">Cyber Security Strategy</option>
                  <option value="security-transformation">Security Transformation</option>
                  <option value="risk-management">Risk Management & Pentesting</option>
                  <option value="compliance-consulting">Compliance Consulting</option>
                </select>
              </div>

              <div className="form-group">
                <label htmlFor="message">Brief Project Scope Details *</label>
                <textarea
                  id="message"
                  name="message"
                  value={formData.message}
                  onChange={handleChange}
                  onBlur={handleBlur}
                  rows="5"
                  placeholder="Please describe your cloud infrastructure, team size, or target compliance timeline..."
                  className={errors.message ? 'error' : ''}
                  disabled={loading}
                ></textarea>
                {errors.message && <span className="field-error">{errors.message}</span>}
              </div>

              <button type="submit" className="btn btn-primary btn-submit" disabled={loading}>
                {loading ? 'Sending Request...' : 'Submit Evaluation Request'} <Send size={16} />
              </button>
            </form>
          </div>
        </div>
      </section>
    </div>
  );
}
