use axum::response::Html;
use crate::services::{ApiService, format_event_datetime, strip_html};
use crate::layout::layout;

pub async fn home_handler() -> Html<String> {
    let api_service = ApiService::new();
    
    // Fetch data concurrently for better performance
    let (config, bulletin, events, verse) = tokio::join!(
        api_service.get_config(),
        api_service.get_current_bulletin(),
        api_service.get_events(Some(3)),
        api_service.get_random_verse()
    );

    let config = config.unwrap_or(None);
    let current_bulletin = bulletin.unwrap_or(None);
    let upcoming_events = events.unwrap_or_default();
    let bible_verse = verse.unwrap_or(None);

    let church_info = config.as_ref();
    let church_name = church_info
        .and_then(|c| c.church_name.as_ref())
        .map(|s| s.as_str())
        .unwrap_or("Rockville Tolland SDA Church");
    
    let about_text = church_info
        .and_then(|c| c.about_text.as_ref())
        .map(|s| s.as_str())
        .unwrap_or("Proclaiming the Three Angels' Messages with Love and Hope. Join our community of faith as we worship together and grow in Christ.");

    let content = format!(r#"
      <!-- 2025 Hero Section -->
      <section class="hero-2025">
        <div class="hero-content">
          <div class="hero-text">
            <h1 class="hero-title serif">
              Welcome to<br>
              {}
            </h1>
            <p class="hero-subtitle">
              {}
            </p>
            <div class="hero-cta-group">
              <a href="/events" class="btn-2025 btn-primary">
                <i class="fas fa-calendar-alt"></i>
                Join Us This Sabbath
              </a>
              <a href="/sermons" class="btn-2025 btn-outline">
                <i class="fas fa-play"></i>
                Watch Online
              </a>
            </div>
            <div style="display: flex; gap: 2rem; margin-top: 2rem; flex-wrap: wrap;">
              <div style="display: flex; align-items: center; gap: 0.75rem; color: rgba(255,255,255,0.9);">
                <div style="width: 12px; height: 12px; background: var(--soft-gold); border-radius: 50%;"></div>
                <span style="font-size: 0.95rem;">Sabbath School 9:30 AM</span>
              </div>
              <div style="display: flex; align-items: center; gap: 0.75rem; color: rgba(255,255,255,0.9);">
                <div style="width: 12px; height: 12px; background: var(--soft-gold); border-radius: 50%;"></div>
                <span style="font-size: 0.95rem;">Divine Worship 11:00 AM</span>
              </div>
            </div>
          </div>
          
          <div class="hero-visual">
            <div class="floating-card">
              <div style="text-align: center; color: white;">
                <i class="fas fa-dove" style="font-size: 2rem; margin-bottom: 1rem; color: var(--warm-gold);"></i>
                <h4 style="margin-bottom: 0.5rem; font-weight: 600;">First Angel</h4>
                <p style="font-size: 0.9rem; opacity: 0.9;">Fear God & Give Glory</p>
              </div>
            </div>
            <div class="floating-card">
              <div style="text-align: center; color: white;">
                <i class="fas fa-bullhorn" style="font-size: 2rem; margin-bottom: 1rem; color: var(--warm-gold);"></i>
                <h4 style="margin-bottom: 0.5rem; font-weight: 600;">Second Angel</h4>
                <p style="font-size: 0.9rem; opacity: 0.9;">Babylon is Fallen</p>
              </div>
            </div>
            <div class="floating-card">
              <div style="text-align: center; color: white;">
                <i class="fas fa-scroll" style="font-size: 2rem; margin-bottom: 1rem; color: var(--warm-gold);"></i>
                <h4 style="margin-bottom: 0.5rem; font-weight: 600;">Third Angel</h4>
                <p style="font-size: 0.9rem; opacity: 0.9;">Keep God's Commands</p>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- Three Angels Messages 2025 -->
      <section class="section-2025 angels-2025">
        <div class="container-2025">
          <div class="section-header scroll-reveal">
            <h2 class="section-title serif">The Three Angels' Messages</h2>
            <p class="section-subtitle">Central to our mission as Seventh-day Adventists, these messages from Revelation 14 guide our purpose and calling.</p>
          </div>
          
          <div class="angels-grid">
            <div class="card-2025 scroll-reveal stagger-1">
              <div class="card-icon-2025">
                <i class="fas fa-dove"></i>
              </div>
              <h3 class="card-title">First Angel's Message</h3>
              <blockquote style="font-style: italic; color: var(--deep-navy); margin: 1.5rem 0; font-size: 1.1rem; font-weight: 500;">
                "Fear God and give glory to Him, for the hour of His judgment has come; and worship Him who made heaven and earth, the sea and springs of water."
              </blockquote>
              <cite style="color: var(--medium-gray); font-size: 0.9rem;">(Revelation 14:6-7)</cite>
              <p class="card-text" style="margin-top: 1.5rem;">The everlasting gospel calls all people to worship the Creator God who made heaven and earth, recognizing His authority and giving Him glory.</p>
            </div>

            <div class="card-2025 scroll-reveal stagger-2">
              <div class="card-icon-2025">
                <i class="fas fa-bullhorn"></i>
              </div>
              <h3 class="card-title">Second Angel's Message</h3>
              <blockquote style="font-style: italic; color: var(--deep-navy); margin: 1.5rem 0; font-size: 1.1rem; font-weight: 500;">
                "Babylon is fallen, is fallen, that great city, because she has made all nations drink of the wine of the wrath of her fornication."
              </blockquote>
              <cite style="color: var(--medium-gray); font-size: 0.9rem;">(Revelation 14:8)</cite>
              <p class="card-text" style="margin-top: 1.5rem;">A warning about false religious systems and a call to come out of spiritual confusion, choosing truth over tradition.</p>
            </div>

            <div class="card-2025 scroll-reveal stagger-3">
              <div class="card-icon-2025">
                <i class="fas fa-scroll"></i>
              </div>
              <h3 class="card-title">Third Angel's Message</h3>
              <blockquote style="font-style: italic; color: var(--deep-navy); margin: 1.5rem 0; font-size: 1.1rem; font-weight: 500;">
                "Here is the patience of the saints; here are those who keep the commandments of God and the faith of Jesus."
              </blockquote>
              <cite style="color: var(--medium-gray); font-size: 0.9rem;">(Revelation 14:12)</cite>
              <p class="card-text" style="margin-top: 1.5rem;">A call to remain faithful to God's commandments, including the seventh-day Sabbath, while maintaining faith in Jesus Christ.</p>
            </div>
          </div>
        </div>
      </section>

      {}

      <!-- Service Times 2025 -->
      <section class="section-2025 services-2025">
        <div class="container-2025">
          <div class="section-header scroll-reveal">
            <h2 class="section-title" style="color: white;">Service Times</h2>
            <p class="section-subtitle" style="color: rgba(255,255,255,0.8);">Join us for worship and fellowship</p>
          </div>
          
          <div class="services-grid">
            <div class="service-card-2025 scroll-reveal stagger-1">
              <div class="service-icon-2025">
                <i class="fas fa-book"></i>
              </div>
              <h3 style="color: white; font-family: 'Playfair Display', serif; font-size: 1.5rem; margin-bottom: 1rem;">Sabbath School</h3>
              <div class="service-time">9:30 AM</div>
              <p style="color: rgba(255,255,255,0.8); margin-top: 1rem;">Join us for Bible study and fellowship every Sabbath morning</p>
            </div>
            
            <div class="service-card-2025 scroll-reveal stagger-2">
              <div class="service-icon-2025">
                <i class="fas fa-praying-hands"></i>
              </div>
              <h3 style="color: white; font-family: 'Playfair Display', serif; font-size: 1.5rem; margin-bottom: 1rem;">Divine Worship</h3>
              <div class="service-time">11:00 AM</div>
              <p style="color: rgba(255,255,255,0.8); margin-top: 1rem;">Worship service with inspiring sermons and uplifting music</p>
            </div>
            
            <div class="service-card-2025 scroll-reveal stagger-3">
              <div class="service-icon-2025">
                <i class="fas fa-hands-praying"></i>
              </div>
              <h3 style="color: white; font-family: 'Playfair Display', serif; font-size: 1.5rem; margin-bottom: 1rem;">Prayer Meeting</h3>
              <div class="service-time">Wed 7:00 PM</div>
              <p style="color: rgba(255,255,255,0.8); margin-top: 1rem;">Mid-week spiritual refreshment with prayer and Bible study</p>
            </div>
          </div>
        </div>
      </section>

      {}

      {}

      <!-- Our Beliefs 2025 -->
      <section class="section-2025">
        <div class="container-2025">
          <div class="section-header scroll-reveal">
            <h2 class="section-title">Our Core Beliefs</h2>
            <p class="section-subtitle">As Seventh-day Adventists, we accept the Bible as our only creed and hold certain fundamental beliefs to be the teaching of the Holy Scriptures.</p>
          </div>
          
          <div class="cards-grid">
            <div class="card-2025 scroll-reveal stagger-1">
              <div class="card-icon-2025">
                <i class="fas fa-bible"></i>
              </div>
              <h4 class="card-title">The Holy Scriptures</h4>
              <p class="card-text">The Holy Scriptures are the infallible revelation of God's will and the authoritative revealer of doctrines.</p>
            </div>
            
            <div class="card-2025 scroll-reveal stagger-2">
              <div class="card-icon-2025">
                <i class="fas fa-cross"></i>
              </div>
              <h4 class="card-title">The Trinity</h4>
              <p class="card-text">There is one God: Father, Son, and Holy Spirit, a unity of three co-eternal Persons.</p>
            </div>
            
            <div class="card-2025 scroll-reveal stagger-3">
              <div class="card-icon-2025">
                <i class="fas fa-calendar-week"></i>
              </div>
              <h4 class="card-title">The Sabbath</h4>
              <p class="card-text">The seventh day of the week is the Sabbath of the Lord our God, a day of rest and worship.</p>
            </div>
            
            <div class="card-2025 scroll-reveal stagger-4">
              <div class="card-icon-2025">
                <i class="fas fa-cloud"></i>
              </div>
              <h4 class="card-title">The Second Coming</h4>
              <p class="card-text">The second coming of Christ is the blessed hope of the church and the grand climax of the gospel.</p>
            </div>
          </div>
        </div>
      </section>

      <!-- Mobile App Section -->
      <section class="section-2025" style="background: var(--soft-gray);">
        <div class="container-2025">
          <div class="section-header scroll-reveal">
            <h2 class="section-title">Faith in Your Pocket</h2>
            <p class="section-subtitle">Access sermons, events, and stay connected with our church family through our mobile app designed for spiritual growth.</p>
          </div>
          
          <div class="card-2025 scroll-reveal" style="max-width: 800px; margin: 0 auto; text-align: center;">
            <div class="card-icon-2025" style="margin: 0 auto 2rem;">
              <i class="fas fa-mobile-alt"></i>
            </div>
            <h3 class="card-title" style="font-size: 2rem; margin-bottom: 2rem;">Download Our Mobile App</h3>
            <p style="color: var(--medium-gray); line-height: 1.6; margin-bottom: 3rem; font-size: 1.1rem;">
              Stay connected with sermons, events, and church activities wherever you go. 
              Our app makes it easy to access spiritual content and stay engaged with our community.
            </p>
            
            <div style="display: flex; flex-wrap: wrap; gap: 1.5rem; justify-content: center; align-items: center;">
              <!-- iOS App Store -->
              <a href="https://apps.apple.com/us/app/rtsda/id6738595657" target="_blank" rel="noopener noreferrer" style="display: block; transition: transform 0.3s ease;" onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'">
                <img src="/images/app-store-badge.svg" alt="Download on the App Store" style="height: 60px; border-radius: 8px;">
              </a>
              
              <!-- Android APK Download -->
              <button onclick="downloadApk()" class="btn-2025 btn-primary" style="display: flex; align-items: center; gap: 1rem; font-size: 1rem; padding: 1rem 1.5rem; background: var(--deep-navy); border: none; cursor: pointer;">
                <svg viewBox="0 0 24 24" style="height: 40px; width: 40px; fill: var(--soft-gold);">
                  <path d="M17.6 9.48l1.84-3.18c.16-.31.04-.69-.26-.85a.637.637 0 0 0-.83.22l-1.88 3.24a11.463 11.463 0 0 0-8.94 0L5.65 5.67a.643.643 0 0 0-.87-.2c-.28.18-.37.54-.22.83L6.4 9.48A10.78 10.78 0 0 0 1 18h22a10.78 10.78 0 0 0-5.4-8.52zM7 15.25a1.25 1.25 0 1 1 0-2.5 1.25 1.25 0 0 1 0 2.5zm10 0a1.25 1.25 0 1 1 0-2.5 1.25 1.25 0 0 1 0 2.5z"/>
                </svg>
                <div style="text-align: left; color: white;">
                  <div style="font-size: 0.8rem; opacity: 0.8;">DOWNLOAD APK</div>
                  <div style="font-size: 1.2rem; font-weight: 600;">Android</div>
                </div>
              </button>
            </div>
            
            <div style="margin-top: 2rem; padding: 1.5rem; background: rgba(255,255,255,0.8); border-radius: 12px; border-left: 4px solid var(--soft-gold);">
              <p style="color: var(--deep-navy); margin: 0; font-style: italic;">
                <i class="fas fa-info-circle" style="color: var(--soft-gold); margin-right: 0.5rem;"></i>
                Available on both iOS and Android platforms. Download today to access sermons, events, and stay connected with our church community.
              </p>
            </div>
          </div>
        </div>
      </section>

      <script>
        function downloadApk() {{
          window.location.href = 'https://api.rockvilletollandsda.church/uploads/rtsda_android/current';
        }}
      </script>
    "#, 
    church_name,
    about_text,
    
    // Bible verse section
    if let Some(verse) = &bible_verse {
        format!(r#"
        <section class="section-2025">
          <div class="container-2025">
            <div class="card-2025 scroll-reveal" style="max-width: 800px; margin: 0 auto; text-align: center;">
              <div class="card-icon-2025" style="margin: 0 auto 2rem;">
                <i class="fas fa-book-open"></i>
              </div>
              <h3 class="section-title" style="font-size: 2rem; margin-bottom: 2rem;">Today's Scripture</h3>
              <blockquote style="font-family: 'Playfair Display', serif; font-size: 1.4rem; font-style: italic; color: var(--deep-navy); margin: 2rem 0; line-height: 1.6;">
                "{}"
              </blockquote>
              <cite style="color: var(--medium-gray); font-size: 1.1rem; font-weight: 600;">- {}</cite>
            </div>
          </div>
        </section>
        "#, verse.text, verse.reference)
    } else {
        String::new()
    },
    
    // Current bulletin section
    if let Some(bulletin) = &current_bulletin {
        let formatted_date = format!("{}", bulletin.date); // You can add date formatting here
        format!(r#"
        <!-- This Week's Bulletin -->
        <section class="section-2025">
          <div class="container-2025">
            <div class="section-header scroll-reveal">
              <h2 class="section-title">This Week's Bulletin</h2>
              <p class="section-subtitle">Stay informed about church activities and worship</p>
            </div>
            
            <div class="card-2025 scroll-reveal" style="max-width: 800px; margin: 0 auto; text-align: center;">
              <div class="card-icon-2025" style="margin: 0 auto 2rem;">
                <i class="fas fa-file-alt"></i>
              </div>
              <h3 class="card-title" style="font-size: 2rem; margin-bottom: 1rem;">{}</h3>
              <p style="color: var(--medium-gray); font-size: 1.1rem; margin-bottom: 2rem;">
                <i class="fas fa-calendar" style="color: var(--soft-gold); margin-right: 0.5rem;"></i>
                {}
              </p>
              {}
              <div style="display: flex; flex-wrap: wrap; gap: 1rem; justify-content: center; margin-top: 2rem;">
                {}
                <a href="/bulletins/{}" class="btn-2025 btn-outline" style="border: 2px solid var(--deep-navy); color: var(--deep-navy);">
                  <i class="fas fa-eye"></i>
                  View Details
                </a>
                <a href="/bulletins" class="btn-2025 btn-outline" style="border: 2px solid var(--deep-navy); color: var(--deep-navy);">
                  <i class="fas fa-archive"></i>
                  View Archive
                </a>
              </div>
            </div>
          </div>
        </section>
        "#, 
        bulletin.title,
        formatted_date,
        if let Some(ref scripture) = bulletin.scripture_reading {
            if !scripture.is_empty() {
                format!(r#"
                <div style="background: var(--soft-gray); padding: 2rem; border-radius: 16px; margin: 2rem 0; border-left: 4px solid var(--soft-gold); font-style: italic; color: var(--deep-navy);">
                  <strong style="color: var(--deep-navy);">Scripture Reading:</strong><br>
                  {}
                </div>
                "#, scripture)
            } else {
                String::new()
            }
        } else {
            String::new()
        },
        if let Some(ref pdf_path) = bulletin.pdf_path {
            if !pdf_path.is_empty() {
                format!(r#"
                <a href="{}" target="_blank" class="btn-2025 btn-primary">
                  <i class="fas fa-download"></i>
                  Download PDF
                </a>
                "#, pdf_path)
            } else {
                String::new()
            }
        } else {
            String::new()
        },
        bulletin.id
        )
    } else {
        String::new()
    },
    
    // Upcoming events section
    if !upcoming_events.is_empty() {
        let events_html = upcoming_events.iter().enumerate().map(|(index, event)| {
            let description = event.description.as_ref()
                .map(|d| {
                    let stripped = strip_html(d);
                    if stripped.len() > 120 {
                        format!("{}...", &stripped[..120])
                    } else {
                        stripped
                    }
                })
                .unwrap_or_else(|| "Join us for this special event.".to_string());
                
            let formatted_time = format_event_datetime(&event.start_time, &event.end_time);
            
            format!(r#"
              <a href="/events/{}" style="text-decoration: none; color: inherit; display: block;">
                <div class="event-card-2025 scroll-reveal stagger-{}" style="cursor: pointer;">
                  <div class="event-image-2025" {}></div>
                  <div class="event-content-2025">
                    <h3 class="event-title" style="margin-bottom: 1.5rem;">{}</h3>
                    <p style="margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem; color: var(--medium-gray);">
                      <i class="fas fa-clock" style="color: var(--soft-gold);"></i>
                      {}
                    </p>
                    <p style="margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem; color: var(--medium-gray);">
                      <i class="fas fa-map-marker-alt" style="color: var(--soft-gold);"></i>
                      {}
                    </p>
                    <div style="margin: 1.5rem 0; color: var(--medium-gray); line-height: 1.6;">
                      {}
                    </div>
                    <div class="btn-2025 btn-primary" style="background: var(--gradient-gold) !important; color: var(--midnight) !important; display: inline-flex; align-items: center; gap: 0.5rem;">
                      View Details <i class="fas fa-arrow-right"></i>
                    </div>
                  </div>
                </div>
              </a>
            "#, 
            event.id,
            (index % 3) + 1,
            event.image.as_ref()
                .filter(|img| !img.is_empty())
                .map(|img| format!(r#"style="background-image: url('{}'); background-size: cover; background-position: center;""#, img))
                .unwrap_or_default(),
            event.title,
            formatted_time,
            event.location,
            description
            )
        }).collect::<Vec<_>>().join("");
        
        format!(r#"
        <!-- Upcoming Events -->
        <section class="section-2025" style="background: var(--soft-gray);">
          <div class="container-2025">
            <div class="section-header scroll-reveal">
              <h2 class="section-title">Upcoming Events</h2>
              <p class="section-subtitle">Join us for these special occasions and activities</p>
            </div>
            
            <div class="events-grid">
              {}
            </div>
            
            <div style="text-align: center; margin-top: 3rem;">
              <a href="/events" class="btn-2025 btn-primary" style="font-size: 1.1rem; padding: 1rem 3rem;">
                <i class="fas fa-calendar" style="margin-right: 0.5rem;"></i>
                View All Events
              </a>
            </div>
          </div>
        </section>
        "#, events_html)
    } else {
        String::new()
    }
    );

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