use axum::{response::Html, http::StatusCode, Json, extract::Host};
use serde_json::json;
use crate::services::ApiService;
use crate::models::ContactForm;
use crate::layout::layout;

pub async fn contact_handler(Host(hostname): Host) -> Html<String> {
    let api_service = ApiService::new();
    let config = api_service.get_config().await.unwrap_or(None);

    let church_name = config.as_ref()
        .and_then(|c| c.church_name.as_ref())
        .map(|s| s.as_str())
        .unwrap_or("Rockville Tolland SDA Church");
    
    let church_address = config.as_ref()
        .and_then(|c| c.church_address.as_ref())
        .map(|s| s.as_str())
        .unwrap_or("");
    
    let po_box = config.as_ref()
        .and_then(|c| c.po_box.as_ref())
        .map(|s| s.as_str())
        .unwrap_or("");
    
    let contact_phone = config.as_ref()
        .and_then(|c| c.contact_phone.as_ref())
        .map(|s| s.as_str())
        .unwrap_or("");
    
    let google_maps_url = config.as_ref()
        .and_then(|c| c.google_maps_url.as_ref())
        .map(|s| s.as_str())
        .unwrap_or("");
    
    // Create dynamic email based on current domain
    let contact_email = format!("info@{}", hostname);
    

    let content = format!(r#"
      <!-- Contact Hero -->
      <section class="section-2025" style="background: var(--gradient-primary); color: white; padding: 6rem 0 4rem 0;">
        <div class="container-2025">
          <div class="section-header scroll-reveal">
            <h1 class="section-title serif" style="color: white;">Contact Us</h1>
            <p class="section-subtitle" style="color: rgba(255,255,255,0.9);">We'd love to hear from you! Whether you have questions, prayer requests, or just want to connect, please reach out</p>
          </div>
        </div>
      </section>

      <!-- Contact Info & Form -->
      <section class="section-2025">
        <div class="container-2025">
          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 3rem; align-items: start;">
            <!-- Church Info -->
            <div class="card-2025 scroll-reveal">
              <div class="card-icon-2025">
                <i class="fas fa-church"></i>
              </div>
              <h3 class="card-title">Church Information</h3>
              <div style="margin: 1.5rem 0;">
                <h4 style="color: var(--deep-navy); margin-bottom: 1rem;">{}</h4>
                {}
                {}
                <p style="margin-bottom: 0.75rem; display: flex; align-items: center; gap: 0.5rem; color: var(--medium-gray);">
                  <i class="fas fa-envelope" style="color: var(--soft-gold);"></i>
                  <a href="mailto:{}" style="color: var(--soft-gold); text-decoration: none;">{}</a>
                </p>
                {}
              </div>
              {}
            </div>

            <!-- Contact Form -->
            <div class="card-2025 scroll-reveal">
              <div class="card-icon-2025">
                <i class="fas fa-paper-plane"></i>
              </div>
              <h3 class="card-title">Send Us a Message</h3>
              <form id="contact-form" style="margin-top: 1.5rem;" onsubmit="handleContactSubmit(event)">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1rem;">
                  <div>
                    <label for="first_name" style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: var(--deep-navy);">First Name *</label>
                    <input type="text" id="first_name" name="first_name" required style="width: 100%; padding: 0.75rem; border: 2px solid var(--soft-gray); border-radius: 8px; font-size: 1rem;">
                  </div>
                  <div>
                    <label for="last_name" style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: var(--deep-navy);">Last Name</label>
                    <input type="text" id="last_name" name="last_name" style="width: 100%; padding: 0.75rem; border: 2px solid var(--soft-gray); border-radius: 8px; font-size: 1rem;">
                  </div>
                </div>
                
                <div style="margin-bottom: 1rem;">
                  <label for="email" style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: var(--deep-navy);">Your Email *</label>
                  <input type="email" id="email" name="email" required style="width: 100%; padding: 0.75rem; border: 2px solid var(--soft-gray); border-radius: 8px; font-size: 1rem;">
                </div>
                
                <div style="margin-bottom: 1rem;">
                  <label for="phone" style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: var(--deep-navy);">Phone Number</label>
                  <input type="tel" id="phone" name="phone" placeholder="(555) 123-4567" onblur="formatPhoneNumber(this)" oninput="keepDigitsOnly(this)" style="width: 100%; padding: 0.75rem; border: 2px solid var(--soft-gray); border-radius: 8px; font-size: 1rem;">
                </div>
                
                <div style="margin-bottom: 1rem;">
                  <label for="subject" style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: var(--deep-navy);">Subject *</label>
                  <select id="subject" name="subject" required style="width: 100%; padding: 0.75rem; border: 2px solid var(--soft-gray); border-radius: 8px; font-size: 1rem;">
                    <option value="">Select a subject</option>
                    <option value="general">General Inquiry</option>
                    <option value="prayer">Prayer Request</option>
                    <option value="bible_study">Bible Study Interest</option>
                    <option value="membership">Membership Information</option>
                    <option value="pastoral">Pastoral Care</option>
                    <option value="adventist_youth">Adventist Youth</option>
                    <option value="other">Other</option>
                  </select>
                </div>
                
                <div style="margin-bottom: 1.5rem;">
                  <label for="message" style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: var(--deep-navy);">Message *</label>
                  <textarea id="message" name="message" rows="6" required style="width: 100%; padding: 0.75rem; border: 2px solid var(--soft-gray); border-radius: 8px; font-size: 1rem; resize: vertical;"></textarea>
                </div>
                
                <button type="submit" class="btn-2025 btn-primary" style="width: 100%;">
                  <i class="fas fa-paper-plane"></i>
                  Send Message
                </button>
                
                <div id="form-message" style="margin-top: 1rem; padding: 1rem; border-radius: 8px; display: none;"></div>
              </form>
            </div>
          </div>
        </div>
      </section>

      <!-- Connect Section -->
      <section class="section-2025" style="background: var(--soft-gray);">
        <div class="container-2025">
          <div class="section-header scroll-reveal">
            <h2 class="section-title">Connect With Us</h2>
            <p class="section-subtitle">Multiple ways to get involved and stay connected</p>
          </div>
          
          <div class="cards-grid">
            <div class="card-2025 scroll-reveal stagger-1">
              <div class="card-icon-2025">
                <i class="fas fa-handshake"></i>
              </div>
              <h3 class="card-title">Visit Us</h3>
              <p class="card-text">Join us for worship any Sabbath morning. Visitors are always welcome!</p>
            </div>
            
            <div class="card-2025 scroll-reveal stagger-2">
              <div class="card-icon-2025">
                <i class="fas fa-praying-hands"></i>
              </div>
              <h3 class="card-title">Prayer Requests</h3>
              <p class="card-text">Submit your prayer requests and our prayer team will lift you up in prayer.</p>
            </div>
            
            <div class="card-2025 scroll-reveal stagger-3">
              <div class="card-icon-2025">
                <i class="fas fa-bible"></i>
              </div>
              <h3 class="card-title">Bible Studies</h3>
              <p class="card-text">Interested in learning more about the Bible? We offer free Bible studies.</p>
            </div>
          </div>
        </div>
      </section>

      <!-- Pastor's Welcome -->
      <section class="section-2025">
        <div class="container-2025">
          <div class="card-2025 scroll-reveal" style="text-align: center; max-width: 800px; margin: 0 auto;">
            <div class="card-icon-2025" style="margin: 0 auto 2rem;">
              <i class="fas fa-user-tie"></i>
            </div>
            <h3 class="card-title">Pastor's Welcome</h3>
            <p class="card-text" style="font-style: italic; font-size: 1.1rem; line-height: 1.7;">Welcome to Rockville Tolland SDA Church! We are a community of believers dedicated to sharing God's love and the Three Angels' Messages with our community. Whether you're a long-time member or a first-time visitor, we're glad you're here.</p>
            <p style="margin-top: 1.5rem; color: var(--soft-gold); font-weight: 600;">- Pastor Joseph Piresson</p>
          </div>
        </div>
      </section>
      
      <!-- Mobile Layout -->
      <style>
        @media (max-width: 768px) {{
          .container-2025 > div[style*="grid-template-columns"] {{
            grid-template-columns: 1fr !important;
            gap: 2rem !important;
          }}
        }}
      </style>

      <script>
        function keepDigitsOnly(input) {{
          input.value = input.value.replace(/\\D/g, '');
        }}
        
        function formatPhoneNumber(input) {{
          const value = input.value.replace(/\\D/g, '');
          if (value.length === 10) {{
            input.value = `(${{value.slice(0, 3)}}) ${{value.slice(3, 6)}}-${{value.slice(6, 10)}}`;
          }}
        }}
        
        async function handleContactSubmit(event) {{
          event.preventDefault();
          
          const formData = new FormData(event.target);
          const messageDiv = document.getElementById('form-message');
          
          // Convert FormData to JSON object for the backend API
          const jsonData = {{
            first_name: formData.get('first_name'),
            last_name: formData.get('last_name') || null,
            email: formData.get('email'),
            phone: formData.get('phone') || null,
            subject: formData.get('subject'),
            message: formData.get('message')
          }};
          
          try {{
            const response = await fetch('/contact', {{
              method: 'POST',
              headers: {{
                'Content-Type': 'application/json',
              }},
              body: JSON.stringify(jsonData)
            }});
            
            if (response.ok) {{
              messageDiv.style.display = 'block';
              messageDiv.style.background = 'var(--soft-green)';
              messageDiv.style.color = 'var(--deep-navy)';
              messageDiv.style.border = '2px solid var(--green)';
              messageDiv.innerHTML = '<i class="fas fa-check-circle"></i> Thank you for your message! We will get back to you soon.';
              event.target.reset();
            }} else {{
              throw new Error('Server error');
            }}
          }} catch (error) {{
            messageDiv.style.display = 'block';
            messageDiv.style.background = 'var(--soft-red)';
            messageDiv.style.color = 'var(--deep-navy)';
            messageDiv.style.border = '2px solid var(--red)';
            messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> Sorry, there was an error sending your message. Please try again.';
          }}
        }}
      </script>
    "#,
    church_name,
    
    // Church address
    if !church_address.is_empty() {
        format!(r#"
        <p style="margin-bottom: 0.75rem; display: flex; gap: 0.5rem; color: var(--medium-gray);">
          <i class="fas fa-map-marker-alt" style="color: var(--soft-gold); width: 20px; flex-shrink: 0; margin-top: 2px;"></i>
          <span>{}</span>
        </p>
        "#, church_address)
    } else {
        String::new()
    },
    
    // PO Box
    if !po_box.is_empty() {
        format!(r#"
        <p style="margin-bottom: 0.75rem; display: flex; gap: 0.5rem; color: var(--medium-gray);">
          <i class="fas fa-mailbox" style="color: var(--soft-gold); width: 20px; flex-shrink: 0; margin-top: 2px;"></i>
          <span>{}</span>
        </p>
        "#, po_box)
    } else {
        String::new()
    },
    
    // Contact email (for mailto link)
    contact_email,
    contact_email,
    
    // Contact phone
    if !contact_phone.is_empty() {
        format!(r#"
        <p style="margin-bottom: 0.75rem; display: flex; align-items: center; gap: 0.5rem; color: var(--medium-gray);">
          <i class="fas fa-phone" style="color: var(--soft-gold);"></i>
          <a href="tel:{}" style="color: var(--soft-gold); text-decoration: none;">{}</a>
        </p>
        "#, contact_phone, contact_phone)
    } else {
        String::new()
    },
    
    // Google Maps link
    if !google_maps_url.is_empty() {
        format!(r#"
        <a href="{}" target="_blank" class="btn-2025 btn-primary">
          <i class="fas fa-directions"></i>
          Get Directions
        </a>
        "#, google_maps_url)
    } else {
        String::new()
    }
    );

    Html(layout(&content, "Contact"))
}

pub async fn contact_form_handler(Json(form): Json<ContactForm>) -> Result<Json<serde_json::Value>, StatusCode> {
    let api_service = ApiService::new();
    
    match api_service.submit_contact_form(&form).await {
        Ok(true) => Ok(Json(json!({
            "success": true,
            "message": "Thank you for your message! We will get back to you soon."
        }))),
        Ok(false) => Err(StatusCode::INTERNAL_SERVER_ERROR),
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR)
    }
}