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

pub async fn events_handler() -> Html<String> {
    let api_service = ApiService::new();
    
    // Fetch data concurrently for better performance
    let (upcoming_res, featured_res) = tokio::join!(
        api_service.get_events(None), // Get all upcoming events
        api_service.get_events(Some(3)) // Get top 3 for featured
    );

    let upcoming_events = upcoming_res.unwrap_or_default();
    let _featured_events = featured_res.unwrap_or_default();

    let content = format!(r#"
      <section class="section-2025" style="background: var(--soft-gray); padding-top: 6rem;">
        <div class="container-2025">
          <div class="section-header scroll-reveal">
            <h1 class="section-title serif">Upcoming Events</h1>
            <p class="section-subtitle">Join us for these special occasions and activities</p>
          </div>
          
          <div class="events-grid">
            {}
          </div>

          {}
        </div>
      </section>

      <section class="section-2025">
        <div class="container-2025">
          <div class="card-2025 scroll-reveal" style="text-align: center; max-width: 600px; margin: 0 auto;">
            <div class="card-icon-2025" style="margin: 0 auto 2rem;">
              <i class="fas fa-plus-circle"></i>
            </div>
            <h3 class="card-title">Submit an Event</h3>
            <p class="card-text">Have an event you'd like to share with the church community?</p>
            <a href="https://events.rockvilletollandsda.church" target="_blank" class="btn-2025 btn-primary" style="margin-top: 1rem;">
              <i class="fas fa-paper-plane"></i>
              Submit Event Request
            </a>
          </div>
        </div>
      </section>
    "#,
    // Events grid HTML
    upcoming_events.iter().enumerate().map(|(index, event)| {
        render_event_card(event, false, index)
    }).collect::<Vec<_>>().join(""),
    
    // No events message
    if upcoming_events.is_empty() {
        r#"
        <div class="card-2025 scroll-reveal" style="text-align: center; padding: 3rem;">
          <div class="card-icon-2025" style="margin: 0 auto 2rem;">
            <i class="fas fa-calendar-alt"></i>
          </div>
          <h3 class="card-title">No Events Scheduled</h3>
          <p class="card-text">No upcoming events at this time. Please check back later for new events.</p>
        </div>
        "#
    } else {
        ""
    }
    );

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

pub async fn upcoming_events_handler() -> Html<String> {
    let api_service = ApiService::new();
    
    match api_service.get_events(None).await {
        Ok(events) => {
            let content = format!(r#"
              <section class="section-2025" style="background: var(--soft-gray); padding-top: 6rem;">
                <div class="container-2025">
                  <div class="section-header scroll-reveal">
                    <a href="/events" style="color: var(--medium-gray); text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; margin-bottom: 2rem; font-weight: 500;">
                      <i class="fas fa-arrow-left"></i> Back to Events
                    </a>
                    <h1 class="section-title serif">All Upcoming Events</h1>
                    <p class="section-subtitle">Complete list of all scheduled events and activities</p>
                  </div>
                  
                  <div class="events-grid">
                    {}
                  </div>

                  {}
                </div>
              </section>

              <section class="section-2025">
                <div class="container-2025">
                  <div class="card-2025 scroll-reveal" style="text-align: center; max-width: 600px; margin: 0 auto;">
                    <div class="card-icon-2025" style="margin: 0 auto 2rem;">
                      <i class="fas fa-plus-circle"></i>
                    </div>
                    <h3 class="card-title">Submit an Event</h3>
                    <p class="card-text">Have an event you'd like to share with the church community?</p>
                    <a href="https://events.rockvilletollandsda.church" target="_blank" class="btn-2025 btn-primary" style="margin-top: 1rem;">
                      <i class="fas fa-paper-plane"></i>
                      Submit Event Request
                    </a>
                  </div>
                </div>
              </section>
            "#,
            // Events grid HTML
            events.iter().enumerate().map(|(index, event)| {
                render_event_card(event, false, index)
            }).collect::<Vec<_>>().join(""),
            
            // No events message
            if events.is_empty() {
                r#"
                <div class="card-2025 scroll-reveal" style="text-align: center; padding: 3rem;">
                  <div class="card-icon-2025" style="margin: 0 auto 2rem;">
                    <i class="fas fa-calendar-alt"></i>
                  </div>
                  <h3 class="card-title">No Events Scheduled</h3>
                  <p class="card-text">No upcoming events at this time. Please check back later for new events.</p>
                </div>
                "#
            } else {
                ""
            }
            );

            Html(layout(&content, "Upcoming Events"))
        }
        Err(_) => {
            let content = r#"
                <section class="section-2025">
                    <div class="container-2025">
                        <div class="card-2025 scroll-reveal" style="text-align: center; padding: 3rem;">
                            <h1>Unable to Load Events</h1>
                            <p>We're having trouble loading the events right now. Please try again later.</p>
                            <a href="/events" class="btn-2025 btn-primary">← Back to Events</a>
                        </div>
                    </div>
                </section>
            "#;
            Html(layout(content, "Upcoming Events"))
        }
    }
}

pub async fn event_detail_handler(Path(id): Path<String>) -> Html<String> {
    let api_service = ApiService::new();
    
    match api_service.get_event(&id).await {
        Ok(Some(event)) => {
            let content = format!(r#"
              <!-- Event Detail Hero -->
              <section class="section-2025" style="background: var(--gradient-primary); color: white; padding: 3rem 0;">
                <div class="container-2025">
                  <a href="/events" style="color: rgba(255,255,255,0.8); text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; margin-bottom: 2rem; font-weight: 500;">
                    <i class="fas fa-arrow-left"></i> Back to Events
                  </a>
                  <h1 class="section-title serif" style="color: white; font-size: clamp(2.5rem, 5vw, 4rem); margin-bottom: 1rem;">{}</h1>
                  <div style="display: flex; flex-wrap: wrap; gap: 2rem; align-items: center; opacity: 0.9;">
                    <div style="display: flex; align-items: center; gap: 0.5rem;">
                      <i class="fas fa-calendar-alt" style="color: var(--soft-gold);"></i>
                      <span>{}</span>
                    </div>
                    <div style="display: flex; align-items: center; gap: 0.5rem;">
                      <i class="fas fa-map-marker-alt" style="color: var(--soft-gold);"></i>
                      {}
                    </div>
                    {}
                  </div>
                </div>
              </section>

              {}
              
              <!-- Event Details -->
              <section class="section-2025">
                <div class="container-2025">
                  <div style="display: grid; grid-template-columns: 1fr 300px; gap: 3rem; align-items: start;">
                    <!-- Main Content -->
                    <div>
                      <div class="card-2025 scroll-reveal">
                        <h3 class="card-title" style="margin-bottom: 2rem;">Event Description</h3>
                        <div style="line-height: 1.7; color: var(--medium-gray);">
                          {}
                        </div>
                      </div>
                    </div>
                    
                    <!-- Sidebar -->
                    <div>
                      <div class="card-2025 scroll-reveal" style="margin-bottom: 2rem;">
                        <h4 class="card-title" style="font-size: 1.2rem; margin-bottom: 1.5rem;">Event Details</h4>
                        
                        <div style="margin-bottom: 1.5rem;">
                          <div style="display: flex; align-items: center; gap: 0.75rem; margin-bottom: 0.5rem;">
                            <i class="fas fa-calendar-alt" style="color: var(--soft-gold); width: 20px;"></i>
                            <strong style="color: var(--deep-navy);">Date & Time</strong>
                          </div>
                          <p style="color: var(--medium-gray); margin-left: 2rem; line-height: 1.5;">{}</p>
                        </div>
                        
                        <div style="margin-bottom: 1.5rem;">
                          <div style="display: flex; align-items: center; gap: 0.75rem; margin-bottom: 0.5rem;">
                            <i class="fas fa-map-marker-alt" style="color: var(--soft-gold); width: 20px;"></i>
                            <strong style="color: var(--deep-navy);">Location</strong>
                          </div>
                          <p style="color: var(--medium-gray); margin-left: 2rem; line-height: 1.5;">
                            {}
                          </p>
                          {}
                        </div>
                        
                      </div>
                      
                      <div class="card-2025 scroll-reveal" style="text-align: center;">
                        <div class="card-icon-2025" style="margin: 0 auto 1.5rem;">
                          <i class="fas fa-envelope"></i>
                        </div>
                        <h4 class="card-title" style="font-size: 1.1rem; margin-bottom: 1rem;">Need More Info?</h4>
                        <p style="color: var(--medium-gray); margin-bottom: 1.5rem; font-size: 0.95rem;">Contact us for additional details about this event.</p>
                        <a href="/contact" class="btn-2025 btn-primary">
                          <i class="fas fa-phone"></i> Contact Us
                        </a>
                      </div>
                    </div>
                  </div>
                </div>
              </section>
              
              <!-- Mobile Layout Adjustments -->
              <style>
                @media (max-width: 768px) {{
                  .container-2025 > div[style*="grid-template-columns"] {{
                    grid-template-columns: 1fr !important;
                    gap: 2rem !important;
                  }}
                }}
              </style>
            "#,
            event.title,
            format_event_datetime(&event.start_time, &event.end_time),
            // Location with optional URL
            if let Some(ref url) = event.location_url {
                if !url.is_empty() {
                    format!(r#"<a href="{}" target="_blank" style="color: white; text-decoration: none; font-weight: 500;">
                        {} <i class="fas fa-external-link-alt" style="font-size: 0.8rem; margin-left: 0.25rem;"></i>
                    </a>"#, url, event.location)
                } else {
                    format!("<span>{}</span>", event.location)
                }
            } else {
                format!("<span>{}</span>", event.location)
            },
            // Category badge
            if let Some(ref category) = event.category {
                if !category.is_empty() {
                    format!(r#"
                    <div style="background: var(--gradient-gold); color: var(--midnight); padding: 0.5rem 1rem; border-radius: 20px; font-size: 0.9rem; font-weight: 600;">
                      {}
                    </div>
                    "#, category)
                } else {
                    String::new()
                }
            } else {
                String::new()
            },
            // Event image section
            if let Some(ref image) = event.image {
                if !image.is_empty() {
                    format!(r#"
                    <section class="section-2025" style="padding: 2rem 0;">
                      <div class="container-2025">
                        <div class="card-2025 scroll-reveal" style="padding: 1rem; text-align: center;">
                          <img src="{}" alt="{}" style="max-width: 100%; height: auto; display: block; margin: 0 auto;">
                        </div>
                      </div>
                    </section>
                    "#, image, event.title)
                } else {
                    String::new()
                }
            } else {
                String::new()
            },
            // Description
            event.description.as_ref()
                .map(|d| d.as_str())
                .unwrap_or("<p>No description available for this event.</p>"),
            // Sidebar date/time
            format_event_datetime(&event.start_time, &event.end_time),
            // Sidebar location
            if let Some(ref url) = event.location_url {
                if !url.is_empty() {
                    format!(r#"<a href="{}" target="_blank" style="color: var(--soft-gold); text-decoration: none; font-weight: 500;">
                        {} <i class="fas fa-external-link-alt" style="font-size: 0.8rem; margin-left: 0.25rem;"></i>
                    </a>"#, url, event.location)
                } else {
                    event.location.clone()
                }
            } else {
                event.location.clone()
            },
            // Get directions button
            if let Some(ref url) = event.location_url {
                if !url.is_empty() {
                    format!(r#"
                    <a href="{}" target="_blank" class="btn-2025 btn-outline" style="margin-left: 2rem; margin-top: 0.5rem; font-size: 0.9rem; padding: 0.5rem 1rem;">
                      <i class="fas fa-directions"></i> Get Directions
                    </a>
                    "#, url)
                } else {
                    String::new()
                }
            } else {
                String::new()
            }
            );

            Html(layout(&content, &event.title))
        },
        Ok(None) => {
            let content = r#"
                <section class="section-2025">
                    <div class="container-2025">
                        <div class="card-2025 scroll-reveal" style="text-align: center; padding: 3rem;">
                            <h1>Event Not Found</h1>
                            <p>The requested event could not be found.</p>
                            <a href="/events" class="btn-2025 btn-primary">← Back to Events</a>
                        </div>
                    </div>
                </section>
            "#;
            Html(layout(content, "Event Not Found"))
        },
        Err(_) => {
            let content = r#"
                <section class="section-2025">
                    <div class="container-2025">
                        <div class="card-2025 scroll-reveal" style="text-align: center; padding: 3rem;">
                            <h1>Error</h1>
                            <p>Unable to load event. Please try again later.</p>
                            <a href="/events" class="btn-2025 btn-primary">← Back to Events</a>
                        </div>
                    </div>
                </section>
            "#;
            Html(layout(content, "Error"))
        }
    }
}

fn render_event_card(event: &crate::models::Event, is_featured: bool, index: usize) -> String {
    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(|| String::new());
    
    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-{}" id="{}" {}>
          {}
          <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.id,
    if is_featured {
        r#"style="border: 2px solid var(--soft-gold); cursor: pointer;""#
    } else {
        r#"style="cursor: pointer;""#
    },
    if is_featured {
        r#"<div style="background: var(--gradient-gold); color: var(--midnight); padding: 0.75rem; text-align: center; font-weight: 600; font-size: 0.9rem;">⭐ FEATURED EVENT</div>"#
    } else {
        ""
    },
    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,
    if let Some(ref url) = event.location_url {
        if !url.is_empty() {
            format!(r#"
              <span onclick="event.stopPropagation(); window.open('{}', '_blank');" style="color: var(--soft-gold); cursor: pointer; text-decoration: underline;">
                {} <i class="fas fa-external-link-alt" style="font-size: 0.8rem; margin-left: 0.25rem;"></i>
              </span>
            "#, url, event.location)
        } else {
            event.location.clone()
        }
    } else {
        event.location.clone()
    },
    description
    )
}