//! Unified Contact Page Component using shared delegation patterns
//!
//! This module provides a unified interface that automatically selects between
//! client-side reactive and server-side static implementations based on
//! context.

use leptos::prelude::*;
use rustelo_components_leptos::server_send_contact_form;
use rustelo_core_lib::i18n::content_helper::create_content_provider_reactive;
#[cfg(target_arch = "wasm32")]
use rustelo_core_lib::utils::nav;

/// Unified Contact Page component that works in both SSR and client contexts
/// Takes structured content data instead of individual parameters
#[component]
pub fn UnifiedContactPage(
    #[prop(default = rustelo_core_lib::config::get_default_language().to_string())]
    _language: String,
    #[prop(optional)] lang_content: Option<std::collections::HashMap<String, String>>,
) -> impl IntoView {
    // Use DRY content accessor helper
    let content = create_content_provider_reactive(lang_content.clone());

    // Form field signals
    let name = RwSignal::new(String::new());
    let email = RwSignal::new(String::new());
    let subject = RwSignal::new(String::new());
    let message = RwSignal::new(String::new());

    // Submission state
    let submitting = RwSignal::new(false);
    let submit_ok = RwSignal::new(false);
    let submit_error = RwSignal::new(Option::<String>::None);

    let send_action = Action::new(move |(n, em, s, msg): &(String, String, String, String)| {
        let n = n.clone();
        let em = em.clone();
        let s = s.clone();
        let msg = msg.clone();
        async move { server_send_contact_form(n, em, s, msg).await }
    });

    let on_submit = move |ev: leptos::ev::SubmitEvent| {
        ev.prevent_default();
        let n = name.get_untracked();
        let em = email.get_untracked();
        if n.trim().is_empty() || em.trim().is_empty() {
            submit_error.set(Some("Name and email are required.".to_string()));
            return;
        }
        let s = subject.get_untracked();
        let msg = message.get_untracked();
        submitting.set(true);
        submit_ok.set(false);
        submit_error.set(None);
        send_action.dispatch((n, em, s, msg));
    };

    Effect::new(move |_| {
        if let Some(result) = send_action.value().get() {
            submitting.set(false);
            match result {
                Ok(_) => {
                    submit_ok.set(true);
                    name.set(String::new());
                    email.set(String::new());
                    subject.set(String::new());
                    message.set(String::new());
                }
                Err(e) => submit_error.set(Some(e.to_string())),
            }
        }
    });

    // Pre-extract all content to avoid closure ownership issues
    let contact_page_subtitle = content.t("contact-page-subtitle");
    let contact_work_request_url = content.t("contact-work-request-url");
    let contact_request_quote = content.t("contact-request-quote");

    // Clone values that are used multiple times
    let contact_request_quote_clone = contact_request_quote.clone();
    let contact_work_request_url_clone = contact_work_request_url.clone();

    view! {
        <div class="ds-bg-page py-ds-6">
            <section class="ds-container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                // Header Section
                <div class="text-center mb-ds-8">
                    <h1 class="ds-heading-1 ds-text mb-ds-4">
                        {content.t("contact-page-title")}
                    </h1>
                    <rustelo_components_leptos::HtmlContent
                      content={contact_page_subtitle}
                      class="mt-ds-6 ds-body ds-text-secondary max-w-2xl mx-auto".to_string()
                    />
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-3 gap-ds-6">
                    // Contact Information Sidebar
                    <div class="lg:col-span-1">
                        <div class="ds-bg ds-rounded-lg ds-shadow-sm p-ds-6">
                            <h2 class="ds-heading-2 ds-text mb-ds-6">
                                {content.t("contact-lets-connect")}
                            </h2>

                            <div class="space-y-6">
                                // Email Contact
                                <div class="flex items-start">
                                    <div class="flex-shrink-0">
                                        <div class="w-10 h-10 ds-bg-secondary ds-rounded-lg flex items-center justify-center">
                                            <span class="text-lg">"📧"</span>
                                        </div>
                                    </div>
                                    <div class="ml-4">
                                        <h3 class="ds-heading-4 ds-text">{content.t("contact-email-contact")}</h3>
                                        <p class="ds-text-secondary">"hello@jesusperez.pro"</p>
                                        <p class="ds-caption ds-text-muted">{content.t("contact-best-for-detailed")}</p>
                                    </div>
                                </div>

                                // Telegram Contact
                                <div class="flex items-start">
                                    <div class="flex-shrink-0">
                                        <div class="w-10 h-10 ds-bg-secondary ds-rounded-lg flex items-center justify-center">
                                            <span class="text-lg">"💬"</span>
                                        </div>
                                    </div>
                                    <div class="ml-4">
                                        <h3 class="ds-heading-4 ds-text">{content.t("contact-telegram-contact")}</h3>
                                        <p class="ds-text-secondary">"@jesusperez_dev"</p>
                                        <p class="ds-caption ds-text-muted">{content.t("contact-quick-questions")}</p>
                                    </div>
                                </div>

                                // Schedule Call
                                <div class="flex items-start">
                                    <div class="flex-shrink-0">
                                        <div class="w-10 h-10 ds-bg-secondary ds-rounded-lg flex items-center justify-center">
                                            <span class="text-lg">"📞"</span>
                                        </div>
                                    </div>
                                    <div class="ml-4">
                                        <h3 class="ds-heading-4 ds-text">{content.t("contact-schedule-call")}</h3>
                                        <p class="ds-text-secondary">{content.t("contact-consultation-30min")}</p>
                                        <a href="https://calendly.com/jesusperez-dev" target="_blank" rel="noopener noreferrer" class="ds-caption ds-text font-medium hover:ds-text-secondary">
                                            {content.t("contact-book-time-slot")}
                                        </a>
                                    </div>
                                </div>
                            </div>

                            // Professional Networks
                            <div class="mt-ds-6 pt-ds-6 border-t ds-border">
                                <h3 class="ds-heading-4 ds-text mb-ds-4">{content.t("contact-professional-networks")}</h3>
                                <div class="space-y-2">
                                    <a href="https://www.linkedin.com/in/jesusperezlorenzo/" target="_blank" rel="noopener noreferrer" class="no-underline block ds-text-secondary hover:ds-text ds-caption">
                                        {content.t("contact-linkedin-profile")}
                                    </a>
                                    <a href="https://github.com/jesusperezlorenzo" target="_blank" rel="noopener noreferrer" class="no-underline block ds-text-secondary hover:ds-text ds-caption">
                                        {content.t("contact-git-profile")}
                                    </a>
                                    <a href={content.t("contact-blog-url")} class="no-underline block ds-text-secondary hover:ds-text ds-caption">
                                        {content.t("contact-read-my-blog")}
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    // Contact Form - Temporarily simplified for SSR compatibility
                    <div class="lg:col-span-2">
                        <div class="ds-bg ds-rounded-lg ds-shadow-sm p-ds-6">
                            <div class="form-header mb-ds-6">
                                <h2 class="ds-heading-2 ds-text mb-2">
                                    {content.t("contact-send-message")}
                                </h2>
                                <p class="ds-text-secondary">
                                    {content.t("contact-contact-form-description")}
                                </p>
                            </div>

                            <form on:submit=on_submit class="space-y-ds-4">
                                // Name + Email row
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-ds-4">
                                    <div class="relative">
                                        <label for="contact-form-name" class="ds-text font-medium block mb-2">
                                            {content.t("contact-name-label")}
                                        </label>
                                        <input
                                            type="text"
                                            id="contact-form-name"
                                            required
                                            prop:value=name
                                            on:input=move |ev| name.set(event_target_value(&ev))
                                            class="ds-input w-full p-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            placeholder={content.t("contact-name-placeholder")}
                                        />
                                    </div>

                                    // Email Field
                                    <div class="relative">
                                        <label for="contact-form-email" class="ds-text font-medium block mb-2">
                                            {content.t("contact-email-label")}
                                        </label>
                                        <input
                                            type="email"
                                            id="contact-form-email"
                                            required
                                            prop:value=email
                                            on:input=move |ev| email.set(event_target_value(&ev))
                                            class="ds-input w-full p-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            placeholder={content.t("contact-email-placeholder")}
                                        />
                                    </div>
                                </div>

                                // Subject Field
                                <div class="relative">
                                    <label for="contact-form-subject" class="ds-text font-medium block mb-2">
                                        {content.t("contact-subject-label")}
                                    </label>
                                    <input
                                        type="text"
                                        id="contact-form-subject"
                                        required
                                        prop:value=subject
                                        on:input=move |ev| subject.set(event_target_value(&ev))
                                        class="ds-input w-full p-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        placeholder={content.t("contact-subject-placeholder")}
                                    />
                                </div>

                                // Message Field
                                <div class="relative">
                                    <label for="contact-form-message" class="ds-text font-medium block mb-2">
                                        {content.t("contact-message-label")}
                                    </label>
                                    <textarea
                                        id="contact-form-message"
                                        rows="6"
                                        required
                                        prop:value=message
                                        on:input=move |ev| message.set(event_target_value(&ev))
                                        class="ds-textarea w-full p-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500 resize-vertical"
                                        placeholder={content.t("contact-message-placeholder")}
                                    ></textarea>
                                </div>

                                // Submit Button + Feedback
                                <div class="flex flex-col gap-2">
                                    {
                                        let success_label = content.t("contact-submit-success");
                                        move || {
                                            #[cfg(target_arch = "wasm32")]
                                            let ok = submit_ok.get();
                                            #[cfg(not(target_arch = "wasm32"))]
                                            let ok = submit_ok.get_untracked();
                                            ok.then(|| view! {
                                                <div class="p-4 bg-green-50 border border-green-200 ds-rounded text-green-800 text-sm">
                                                    {success_label.clone()}
                                                </div>
                                            })
                                        }
                                    }
                                    {move || {
                                        #[cfg(target_arch = "wasm32")]
                                        let err = submit_error.get();
                                        #[cfg(not(target_arch = "wasm32"))]
                                        let err = submit_error.get_untracked();
                                        err.map(|e| view! {
                                            <div class="p-4 bg-red-50 border border-red-200 ds-rounded text-red-800 text-sm">
                                                {e}
                                            </div>
                                        })
                                    }}
                                    <div class="flex justify-end">
                                        <button
                                            type="submit"
                                            disabled=move || {
                                                #[cfg(target_arch = "wasm32")]
                                                { submitting.get() }
                                                #[cfg(not(target_arch = "wasm32"))]
                                                { submitting.get_untracked() }
                                            }
                                            class="ds-btn-primary px-8 py-3 font-medium ds-rounded transition-colors duration-200 disabled:opacity-60 disabled:cursor-not-allowed"
                                        >
                                            {
                                                let send_label = content.t("contact-send-message-btn");
                                                move || {
                                                    #[cfg(target_arch = "wasm32")]
                                                    let is_busy = submitting.get();
                                                    #[cfg(not(target_arch = "wasm32"))]
                                                    let is_busy = submitting.get_untracked();
                                                    if is_busy {
                                                        "Sending…".to_string()
                                                    } else {
                                                        send_label.clone()
                                                    }
                                                }
                                            }
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                        // Response Time
                        <div class="mt-ds-6 p-ds-4 ds-bg-secondary ds-rounded-lg">
                            <h3 class="font-semibold ds-text mb-2">{content.t("contact-response-time")}</h3>
                            <p class="ds-caption ds-text-secondary">
                                {content.t("contact-response-time-text")}
                            </p>
                        </div>
                    </div>
                </div>

                // FAQ Section
                <div class="mt-ds-8">
                    <div class="ds-bg ds-rounded-lg ds-shadow-sm p-ds-6">
                        <h2 class="ds-heading-2 ds-text mb-ds-6 text-center">
                            {content.t("contact-frequently-asked-questions")}
                        </h2>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-ds-6">
                            // FAQ Item 1
                            <div>
                                <h3 class="ds-heading-4 ds-text mb-2">
                                    {content.t("contact-faq-what-projects")}
                                </h3>
                                <p class="ds-text-secondary">
                                    {content.t("contact-faq-what-projects-answer")}
                                </p>
                            </div>

                            // FAQ Item 2
                            <div>
                                <h3 class="ds-heading-4 ds-text mb-2">
                                    {content.t("contact-faq-remote-teams")}
                                </h3>
                                <p class="ds-text-secondary">
                                    {content.t("contact-faq-remote-teams-answer")}
                                </p>
                            </div>

                            // FAQ Item 3
                            <div>
                                <h3 class="ds-heading-4 ds-text mb-2">
                                    {content.t("contact-faq-pricing-approach")}
                                </h3>
                                <p class="ds-text-secondary">
                                    {content.t("contact-faq-pricing-answer")}
                                </p>
                            </div>

                            // FAQ Item 4
                            <div>
                                <h3 class="ds-heading-4 ds-text mb-2">
                                    {content.t("contact-faq-existing-projects")}
                                </h3>
                                <p class="ds-text-secondary">
                                    {content.t("contact-faq-existing-projects-answer")}
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                // Alternative Contact Methods
                <div class="mt-ds-8">
                    <div class="text-center">
                        <h2 class="ds-heading-2 ds-text mb-ds-6">
                            {content.t("contact-other-ways-connect")}
                        </h2>

                        <div class="grid grid-cols-1 md:grid-cols-3 gap-ds-6">
                            // Project Consultation
                            <div class="ds-bg-secondary ds-rounded-lg p-ds-6">
                                <div class="ds-text-secondary mb-ds-4">
                                    <span class="text-4xl">"🚀"</span>
                                </div>
                                <h3 class="ds-heading-4 ds-text mb-2">
                                    {content.t("contact-project-consultation")}
                                </h3>
                                <p class="ds-text-secondary mb-ds-4">
                                    {content.t("contact-consultation-help")}
                                </p>
                                <a href={contact_work_request_url_clone.clone()} class="no-underline ds-btn-primary"
                                    on:click=move |_ev| {
                                        #[cfg(target_arch = "wasm32")]
                                        {
                                            if let Some(set_path) = use_context::<WriteSignal<String>>() {
                                                _ev.prevent_default();
                                                nav::anchor_navigate(set_path, &contact_work_request_url_clone);
                                                rustelo_core_lib::utils::doc_scroll_to_top(100);
                                            }
                                        }
                                    }
                                >
                                  {contact_request_quote_clone}
                                </a>
                            </div>

                            // Mentoring Services
                            <div class="ds-bg-secondary ds-rounded-lg p-ds-6">
                                <div class="ds-text-secondary mb-ds-4">
                                    <span class="text-4xl">"🧑‍🏫"</span>
                                </div>
                                <h3 class="ds-heading-4 ds-text mb-2">
                                    {content.t("contact-mentoring-training")}
                                </h3>
                                <p class="ds-text-secondary mb-ds-4">
                                    {content.t("contact-mentoring-help")}
                                </p>
                                <a
                                    href=format!("{}#mentoring", content.t("contact-services-url"))
                                    class="ds-btn-primary"
                                >
                                    {content.t("contact-learn-more")}
                                </a>
                            </div>

                            // Speaking & Events
                            <div class="ds-bg-secondary ds-rounded-lg p-ds-6">
                                <div class="ds-text-secondary mb-ds-4">
                                    <span class="text-4xl">"🎤"</span>
                                </div>
                                <h3 class="ds-heading-4 ds-text mb-2">
                                    {content.t("contact-speaking-events")}
                                </h3>
                                <p class="ds-text-secondary mb-ds-4">
                                    {content.t("contact-speaking-help")}
                                </p>
                                <a
                                    href="mailto:hello@jesusperez.pro?subject=Speaking Opportunity"
                                    class="ds-btn-primary"
                                >
                                    {content.t("contact-get-in-touch")}
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    }
}
