use leptos::prelude::*;
use std::mem;
use leptos::task::spawn_local;
use gloo_timers::future::IntervalStream;
use futures_util::stream::StreamExt;
use crate::components::card::{Card, CardVariant};
use crate::components::profile::{
    ProfileSidebar, DashboardCenter, DashboardRight,
    HomeCenter, HomeRight, ChangePasswordPage, ApiSettingsPage,
    WhitelistPage, ReferralPage, ParametersPanel, ProxyListPage, BuyProxyPage, CountrySelectionPage,
    StateSelectionPage, CitySelectionPage, ZipCodeSelectionPage, LocationType, DynamicLocationSelectionPage
};
use crate::components::profile::dashboard::proxy_params_context::ProxyParamsProvider;
use crate::components::layout::PageContent;
use crate::auth::AuthState;
use crate::components::prelude::*;

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ProfileSection {
    Home,
    Dashboard,
    Parameters,
    ProxyList,
    BuyProxy,
    CountrySelection,
    StateSelection,
    CitySelection,
    ZipCodeSelection,
    IncludeAsnSelection,
    ExcludeAsnSelection,
    Whitelist,
    ChangePassword,
    Api,
    ReferralSystem,
}

impl ProfileSection {
    pub fn from_str(s: &str) -> Self {
        match s {
            "home" => Self::Home,
            "dashboard" => Self::Dashboard,
            "parameters" => Self::Parameters,
            "proxy-list" => Self::ProxyList,
            "buy-proxy" => Self::BuyProxy,
            "country-selection" => Self::CountrySelection,
            "state-selection" => Self::StateSelection,
            "city-selection" => Self::CitySelection,
            "zip-code-selection" => Self::ZipCodeSelection,
            "include-asn-selection" => Self::IncludeAsnSelection,
            "exclude-asn-selection" => Self::ExcludeAsnSelection,
            "whitelist" => Self::Whitelist,
            "change-password" => Self::ChangePassword,
            "api" => Self::Api,
            "referral" => Self::ReferralSystem,
            _ => Self::Home, // Default fallback
        }
    }

    pub fn to_str(self) -> &'static str {
        match self {
            Self::Home => "home",
            Self::Dashboard => "dashboard",
            Self::Parameters => "parameters",
            Self::ProxyList => "proxy-list",
            Self::BuyProxy => "buy-proxy",
            Self::CountrySelection => "country-selection",
            Self::StateSelection => "state-selection",
            Self::CitySelection => "city-selection",
            Self::ZipCodeSelection => "zip-code-selection",
            Self::IncludeAsnSelection => "include-asn-selection",
            Self::ExcludeAsnSelection => "exclude-asn-selection",
            Self::Whitelist => "whitelist",
            Self::ChangePassword => "change-password",
            Self::Api => "api",
            Self::ReferralSystem => "referral",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ProfileLayoutType {
    TwoColumn,     // Dashboard: center + right panels
    SingleCard,    // Change Password, API: one centered card
    FullWidth,     // Whitelist, Referral: full width content
}

#[component]
pub fn ProfilePageLayout(
    auth: AuthState,
    on_logout: Callback<()>,
) -> impl IntoView {
    let (active_section, set_active_section) = signal(ProfileSection::Home);
    
    // Refresh profile data when the page loads
    {
        let mut auth = auth.clone();
        Effect::new(move |_| {
            let auth = auth.clone();
            spawn_local(async move {
                if let Err(e) = auth.refresh_profile().await {
                    log::warn!("Failed to refresh profile on page load: {}", e);
                }
            });
        });
    }
    
    // Refresh profile data every 3 minutes
    {
        let auth = auth.clone();
        Effect::new(move |_| {
            let auth = auth.clone();
            spawn_local(async move {
                let mut interval = IntervalStream::new(180000); // 3 minutes = 180000ms
                while let Some(_) = interval.next().await {
                    if let Err(e) = auth.refresh_profile().await {
                        log::warn!("Failed to refresh profile periodically: {}", e);
                    }
                }
            });
        });
    }
    
    let on_nav_click = Callback::new(move |section: ProfileSection| {
        set_active_section.set(section);
    });
    
    let on_parameters_click = Callback::new(move |_| {
        set_active_section.set(ProfileSection::Parameters);
    });
    
    let on_get_proxy_click = Callback::new(move |_| {
        set_active_section.set(ProfileSection::ProxyList);
    });
    
    let on_back_from_parameters = Callback::new(move |_| {
        set_active_section.set(ProfileSection::Dashboard);
    });
    
    let on_back_from_proxy_list = Callback::new(move |_| {
        set_active_section.set(ProfileSection::Dashboard);
    });
    
    let on_buy_proxy_click = Callback::new(move |_| {
        set_active_section.set(ProfileSection::BuyProxy);
    });
    
    let on_back_from_buy_proxy = Callback::new(move |_| {
        set_active_section.set(ProfileSection::Home);
    });
    
    let on_back_from_country_selection = Callback::new(move |_| {
        set_active_section.set(ProfileSection::Parameters);
    });
    
    let on_country_select_click = Callback::new(move |_| {
        set_active_section.set(ProfileSection::CountrySelection);
    });
    
    let on_state_select_click = Callback::new(move |_| {
        set_active_section.set(ProfileSection::StateSelection);
    });
    
    let on_city_select_click = Callback::new(move |_| {
        set_active_section.set(ProfileSection::CitySelection);
    });
    
    let on_zip_code_select_click = Callback::new(move |_| {
        set_active_section.set(ProfileSection::ZipCodeSelection);
    });
    
    let on_include_asn_select_click = Callback::new(move |_| {
        set_active_section.set(ProfileSection::IncludeAsnSelection);
    });
    
    let on_exclude_asn_select_click = Callback::new(move |_| {
        set_active_section.set(ProfileSection::ExcludeAsnSelection);
    });
    
    let on_back_from_state_selection = Callback::new(move |_| {
        set_active_section.set(ProfileSection::Parameters);
    });
    
    let on_back_from_city_selection = Callback::new(move |_| {
        set_active_section.set(ProfileSection::Parameters);
    });
    
    let on_back_from_zip_code_selection = Callback::new(move |_| {
        set_active_section.set(ProfileSection::Parameters);
    });
    
    let on_back_from_include_asn_selection = Callback::new(move |_| {
        set_active_section.set(ProfileSection::Parameters);
    });
    
    let on_back_from_exclude_asn_selection = Callback::new(move |_| {
        set_active_section.set(ProfileSection::Parameters);
    });

    view! {
        <PageContent>
            <Card 
                variant=CardVariant::L1
                max_width="max-w-7xl" 
                padding="p-4" 
                class="w-full mb-[-50px] h-full"
                id="dashboard-card"
            >
                <div class="flex gap-4 text-white" id="dashboard-container">
                    <ProfileSidebar 
                        auth=auth.clone() 
                        on_logout=on_logout 
                        active_section=active_section
                        on_nav_click=on_nav_click
                    />
                    <ProfileContent 
                        active_section=active_section
                        on_parameters_click=on_parameters_click
                        on_get_proxy_click=on_get_proxy_click
                        on_buy_proxy_click=on_buy_proxy_click
                        on_back_from_parameters=on_back_from_parameters
                        on_back_from_proxy_list=on_back_from_proxy_list
                        on_back_from_buy_proxy=on_back_from_buy_proxy
                        on_back_from_country_selection=on_back_from_country_selection
                        on_country_select_click=on_country_select_click
                        on_state_select_click=on_state_select_click
                        on_city_select_click=on_city_select_click
                        on_zip_code_select_click=on_zip_code_select_click
                        on_include_asn_select_click=on_include_asn_select_click
                        on_exclude_asn_select_click=on_exclude_asn_select_click
                        on_back_from_state_selection=on_back_from_state_selection
                        on_back_from_city_selection=on_back_from_city_selection
                        on_back_from_zip_code_selection=on_back_from_zip_code_selection
                        on_back_from_include_asn_selection=on_back_from_include_asn_selection
                        on_back_from_exclude_asn_selection=on_back_from_exclude_asn_selection
                    />
                </div>
            </Card>
        </PageContent>
    }
}

#[component]
fn ProfileContent(
    active_section: ReadSignal<ProfileSection>,
    on_parameters_click: Callback<()>,
    on_get_proxy_click: Callback<()>,
    on_buy_proxy_click: Callback<()>,
    on_back_from_parameters: Callback<()>,
    on_back_from_proxy_list: Callback<()>,
    on_back_from_buy_proxy: Callback<()>,
    on_back_from_country_selection: Callback<()>,
    on_country_select_click: Callback<()>,
    on_state_select_click: Callback<()>,
    on_city_select_click: Callback<()>,
    on_zip_code_select_click: Callback<()>,
    on_include_asn_select_click: Callback<()>,
    on_exclude_asn_select_click: Callback<()>,
    on_back_from_state_selection: Callback<()>,
    on_back_from_city_selection: Callback<()>,
    on_back_from_zip_code_selection: Callback<()>,
    on_back_from_include_asn_selection: Callback<()>,
    on_back_from_exclude_asn_selection: Callback<()>,
) -> impl IntoView {
    view! {
        <ProxyParamsProvider>
            {move || {
                let section = active_section.get();
                let layout_type = get_layout_type(section);
                
                match layout_type {
                    ProfileLayoutType::TwoColumn => {
                        let (left_content, right_content) = get_two_column_content(section, on_parameters_click, on_get_proxy_click, on_buy_proxy_click);
                        render_two_column_layout(left_content, right_content).into_any()
                    }
                    ProfileLayoutType::SingleCard => {
                        view! {
                            <div class="flex-1 flex justify-start" id="single-card-container">
                                {render_single_card_content(section)}
                            </div>
                        }.into_any()
                    }
                    ProfileLayoutType::FullWidth => {
                        view! {
                            <div class="flex-1 flex" id="full-width-container">
                                {render_full_width_content(section, on_back_from_parameters, on_back_from_proxy_list, on_back_from_buy_proxy, on_back_from_country_selection, on_country_select_click, on_state_select_click, on_city_select_click, on_zip_code_select_click, on_include_asn_select_click, on_exclude_asn_select_click, on_back_from_state_selection, on_back_from_city_selection, on_back_from_zip_code_selection, on_back_from_include_asn_selection, on_back_from_exclude_asn_selection)}
                            </div>
                        }.into_any()
                    }
                }
            }}
        </ProxyParamsProvider>
    }
}

fn get_layout_type(section: ProfileSection) -> ProfileLayoutType {
    match section {
        ProfileSection::Home | ProfileSection::Dashboard => ProfileLayoutType::TwoColumn,
        ProfileSection::Parameters | ProfileSection::ProxyList | ProfileSection::BuyProxy | ProfileSection::CountrySelection | ProfileSection::StateSelection | ProfileSection::CitySelection | ProfileSection::ZipCodeSelection | ProfileSection::IncludeAsnSelection | ProfileSection::ExcludeAsnSelection | ProfileSection::Whitelist | ProfileSection::ReferralSystem => ProfileLayoutType::FullWidth,
        ProfileSection::ChangePassword | ProfileSection::Api => ProfileLayoutType::SingleCard,
    }
}

/// Generic two-column layout component that can be reused across pages
/// 
/// # Usage Examples:
/// 
/// ```rust
/// // Default 45%/55% split
/// view! {
///     <TwoColumnLayout 
///         left_content=view! { <div>"Left content"</div> }
///         right_content=view! { <div>"Right content"</div> }
///     />
/// }
/// 
/// // Custom width split (60%/40%)
/// view! {
///     <TwoColumnLayout 
///         left_width="w-[60%]" 
///         right_width="w-[40%]"
///         left_content=view! { <SomeComponent /> }
///         right_content=view! { <AnotherComponent /> }
///     />
/// }
/// 
/// // Custom gap and container ID
/// view! {
///     <TwoColumnLayout 
///         gap="gap-8" 
///         id="custom-layout"
///         left_content=view! { <MainContent /> }
///         right_content=view! { <Sidebar /> }
///     />
/// }
/// ```
#[component]
pub fn TwoColumnLayout<L, R>(
    left_content: L,
    right_content: R,
    #[prop(optional)] left_width: Option<&'static str>,
    #[prop(optional)] right_width: Option<&'static str>,
    #[prop(optional)] gap: Option<&'static str>,
    #[prop(optional)] id: Option<&'static str>,
) -> impl IntoView 
where
    L: IntoView + 'static,
    R: IntoView + 'static,
{
    let left_width = left_width.unwrap_or("w-[45%]");
    let right_width = right_width.unwrap_or("w-[55%]");
    let gap = gap.unwrap_or("gap-4");
    let container_id = id.unwrap_or("two-column-container");

    view! {
        <div class=format!("flex-1 flex {}", gap) id=container_id>
            <div class=left_width id="first-column">
                {left_content}
            </div>
            <div class=right_width id="second-column">
                {right_content}
            </div>
        </div>
    }
}

/// Internal two-column layout renderer for profile pages
fn render_two_column_layout(
    left_content: impl IntoView + 'static,
    right_content: impl IntoView + 'static,
) -> impl IntoView {
    view! {
        <div class="flex-1 flex gap-4" id="two-column-container">
            <div class="w-[45%]" id="first-column">
                {left_content}
            </div>
            <div class="w-[55%]" id="second-column">
                {right_content}
            </div>
        </div>
    }
}

/// Get content for two-column layout based on section
fn get_two_column_content(section: ProfileSection, on_parameters_click: Callback<()>, on_get_proxy_click: Callback<()>, on_buy_proxy_click: Callback<()>) -> (impl IntoView + 'static, impl IntoView + 'static) {
    match section {
        ProfileSection::Home => (
            view! { <HomeCenter on_buy_proxy_click=on_buy_proxy_click /> }.into_any(),
            view! { <HomeRight /> }.into_any(),
        ),
        ProfileSection::Dashboard => (
            view! { <DashboardCenter on_parameters_click=on_parameters_click on_get_proxy_click=on_get_proxy_click /> }.into_any(),
            view! { <DashboardRight /> }.into_any(),
        ),
        _ => (
            view! { <DashboardCenter on_parameters_click=on_parameters_click on_get_proxy_click=on_get_proxy_click /> }.into_any(),
            view! { <DashboardRight /> }.into_any(),
        ),
    }
}

fn render_single_card_content(section: ProfileSection) -> impl IntoView {
    match section {
        ProfileSection::ChangePassword => view! { <ChangePasswordPage /> }.into_any(),
        ProfileSection::Api => view! { <ApiSettingsPage /> }.into_any(),
        _ => view! {
            <Card 
                variant=CardVariant::L2
                max_width="max-w-md" 
                padding="p-3" 
                class="w-full"
                id="profile-card"
            >
                <h2 class="text-xl font-bold text-white mb-4" id="profile-title">
                    {t8s!("Profile")}
                </h2>
                <p class="text-gray-300" id="profile-content">
                    "Default content"
                </p>
            </Card>
        }.into_any(),
    }
}

fn render_full_width_content(section: ProfileSection, on_back_from_parameters: Callback<()>, on_back_from_proxy_list: Callback<()>, on_back_from_buy_proxy: Callback<()>, on_back_from_country_selection: Callback<()>, on_country_select_click: Callback<()>, on_state_select_click: Callback<()>, on_city_select_click: Callback<()>, on_zip_code_select_click: Callback<()>, on_include_asn_select_click: Callback<()>, on_exclude_asn_select_click: Callback<()>, on_back_from_state_selection: Callback<()>, on_back_from_city_selection: Callback<()>, on_back_from_zip_code_selection: Callback<()>, on_back_from_include_asn_selection: Callback<()>, on_back_from_exclude_asn_selection: Callback<()>) -> impl IntoView {
    match section {
        ProfileSection::Parameters => view! { 
            <ParametersPanel on_back=on_back_from_parameters on_country_select=on_country_select_click on_state_select=on_state_select_click on_city_select=on_city_select_click on_zip_code_select=on_zip_code_select_click on_include_asn_select=on_include_asn_select_click on_exclude_asn_select=on_exclude_asn_select_click />
        }.into_any(),
        ProfileSection::ProxyList => view! { 
            <ProxyListPage on_back=on_back_from_proxy_list />
        }.into_any(),
        ProfileSection::BuyProxy => view! { 
            <BuyProxyPage on_back=on_back_from_buy_proxy />
        }.into_any(),
        ProfileSection::CountrySelection => view! { <CountrySelectionPage on_back=on_back_from_country_selection /> }.into_any(),
        ProfileSection::StateSelection => view! { <StateSelectionPage on_back=on_back_from_state_selection /> }.into_any(),
        ProfileSection::CitySelection => view! { <CitySelectionPage on_back=on_back_from_city_selection /> }.into_any(),
        ProfileSection::ZipCodeSelection => view! { <ZipCodeSelectionPage on_back=on_back_from_zip_code_selection /> }.into_any(),
        ProfileSection::IncludeAsnSelection => view! { <DynamicLocationSelectionPage location_type=LocationType::IncludeAsn on_back=on_back_from_include_asn_selection /> }.into_any(),
        ProfileSection::ExcludeAsnSelection => view! { <DynamicLocationSelectionPage location_type=LocationType::ExcludeAsn on_back=on_back_from_exclude_asn_selection /> }.into_any(),
        ProfileSection::Whitelist => view! { <WhitelistPage /> }.into_any(),
        ProfileSection::ReferralSystem => view! { <ReferralPage /> }.into_any(),
        _ => view! {
            <Card 
                variant=CardVariant::L2
                max_width="flex-1" 
                padding="p-3" 
                class="w-full"
                id="profile-card"
            >
                <h2 class="text-2xl font-bold text-white mb-6" id="profile-title">
                    {t8s!("Profile")}
                </h2>
                <p class="text-gray-300 text-lg" id="profile-content">
                    "Default content"
                </p>
            </Card>
        }.into_any(),
    }
}


