//! Unified WorkRequest Page Component

use leptos::prelude::*;
use rustelo_components_leptos::HtmlContent;
use rustelo_components_leptos::server_send_contact_form;
use rustelo_content::rustelo_core_lib::i18n::content_helper::create_content_provider_reactive;

#[component]
pub fn UnifiedWorkRequestPage(
    #[prop(default = rustelo_content::rustelo_core_lib::config::get_default_language().to_string())]
    _language: String,
    #[prop(optional)] lang_content: Option<std::collections::HashMap<String, String>>,
) -> impl IntoView {
    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 company = RwSignal::new(String::new());
    let project_type = RwSignal::new(String::new());
    let project_description = RwSignal::new(String::new());
    let current_situation = RwSignal::new(String::new());
    let goals = RwSignal::new(String::new());
    let technical_requirements = RwSignal::new(String::new());
    let timeline = RwSignal::new(String::new());
    let budget = RwSignal::new(String::new());
    let contact_method = 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 company_val = company.get_untracked();
        let pt = project_type.get_untracked();
        let pd = project_description.get_untracked();
        let cs = current_situation.get_untracked();
        let g = goals.get_untracked();
        let tr = technical_requirements.get_untracked();
        let tl = timeline.get_untracked();
        let b = budget.get_untracked();
        let cm = contact_method.get_untracked();

        let subject = format!("Work Request: {}", if pt.is_empty() { "General" } else { &pt });
        let message = format!(
            "Company: {company}\n\
             Project type: {pt}\n\
             Description:\n{pd}\n\n\
             Current situation:\n{cs}\n\n\
             Goals:\n{g}\n\n\
             Technical requirements:\n{tr}\n\
             Timeline: {tl}\n\
             Budget: {b}\n\
             Preferred contact: {cm}",
            company = if company_val.is_empty() { "—".to_string() } else { company_val },
            pt = if pt.is_empty() { "—".to_string() } else { pt },
            pd = if pd.is_empty() { "—".to_string() } else { pd },
            cs = if cs.is_empty() { "—".to_string() } else { cs },
            g = if g.is_empty() { "—".to_string() } else { g },
            tr = if tr.is_empty() { "—".to_string() } else { tr },
            tl = if tl.is_empty() { "—".to_string() } else { tl },
            b = if b.is_empty() { "—".to_string() } else { b },
            cm = if cm.is_empty() { "—".to_string() } else { cm },
        );

        submitting.set(true);
        submit_ok.set(false);
        submit_error.set(None);
        send_action.dispatch((n, em, subject, message));
    };

    // React to action completion
    Effect::new(move |_| {
        if let Some(result) = send_action.value().get() {
            submitting.set(false);
            match result {
                Ok(_) => {
                    submit_ok.set(true);
                    // Clear fields
                    name.set(String::new());
                    email.set(String::new());
                    company.set(String::new());
                    project_type.set(String::new());
                    project_description.set(String::new());
                    current_situation.set(String::new());
                    goals.set(String::new());
                    technical_requirements.set(String::new());
                    timeline.set(String::new());
                    budget.set(String::new());
                    contact_method.set(String::new());
                }
                Err(e) => {
                    submit_error.set(Some(e.to_string()));
                }
            }
        }
    });

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

            // Main Form Section
            <div class="py-8">
                <div class="mx-auto max-w-4xl px-6 lg:px-8">
                    <div class="ds-bg ds-rounded-lg ds-shadow-lg p-8">
                        <form on:submit=on_submit class="space-y-8">
                            // Contact Information Section
                            <div>
                                <h2 class="ds-heading-2 ds-text mb-4">
                                    {content.t("work-request-contact-info")}
                                </h2>
                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                    <div>
                                        <label for="work-request-name" class="block ds-text font-medium mb-2">
                                            {content.t("work-request-your-name")}
                                        </label>
                                        <input
                                            type="text"
                                            id="work-request-name"
                                            name="name"
                                            required
                                            prop:value=name
                                            on:input=move |ev| name.set(event_target_value(&ev))
                                            class="ds-input w-full px-4 py-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            placeholder={content.t("work-request-your-name-placeholder")}
                                        />
                                    </div>
                                    <div>
                                        <label for="work-request-email" class="block ds-text font-medium mb-2">
                                            {content.t("work-request-your-email")}
                                        </label>
                                        <input
                                            type="email"
                                            id="work-request-email"
                                            name="email"
                                            required
                                            prop:value=email
                                            on:input=move |ev| email.set(event_target_value(&ev))
                                            class="ds-input w-full px-4 py-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            placeholder={content.t("work-request-your-email-placeholder")}
                                        />
                                    </div>
                                </div>
                                <div class="mt-4">
                                    <label for="work-request-company" class="block ds-text font-medium mb-2">
                                        {content.t("work-request-company")}
                                    </label>
                                    <input
                                        type="text"
                                        id="work-request-company"
                                        name="company"
                                        prop:value=company
                                        on:input=move |ev| company.set(event_target_value(&ev))
                                        class="ds-input w-full px-4 py-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        placeholder={content.t("work-request-company-placeholder")}
                                    />
                                </div>
                            </div>

                            // Project Details Section
                            <div>
                                <h2 class="ds-heading-2 ds-text mb-4">
                                    {content.t("work-request-project-info")}
                                </h2>

                                <div class="mb-4">
                                    <label for="work-request-project-type" class="block ds-text font-medium mb-2">
                                        {content.t("work-request-project-type-label")}
                                    </label>
                                    <select
                                        id="work-request-project-type"
                                        name="project_type"
                                        required
                                        prop:value=project_type
                                        on:change=move |ev| project_type.set(event_target_value(&ev))
                                        class="ds-select w-full px-4 py-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    >
                                        <option value="">{content.t("work-request-project-type-placeholder")}</option>
                                        <option value="new-project">{content.t("work-request-project-type-new")}</option>
                                        <option value="existing-project">{content.t("work-request-project-type-existing")}</option>
                                        <option value="infrastructure">{content.t("work-request-project-type-infrastructure")}</option>
                                        <option value="consulting">{content.t("work-request-project-type-consulting")}</option>
                                        <option value="mentoring">{content.t("work-request-project-type-mentoring")}</option>
                                        <option value="training">{content.t("work-request-project-type-training")}</option>
                                        <option value="audit">{content.t("work-request-project-type-audit")}</option>
                                        <option value="other">{content.t("work-request-project-type-other")}</option>
                                    </select>
                                </div>

                                <div class="mb-4">
                                    <label for="work-request-project-description" class="block ds-text font-medium mb-2">
                                        {content.t("work-request-project-description-label")}
                                    </label>
                                    <textarea
                                        id="work-request-project-description"
                                        name="project_description"
                                        required
                                        rows="5"
                                        prop:value=project_description
                                        on:input=move |ev| project_description.set(event_target_value(&ev))
                                        class="ds-textarea w-full px-4 py-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        placeholder={content.t("work-request-project-description-placeholder")}
                                    ></textarea>
                                </div>

                                <div class="mb-4">
                                    <label for="work-request-current-situation" class="block ds-text font-medium mb-2">
                                        {content.t("work-request-current-situation-label")}
                                    </label>
                                    <textarea
                                        id="work-request-current-situation"
                                        name="current_situation"
                                        rows="3"
                                        prop:value=current_situation
                                        on:input=move |ev| current_situation.set(event_target_value(&ev))
                                        class="ds-textarea w-full px-4 py-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        placeholder={content.t("work-request-current-situation-placeholder")}
                                    ></textarea>
                                </div>

                                <div class="mb-4">
                                    <label for="work-request-goals" class="block ds-text font-medium mb-2">
                                        {content.t("work-request-goals-label")}
                                    </label>
                                    <textarea
                                        id="work-request-goals"
                                        name="goals"
                                        required
                                        rows="3"
                                        prop:value=goals
                                        on:input=move |ev| goals.set(event_target_value(&ev))
                                        class="ds-textarea w-full px-4 py-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        placeholder={content.t("work-request-goals-placeholder")}
                                    ></textarea>
                                </div>

                                <div class="mb-4">
                                    <label for="work-request-technical-requirements" class="block ds-text font-medium mb-2">
                                        {content.t("work-request-technical-requirements-label")}
                                    </label>
                                    <textarea
                                        id="work-request-technical-requirements"
                                        name="technical_requirements"
                                        rows="4"
                                        prop:value=technical_requirements
                                        on:input=move |ev| technical_requirements.set(event_target_value(&ev))
                                        class="ds-textarea w-full px-4 py-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        placeholder={content.t("work-request-technical-requirements-placeholder")}
                                    ></textarea>
                                </div>
                            </div>

                            // Timeline and Budget Section
                            <div>
                                <h2 class="ds-heading-2 ds-text mb-4">
                                    {content.t("work-request-timeline-budget")}
                                </h2>

                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                    <div>
                                        <label for="work-request-timeline" class="block ds-text font-medium mb-2">
                                            {content.t("work-request-timeline-label")}
                                        </label>
                                        <select
                                            id="work-request-timeline"
                                            name="timeline"
                                            required
                                            prop:value=timeline
                                            on:change=move |ev| timeline.set(event_target_value(&ev))
                                            class="ds-select w-full px-4 py-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        >
                                            <option value="">{content.t("work-request-timeline-placeholder")}</option>
                                            <option value="asap">{content.t("work-request-timeline-asap")}</option>
                                            <option value="1-month">{content.t("work-request-timeline-1-month")}</option>
                                            <option value="1-3-months">{content.t("work-request-timeline-1-3-months")}</option>
                                            <option value="3-6-months">{content.t("work-request-timeline-3-6-months")}</option>
                                            <option value="6+ months">{content.t("work-request-timeline-6plus")}</option>
                                            <option value="flexible">{content.t("work-request-timeline-flexible")}</option>
                                        </select>
                                    </div>

                                    <div>
                                        <label for="work-request-budget" class="block ds-text font-medium mb-2">
                                            {content.t("work-request-budget")}
                                        </label>
                                        <select
                                            id="work-request-budget"
                                            name="budget"
                                            prop:value=budget
                                            on:change=move |ev| budget.set(event_target_value(&ev))
                                            class="ds-select w-full px-4 py-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        >
                                            <option value="">{"Select budget range"}</option>
                                            <option value="<5k">{content.t("work-request-budget-under-5k")}</option>
                                            <option value="5k-15k">{content.t("work-request-budget-5k-15k")}</option>
                                            <option value="15k-30k">{content.t("work-request-budget-15k-50k")}</option>
                                            <option value="30k-50k">{content.t("work-request-budget-50k-plus")}</option>
                                            <option value="50k+">{content.t("work-request-budget-50k-plus")}</option>
                                            <option value="hourly">"Hourly rate"</option>
                                            <option value="discuss">{content.t("work-request-budget-discuss")}</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            // Communication Preferences Section
                            <div>
                                <h2 class="ds-heading-2 ds-text mb-4">
                                    {content.t("work-request-communication-preferences")}
                                </h2>

                                <div>
                                    <label for="work-request-contact-method" class="block ds-text font-medium mb-2">
                                        {content.t("work-request-contact-method-label")}
                                    </label>
                                    <select
                                        id="work-request-contact-method"
                                        name="contact_method"
                                        required
                                        prop:value=contact_method
                                        on:change=move |ev| contact_method.set(event_target_value(&ev))
                                        class="ds-select w-full px-4 py-3 ds-border ds-rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    >
                                        <option value="">{content.t("work-request-contact-method-placeholder")}</option>
                                        <option value="email">{content.t("work-request-contact-method-email")}</option>
                                        <option value="telegram">{content.t("work-request-contact-method-telegram")}</option>
                                        <option value="video-call">{content.t("work-request-contact-method-video")}</option>
                                        <option value="phone">{content.t("work-request-contact-method-phone")}</option>
                                    </select>
                                </div>
                            </div>

                            // Submit Button + Feedback
                            <div class="pt-6 border-t ds-border">
                                // Success banner
                                {
                                    let success_label = content.t("work-request-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="mb-4 p-4 bg-green-50 border border-green-200 ds-rounded text-green-800 text-sm">
                                                {success_label.clone()}
                                            </div>
                                        })
                                    }
                                }
                                // Error banner
                                {move || {
                                    #[cfg(target_arch = "wasm32")]
                                    let err = submit_error.get();
                                    #[cfg(not(target_arch = "wasm32"))]
                                    let err = submit_error.get_untracked();
                                    err.map(|err| view! {
                                        <div class="mb-4 p-4 bg-red-50 border border-red-200 ds-rounded text-red-800 text-sm">
                                            {err}
                                        </div>
                                    })
                                }}

                                <button
                                    type="submit"
                                    name="submit"
                                    disabled=move || {
                                        #[cfg(target_arch = "wasm32")]
                                        { submitting.get() }
                                        #[cfg(not(target_arch = "wasm32"))]
                                        { submitting.get_untracked() }
                                    }
                                    class="w-full ds-btn-primary py-4 px-6 ds-rounded font-medium text-lg disabled:opacity-60 disabled:cursor-not-allowed"
                                >
                                    {
                                        let submit_btn_label = content.t("work-request-submit-btn");
                                        move || {
                                            #[cfg(target_arch = "wasm32")]
                                            let is_submitting = submitting.get();
                                            #[cfg(not(target_arch = "wasm32"))]
                                            let is_submitting = submitting.get_untracked();
                                            if is_submitting {
                                                "Sending…".to_string()
                                            } else {
                                                submit_btn_label.clone()
                                            }
                                        }
                                    }
                                </button>
                                <p class="ds-caption ds-text-secondary text-center mt-3">
                                    {content.t("work-request-submit-note")}
                                </p>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            // What Happens Next Section
            <section class="py-16 ds-bg-secondary">
                <div class="mx-auto max-w-4xl px-6 lg:px-8">
                    <h2 class="ds-heading-1 ds-text text-center mb-12">
                        {content.t("work-request-what-happens-next")}
                    </h2>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                        <div class="text-center">
                            <div class="w-16 h-16 ds-bg ds-rounded-full flex items-center justify-center mx-auto mb-4">
                                <span class="text-2xl">"📋"</span>
                            </div>
                            <h3 class="ds-heading-3 ds-text mb-2">
                                {content.t("work-request-step-1-title")}
                            </h3>
                            <p class="ds-text-secondary">
                                {content.t("work-request-step-1-description")}
                            </p>
                        </div>

                        <div class="text-center">
                            <div class="w-16 h-16 ds-bg ds-rounded-full flex items-center justify-center mx-auto mb-4">
                                <span class="text-2xl">"💬"</span>
                            </div>
                            <h3 class="ds-heading-3 ds-text mb-2">
                                {content.t("work-request-step-2-title")}
                            </h3>
                            <p class="ds-text-secondary">
                                {content.t("work-request-step-2-description")}
                            </p>
                        </div>

                        <div class="text-center">
                            <div class="w-16 h-16 ds-bg ds-rounded-full flex items-center justify-center mx-auto mb-4">
                                <span class="text-2xl">"📄"</span>
                            </div>
                            <h3 class="ds-heading-3 ds-text mb-2">
                                {content.t("work-request-step-3-title")}
                            </h3>
                            <p class="ds-text-secondary">
                                {content.t("work-request-step-3-description")}
                            </p>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    }
}
