use yew::prelude::*;
use web_sys::HtmlInputElement;
use wasm_bindgen::JsCast;
use crate::services::calendar_service::CalendarService;

#[derive(Clone, PartialEq)]
pub enum CalendarTab {
    Create,
    External,
}

#[derive(Properties, PartialEq)]
pub struct CalendarManagementModalProps {
    pub is_open: bool,
    pub on_close: Callback<()>,
    pub on_create_calendar: Callback<(String, Option<String>, Option<String>)>, // name, description, color
    pub on_external_success: Callback<i32>, // Pass the newly created external calendar ID
    pub available_colors: Vec<String>,
}

#[function_component(CalendarManagementModal)]
pub fn calendar_management_modal(props: &CalendarManagementModalProps) -> Html {
    let active_tab = use_state(|| CalendarTab::Create);
    
    // Create Calendar state
    let calendar_name = use_state(|| String::new());
    let description = use_state(|| String::new());
    let selected_color = use_state(|| None::<String>);
    let create_error_message = use_state(|| None::<String>);
    let is_creating = use_state(|| false);
    
    // External Calendar state
    let external_name = use_state(|| String::new());
    let external_url = use_state(|| String::new());
    let external_selected_color = use_state(|| Some("#4285f4".to_string()));
    let external_is_loading = use_state(|| false);
    let external_error_message = use_state(|| None::<String>);

    // Reset state when modal opens
    use_effect_with(props.is_open, {
        let calendar_name = calendar_name.clone();
        let description = description.clone();
        let selected_color = selected_color.clone();
        let create_error_message = create_error_message.clone();
        let is_creating = is_creating.clone();
        let external_name = external_name.clone();
        let external_url = external_url.clone();
        let external_is_loading = external_is_loading.clone();
        let external_error_message = external_error_message.clone();
        let external_selected_color = external_selected_color.clone();
        let active_tab = active_tab.clone();
        
        move |is_open| {
            if *is_open {
                // Reset all state when modal opens
                calendar_name.set(String::new());
                description.set(String::new());
                selected_color.set(None);
                create_error_message.set(None);
                is_creating.set(false);
                external_name.set(String::new());
                external_url.set(String::new());
                external_is_loading.set(false);
                external_error_message.set(None);
                external_selected_color.set(Some("#4285f4".to_string()));
                active_tab.set(CalendarTab::Create);
            }
        }
    });

    let on_tab_click = {
        let active_tab = active_tab.clone();
        Callback::from(move |tab: CalendarTab| {
            active_tab.set(tab);
        })
    };

    let on_backdrop_click = {
        let on_close = props.on_close.clone();
        Callback::from(move |e: MouseEvent| {
            if let Some(target) = e.target() {
                let element = target.dyn_into::<web_sys::Element>().unwrap();
                if element.class_list().contains("modal-backdrop") {
                    on_close.emit(());
                }
            }
        })
    };

    // Create Calendar handlers
    let on_name_change = {
        let calendar_name = calendar_name.clone();
        Callback::from(move |e: InputEvent| {
            let input: HtmlInputElement = e.target_unchecked_into();
            calendar_name.set(input.value());
        })
    };

    let on_description_change = {
        let description = description.clone();
        Callback::from(move |e: InputEvent| {
            let input: web_sys::HtmlTextAreaElement = e.target_unchecked_into();
            description.set(input.value());
        })
    };

    let on_color_select = {
        let selected_color = selected_color.clone();
        Callback::from(move |color: String| {
            selected_color.set(Some(color));
        })
    };

    let on_external_color_select = {
        let external_selected_color = external_selected_color.clone();
        Callback::from(move |color: String| {
            external_selected_color.set(Some(color));
        })
    };

    let on_create_submit = {
        let calendar_name = calendar_name.clone();
        let description = description.clone();
        let selected_color = selected_color.clone();
        let create_error_message = create_error_message.clone();
        let is_creating = is_creating.clone();
        let on_create_calendar = props.on_create_calendar.clone();

        Callback::from(move |e: SubmitEvent| {
            e.prevent_default();

            let name = (*calendar_name).trim();
            if name.is_empty() {
                create_error_message.set(Some("Calendar name is required".to_string()));
                return;
            }

            is_creating.set(true);
            create_error_message.set(None);

            let desc = if description.is_empty() {
                None
            } else {
                Some((*description).clone())
            };

            on_create_calendar.emit((name.to_string(), desc, (*selected_color).clone()));
        })
    };

    // External Calendar handlers
    let on_external_submit = {
        let external_name = external_name.clone();
        let external_url = external_url.clone();
        let external_selected_color = external_selected_color.clone();
        let external_is_loading = external_is_loading.clone();
        let external_error_message = external_error_message.clone();
        let on_close = props.on_close.clone();
        let on_external_success = props.on_external_success.clone();

        Callback::from(move |e: SubmitEvent| {
            e.prevent_default();
            
            let name = (*external_name).trim().to_string();
            let url = (*external_url).trim().to_string();
            let color = (*external_selected_color).clone().unwrap_or_else(|| "#4285f4".to_string());

            // Debug logging to understand the issue
            web_sys::console::log_1(&format!("External calendar form submission - Name: '{}', URL: '{}'", name, url).into());

            if name.is_empty() {
                external_error_message.set(Some("Calendar name is required".to_string()));
                web_sys::console::log_1(&"Validation failed: empty name".into());
                return;
            }

            if url.is_empty() {
                external_error_message.set(Some("Calendar URL is required".to_string()));
                web_sys::console::log_1(&"Validation failed: empty URL".into());
                return;
            }

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

            external_is_loading.set(true);
            external_error_message.set(None);

            let external_is_loading = external_is_loading.clone();
            let external_error_message = external_error_message.clone();
            let on_close = on_close.clone();
            let on_external_success = on_external_success.clone();

            wasm_bindgen_futures::spawn_local(async move {
                let _calendar_service = CalendarService::new();
                
                match CalendarService::create_external_calendar(&name, &url, &color).await {
                    Ok(calendar) => {
                        external_is_loading.set(false);
                        on_close.emit(());
                        on_external_success.emit(calendar.id);
                    }
                    Err(e) => {
                        external_is_loading.set(false);
                        external_error_message.set(Some(format!("Failed to add calendar: {}", e)));
                    }
                }
            });
        })
    };

    // External input change handlers
    let on_external_name_change = {
        let external_name = external_name.clone();
        Callback::from(move |e: Event| {
            if let Some(input) = e.target_dyn_into::<HtmlInputElement>() {
                external_name.set(input.value());
            }
        })
    };

    let on_external_url_change = {
        let external_url = external_url.clone();
        Callback::from(move |e: Event| {
            if let Some(input) = e.target_dyn_into::<HtmlInputElement>() {
                external_url.set(input.value());
            }
        })
    };

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

    html! {
        <div class="modal-backdrop" onclick={on_backdrop_click}>
            <div class="modal-content calendar-management-modal">
                <div class="modal-header">
                    <h2>{"Add Calendar"}</h2>
                    <button class="modal-close" onclick={
                        let on_close = props.on_close.clone();
                        Callback::from(move |_: MouseEvent| on_close.emit(()))
                    }>{"×"}</button>
                </div>
                
                <div class="calendar-management-tabs">
                    <button 
                        class={if *active_tab == CalendarTab::Create { "tab-button active" } else { "tab-button" }}
                        onclick={
                            let on_tab_click = on_tab_click.clone();
                            Callback::from(move |_: MouseEvent| on_tab_click.emit(CalendarTab::Create))
                        }
                    >
                        {"Create Calendar"}
                    </button>
                    <button 
                        class={if *active_tab == CalendarTab::External { "tab-button active" } else { "tab-button" }}
                        onclick={
                            let on_tab_click = on_tab_click.clone();
                            Callback::from(move |_: MouseEvent| on_tab_click.emit(CalendarTab::External))
                        }
                    >
                        {"Add External"}
                    </button>
                </div>

                <div class="modal-body">
                    {
                        match *active_tab {
                            CalendarTab::Create => html! {
                                <form onsubmit={on_create_submit}>
                                    <div class="form-group">
                                        <label for="calendar-name">{"Calendar Name"}</label>
                                        <input
                                            type="text"
                                            id="calendar-name"
                                            value={(*calendar_name).clone()}
                                            oninput={on_name_change}
                                            placeholder="Enter calendar name"
                                            disabled={*is_creating}
                                        />
                                    </div>

                                    <div class="form-group">
                                        <label for="calendar-description">{"Description (optional)"}</label>
                                        <textarea
                                            id="calendar-description"
                                            value={(*description).clone()}
                                            oninput={on_description_change}
                                            placeholder="Enter calendar description"
                                            disabled={*is_creating}
                                        />
                                    </div>

                                    <div class="form-group">
                                        <label>{"Calendar Color"}</label>
                                        <div class="color-picker">
                                            {
                                                props.available_colors.iter().map(|color| {
                                                    let is_selected = selected_color.as_ref() == Some(color);
                                                    let color_clone = color.clone();
                                                    let on_color_select = on_color_select.clone();
                                                    
                                                    html! {
                                                        <div
                                                            key={color.clone()}
                                                            class={if is_selected { "color-option selected" } else { "color-option" }}
                                                            style={format!("background-color: {}", color)}
                                                            onclick={Callback::from(move |_: MouseEvent| {
                                                                on_color_select.emit(color_clone.clone());
                                                            })}
                                                        />
                                                    }
                                                }).collect::<Html>()
                                            }
                                        </div>
                                    </div>

                                    {
                                        if let Some(ref error) = *create_error_message {
                                            html! {
                                                <div class="error-message">
                                                    {error}
                                                </div>
                                            }
                                        } else {
                                            html! {}
                                        }
                                    }

                                    <div class="modal-footer">
                                        <button 
                                            type="button" 
                                            class="cancel-button" 
                                            onclick={
                                                let on_close = props.on_close.clone();
                                                Callback::from(move |_: MouseEvent| on_close.emit(()))
                                            }
                                            disabled={*is_creating}
                                        >
                                            {"Cancel"}
                                        </button>
                                        <button 
                                            type="submit" 
                                            class="create-button" 
                                            disabled={*is_creating}
                                        >
                                            {if *is_creating { "Creating..." } else { "Create Calendar" }}
                                        </button>
                                    </div>
                                </form>
                            },
                            CalendarTab::External => html! {
                                <form onsubmit={on_external_submit}>
                                    <div class="form-group">
                                        <label for="external-name">{"Calendar Name"}</label>
                                        <input
                                            type="text"
                                            id="external-name"
                                            value={(*external_name).clone()}
                                            onchange={on_external_name_change}
                                            placeholder="Enter calendar name"
                                            disabled={*external_is_loading}
                                        />
                                    </div>

                                    <div class="form-group">
                                        <label for="external-url">{"Calendar URL"}</label>
                                        <input
                                            type="url"
                                            id="external-url"
                                            value={(*external_url).clone()}
                                            onchange={on_external_url_change}
                                            placeholder="https://example.com/calendar.ics"
                                            disabled={*external_is_loading}
                                        />
                                        <small class="help-text">
                                            {"Enter the ICS/CalDAV URL for your external calendar"}
                                        </small>
                                    </div>

                                    <div class="form-group">
                                        <label>{"Calendar Color"}</label>
                                        <div class="color-picker">
                                            {
                                                props.available_colors.iter().map(|color| {
                                                    let is_selected = external_selected_color.as_ref() == Some(color);
                                                    let color_clone = color.clone();
                                                    let on_external_color_select = on_external_color_select.clone();
                                                    
                                                    html! {
                                                        <div
                                                            key={color.clone()}
                                                            class={if is_selected { "color-option selected" } else { "color-option" }}
                                                            style={format!("background-color: {}", color)}
                                                            onclick={Callback::from(move |_: MouseEvent| {
                                                                on_external_color_select.emit(color_clone.clone());
                                                            })}
                                                        />
                                                    }
                                                }).collect::<Html>()
                                            }
                                        </div>
                                    </div>

                                    {
                                        if let Some(ref error) = *external_error_message {
                                            html! {
                                                <div class="error-message">
                                                    {error}
                                                </div>
                                            }
                                        } else {
                                            html! {}
                                        }
                                    }

                                    <div class="modal-footer">
                                        <button 
                                            type="button" 
                                            class="cancel-button" 
                                            onclick={
                                                let on_close = props.on_close.clone();
                                                Callback::from(move |_: MouseEvent| on_close.emit(()))
                                            }
                                            disabled={*external_is_loading}
                                        >
                                            {"Cancel"}
                                        </button>
                                        <button 
                                            type="submit" 
                                            class="create-button" 
                                            disabled={*external_is_loading}
                                        >
                                            {if *external_is_loading { "Adding..." } else { "Add Calendar" }}
                                        </button>
                                    </div>
                                </form>
                            }
                        }
                    }
                </div>
            </div>
        </div>
    }
}