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

#[derive(Properties, PartialEq)]
pub struct ColorEditorModalProps {
    pub is_open: bool,
    pub current_color: String,
    pub color_index: usize,
    pub default_color: String, // Default color for this index
    pub on_close: Callback<()>,
    pub on_save: Callback<(usize, String)>, // (index, new_color)
    pub on_reset_all: Callback<()>, // Reset all colors to defaults
}

#[function_component(ColorEditorModal)]
pub fn color_editor_modal(props: &ColorEditorModalProps) -> Html {
    let selected_color = use_state(|| props.current_color.clone());
    
    // Reset selected color when modal opens with new color
    {
        let selected_color = selected_color.clone();
        use_effect_with(props.current_color.clone(), move |current_color| {
            selected_color.set(current_color.clone());
        });
    }

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

    let on_save_click = {
        let selected_color = selected_color.clone();
        let on_save = props.on_save.clone();
        let color_index = props.color_index;
        Callback::from(move |_| {
            on_save.emit((color_index, (*selected_color).clone()));
        })
    };

    let on_backdrop_click = {
        let on_close = props.on_close.clone();
        Callback::from(move |e: MouseEvent| {
            // Only close if clicking the backdrop, not the modal content
            if let Some(target) = e.target() {
                if let Some(element) = target.dyn_ref::<web_sys::Element>() {
                    if element.class_list().contains("color-editor-backdrop") {
                        on_close.emit(());
                    }
                }
            }
        })
    };

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

    // Predefined color suggestions
    let suggested_colors = vec![
        "#3B82F6", "#10B981", "#F59E0B", "#EF4444", "#8B5CF6", "#06B6D4",
        "#84CC16", "#F97316", "#EC4899", "#6366F1", "#14B8A6", "#F3B806",
        "#8B5A2B", "#6B7280", "#DC2626", "#7C3AED", "#F87171", "#34D399",
        "#FBBF24", "#A78BFA", "#60A5FA", "#2DD4BF", "#FB7185", "#FDBA74",
    ];

    html! {
        <div class="color-editor-backdrop" onclick={on_backdrop_click}>
            <div class="color-editor-modal">
                <div class="color-editor-header">
                    <h3>{"Edit Color"}</h3>
                    <button class="close-button" onclick={Callback::from({
                        let on_close = props.on_close.clone();
                        move |_| on_close.emit(())
                    })}>
                        {"×"}
                    </button>
                </div>
                
                <div class="color-editor-content">
                    <div class="current-color-preview">
                        <div 
                            class="color-preview-large"
                            style={format!("background-color: {}", *selected_color)}
                        ></div>
                        <div class="color-preview-info">
                            <span class="color-value">{&*selected_color}</span>
                            <button class="reset-this-color-button" onclick={{
                                let selected_color = selected_color.clone();
                                let default_color = props.default_color.clone();
                                Callback::from(move |_| {
                                    selected_color.set(default_color.clone());
                                })
                            }}>
                                {"Reset This Color"}
                            </button>
                        </div>
                    </div>

                    <div class="color-input-section">
                        <label for="color-picker">{"Custom Color:"}</label>
                        <div class="color-input-group">
                            <input 
                                type="color" 
                                id="color-picker"
                                value={(*selected_color).clone()}
                                oninput={on_color_input.clone()}
                            />
                            <input 
                                type="text" 
                                class="color-text-input"
                                value={(*selected_color).clone()}
                                oninput={on_color_input}
                                placeholder="#000000"
                            />
                        </div>
                    </div>

                    <div class="suggested-colors-section">
                        <label>{"Suggested Colors:"}</label>
                        <div class="suggested-colors-grid">
                            {
                                suggested_colors.iter().map(|color| {
                                    let color = color.to_string();
                                    let selected_color = selected_color.clone();
                                    let onclick = {
                                        let color = color.clone();
                                        Callback::from(move |_| {
                                            selected_color.set(color.clone());
                                        })
                                    };
                                    
                                    html! {
                                        <div 
                                            class="suggested-color"
                                            style={format!("background-color: {}", color)}
                                            onclick={onclick}
                                            title={color.clone()}
                                        ></div>
                                    }
                                }).collect::<Html>()
                            }
                        </div>
                    </div>
                </div>

                <div class="color-editor-footer">
                    <button class="cancel-button" onclick={Callback::from({
                        let on_close = props.on_close.clone();
                        move |_| on_close.emit(())
                    })}>
                        {"Cancel"}
                    </button>
                    <button class="reset-all-button" onclick={Callback::from({
                        let on_reset_all = props.on_reset_all.clone();
                        let on_close = props.on_close.clone();
                        move |_| {
                            on_reset_all.emit(());
                            on_close.emit(());
                        }
                    })}>
                        {"Reset All Colors"}
                    </button>
                    <button class="save-button" onclick={on_save_click}>
                        {"Save"}
                    </button>
                </div>
            </div>
        </div>
    }
}