use web_sys::HtmlInputElement;
use yew::prelude::*;

use crate::services::calendar_service::CalendarService;

#[derive(Properties, PartialEq)]
pub struct ExternalCalendarModalProps {
    pub is_open: bool,
    pub on_close: Callback<()>,
    pub on_success: Callback<i32>, // Pass the newly created calendar ID
}

#[function_component(ExternalCalendarModal)]
pub fn external_calendar_modal(props: &ExternalCalendarModalProps) -> Html {
    let name_ref = use_node_ref();
    let url_ref = use_node_ref();
    let color_ref = use_node_ref();
    let is_loading = use_state(|| false);
    let error_message = use_state(|| None::<String>);

    let on_submit = {
        let name_ref = name_ref.clone();
        let url_ref = url_ref.clone();
        let color_ref = color_ref.clone();
        let is_loading = is_loading.clone();
        let error_message = error_message.clone();
        let on_close = props.on_close.clone();
        let on_success = props.on_success.clone();

        Callback::from(move |e: SubmitEvent| {
            e.prevent_default();
            
            let name = name_ref
                .cast::<HtmlInputElement>()
                .map(|input| input.value())
                .unwrap_or_default()
                .trim()
                .to_string();
            
            let url = url_ref
                .cast::<HtmlInputElement>()
                .map(|input| input.value())
                .unwrap_or_default()
                .trim()
                .to_string();
                
            let color = color_ref
                .cast::<HtmlInputElement>()
                .map(|input| input.value())
                .unwrap_or_else(|| "#4285f4".to_string());

            if name.is_empty() {
                error_message.set(Some("Calendar name is required".to_string()));
                return;
            }

            if url.is_empty() {
                error_message.set(Some("Calendar URL is required".to_string()));
                return;
            }

            // Basic URL validation
            if !url.starts_with("http://") && !url.starts_with("https://") {
                error_message.set(Some("Please enter a valid HTTP or HTTPS URL".to_string()));
                return;
            }

            error_message.set(None);
            is_loading.set(true);

            let is_loading = is_loading.clone();
            let error_message = error_message.clone();
            let on_close = on_close.clone();
            let on_success = on_success.clone();

            wasm_bindgen_futures::spawn_local(async move {
                match CalendarService::create_external_calendar(&name, &url, &color).await {
                    Ok(new_calendar) => {
                        is_loading.set(false);
                        on_success.emit(new_calendar.id);
                        on_close.emit(());
                    }
                    Err(e) => {
                        is_loading.set(false);
                        error_message.set(Some(format!("Failed to add calendar: {}", e)));
                    }
                }
            });
        })
    };

    let on_cancel = {
        let on_close = props.on_close.clone();
        Callback::from(move |_| {
            on_close.emit(());
        })
    };
    
    let on_cancel_clone = on_cancel.clone();

    if !props.is_open {
        return html! {};
    }

    html! {
        <div class="modal-backdrop" onclick={on_cancel_clone}>
            <div class="external-calendar-modal" onclick={Callback::from(|e: MouseEvent| e.stop_propagation())}>
                <div class="modal-header">
                    <h3>{"Add External Calendar"}</h3>
                    <button class="modal-close" onclick={on_cancel.clone()}>{"×"}</button>
                </div>
                
                <form onsubmit={on_submit}>
                    <div class="modal-body">
                        {
                            if let Some(error) = (*error_message).as_ref() {
                                html! {
                                    <div class="error-message">
                                        {error}
                                    </div>
                                }
                            } else {
                                html! {}
                            }
                        }
                        
                        <div class="form-help" style="margin-bottom: 1.5rem; padding: 1rem; background: #f8f9fa; border-radius: 8px; border-left: 4px solid #007bff;">
                            <h4 style="margin: 0 0 0.5rem 0; font-size: 0.9rem; color: #495057;">{"Setting up External Calendars"}</h4>
                            <p style="margin: 0 0 0.5rem 0; font-size: 0.8rem; line-height: 1.4;">
                                {"Currently tested with Outlook 365 and Google Calendar. To get your calendar link:"}
                            </p>
                            
                            <div style="margin-bottom: 1rem;">
                                <strong style="font-size: 0.8rem; color: #495057;">{"Outlook 365:"}</strong>
                                <ol style="margin: 0.3rem 0 0 0; padding-left: 1.2rem; font-size: 0.8rem; line-height: 1.3;">
                                    <li>{"Go to Outlook Settings"}</li>
                                    <li>{"Navigate to Calendar → Shared Calendars"}</li>
                                    <li>{"Click \"Publish a calendar\""}</li>
                                    <li>{"Select your calendar and choose \"Can view all details\""}</li>
                                    <li>{"Copy the ICS link and paste it below"}</li>
                                </ol>
                            </div>
                            
                            <div>
                                <strong style="font-size: 0.8rem; color: #495057;">{"Google Calendar:"}</strong>
                                <ol style="margin: 0.3rem 0 0 0; padding-left: 1.2rem; font-size: 0.8rem; line-height: 1.3;">
                                    <li>{"Hover over your calendar name in the left sidebar"}</li>
                                    <li>{"Click the three dots that appear"}</li>
                                    <li>{"Select \"Settings and sharing\""}</li>
                                    <li>{"Scroll to \"Integrate calendar\""}</li>
                                    <li>{"Copy the \"Public address in iCal format\" link"}</li>
                                </ol>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="external-calendar-name">{"Calendar Name"}</label>
                            <input
                                ref={name_ref}
                                id="external-calendar-name"
                                type="text"
                                placeholder="My External Calendar"
                                disabled={*is_loading}
                                required={true}
                            />
                        </div>

                        <div class="form-group">
                            <label for="external-calendar-url">{"ICS URL"}</label>
                            <input
                                ref={url_ref}
                                id="external-calendar-url"
                                type="url"
                                placeholder="https://example.com/calendar.ics"
                                disabled={*is_loading}
                                required={true}
                            />
                            <small class="form-help">
                                {"Enter the public ICS URL for the calendar you want to add"}
                            </small>
                        </div>

                        <div class="form-group">
                            <label for="external-calendar-color">{"Color"}</label>
                            <input
                                ref={color_ref}
                                id="external-calendar-color"
                                type="color"
                                value="#4285f4"
                                disabled={*is_loading}
                            />
                        </div>
                    </div>

                    <div class="modal-actions">
                        <button
                            type="button"
                            class="btn btn-secondary"
                            onclick={on_cancel}
                            disabled={*is_loading}
                        >
                            {"Cancel"}
                        </button>
                        <button
                            type="submit"
                            class="btn btn-primary"
                            disabled={*is_loading}
                        >
                            {
                                if *is_loading {
                                    "Adding..."
                                } else {
                                    "Add Calendar"
                                }
                            }
                        </button>
                    </div>
                </form>
            </div>
        </div>
    }
}