//! `ActivitiesCTAView` — per-activity CTA section rendered below markdown.
//!
//! Reads activity-specific metadata from `UnifiedContentItem.metadata` (JSONB),
//! determines the download-gate state via `server_check_activity_access`, and
//! renders: Slidev iframe, download gate, internal questionnaire, repository
//! link, and image gallery.

use leptos::prelude::*;
use rustelo_core_lib::content::UnifiedContentItem;

use super::questionnaire::QuestionnaireForm;
use super::server_fns::{
    server_check_activity_access, server_get_questionnaire_definition, ActivityAccessStatus,
};

// ── Metadata helpers
// ──────────────────────────────────────────────────────────

fn meta_str(item: &UnifiedContentItem, key: &str) -> Option<String> {
    item.metadata
        .get(key)
        .and_then(|v| v.as_str())
        .map(str::to_string)
}

fn meta_bool(item: &UnifiedContentItem, key: &str) -> bool {
    item.metadata
        .get(key)
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
}

// ── Component
// ─────────────────────────────────────────────────────────────────

/// CTA section rendered below the activity markdown content.
///
/// Handles slides embed, gated PDF download, external / internal questionnaire
/// flow, repository link, and image gallery.  All data comes from
/// `item.metadata` so no schema change to `UnifiedContentItem` is needed.
#[component]
pub fn ActivitiesCTAView(
    item: UnifiedContentItem,
    #[prop(default = "en".to_string())] language: String,
) -> impl IntoView {
    let slides_id = meta_str(&item, "slides_id");
    let pdf_filename = meta_str(&item, "pdf_filename");
    let repository_url = meta_str(&item, "repository_url");
    let questionnaire_type =
        meta_str(&item, "questionnaire_type").unwrap_or_else(|| "external".to_string());
    let questionnaire_url = meta_str(&item, "questionnaire_url");
    let download_requires_auth = meta_bool(&item, "download_requires_auth");
    let download_requires_questionnaire = meta_bool(&item, "download_requires_questionnaire");
    let questionnaire_config = meta_str(&item, "questionnaire_config");

    // Gallery is stored as a JSON array of relative image paths.
    let gallery: Vec<String> = item
        .metadata
        .get("gallery")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default();

    let activity_id = StoredValue::new(item.id.clone());
    let lang = StoredValue::new(language);
    let q_config = StoredValue::new(questionnaire_config);

    // Server-function resource — resolves once after hydration.
    let access = Resource::new(
        || (),
        move |_| server_check_activity_access(activity_id.get_value()),
    );

    // For the internal questionnaire state: whether to show the form.
    let (show_questionnaire, set_show_questionnaire) = signal(false);
    let (download_unlocked, set_download_unlocked) = signal(false);

    // Lazy-load the questionnaire definition the first time the form is shown.
    // The resource fires once `show_questionnaire` flips to `true`; subsequent
    // `false → true` transitions reuse the cached result.
    let questionnaire_def = Resource::new(
        move || show_questionnaire.get(),
        move |show| async move {
            if !show {
                return None;
            }
            match q_config.get_value() {
                Some(name) => server_get_questionnaire_definition(name).await.ok(),
                None => None,
            }
        },
    );

    view! {
        <div class="space-y-8 mt-8">

            // ── Slidev embed ───────────────────────────────────────────────
            {slides_id.map(|sid| {
                let src = format!("/slides/{}/", sid);
                view! {
                    <section class="w-full">
                        <iframe
                            src=src
                            class="w-full rounded-lg border border-base-300 shadow-lg"
                            style="height: 60vh; min-height: 400px;"
                            allowfullscreen
                            title="Slidev presentation"
                        />
                    </section>
                }
            })}

            // ── Download section ──────────────────────────────────────────
            {if pdf_filename.is_some() && download_requires_auth {
                let pdf_fn = pdf_filename.clone().unwrap_or_default();
                let act_id = activity_id.get_value();
                let q_type = questionnaire_type.clone();
                let q_url = questionnaire_url.clone();

                view! {
                    <section class="p-6 rounded-lg border border-base-300 bg-base-200">
                        <Suspense fallback=move || view! { <div class="animate-pulse h-12 bg-base-300 rounded" /> }>
                            {move || {
                                let pdf = pdf_fn.clone();
                                let aid = act_id.clone();
                                let qt = q_type.clone();
                                let qu = q_url.clone();
                                let _lang_val = lang.get_value();
                                access.get().map(|result| {
                                    let status: ActivityAccessStatus = result.unwrap_or(ActivityAccessStatus {
                                        authenticated: false,
                                        questionnaire_completed: false,
                                        can_download: false,
                                    });

                                    let can_dl = status.can_download || download_unlocked.get();

                                    if can_dl {
                                        // Download available
                                        let download_url = format!("/api/activities/download/{}?pdf={}", aid, pdf);
                                        view! {
                                            <div class="flex flex-col items-center gap-4">
                                                <p class="text-success font-semibold">
                                                    "Your download is ready."
                                                </p>
                                                <a
                                                    href=download_url
                                                    class="ds-btn-primary"
                                                    download
                                                >
                                                    "Download PDF"
                                                </a>
                                            </div>
                                        }.into_any()
                                    } else if !status.authenticated {
                                        // Not logged in
                                        view! {
                                            <div class="flex flex-col items-center gap-4 text-center">
                                                <p class="ds-text-secondary">
                                                    "Sign in to download the PDF for this activity."
                                                </p>
                                                <a href="/login" class="ds-btn-secondary">
                                                    "Sign in"
                                                </a>
                                            </div>
                                        }.into_any()
                                    } else if download_requires_questionnaire && !status.questionnaire_completed {
                                        // Logged in, questionnaire pending
                                        if qt == "internal" {
                                            // Show inline form trigger
                                            view! {
                                                <div class="flex flex-col items-center gap-4 text-center">
                                                    <p class="ds-text-secondary">
                                                        "Complete the evaluation to unlock the PDF download."
                                                    </p>
                                                    {move || {
                                                        if show_questionnaire.get() {
                                                            view! { <span /> }.into_any()
                                                        } else {
                                                            view! {
                                                                <button
                                                                    class="ds-btn-primary"
                                                                    on:click=move |_| set_show_questionnaire.set(true)
                                                                >
                                                                    "Complete evaluation"
                                                                </button>
                                                            }.into_any()
                                                        }
                                                    }}
                                                </div>
                                            }.into_any()
                                        } else {
                                            // External questionnaire link
                                            let ext_url = qu.unwrap_or_default();
                                            view! {
                                                <div class="flex flex-col items-center gap-4 text-center">
                                                    <p class="ds-text-secondary">
                                                        "Complete the evaluation to unlock the PDF download."
                                                    </p>
                                                    <a
                                                        href=ext_url
                                                        class="ds-btn-primary"
                                                        target="_blank"
                                                        rel="noopener"
                                                    >
                                                        "Complete evaluation"
                                                    </a>
                                                </div>
                                            }.into_any()
                                        }
                                    } else {
                                        // Logged in, no questionnaire required
                                        let download_url = format!("/api/activities/download/{}?pdf={}", aid, pdf);
                                        view! {
                                            <div class="flex flex-col items-center gap-4">
                                                <a href=download_url class="ds-btn-primary" download>
                                                    "Download PDF"
                                                </a>
                                            </div>
                                        }.into_any()
                                    }
                                })
                            }}
                        </Suspense>

                        // Inline internal questionnaire
                        {move || {
                            if show_questionnaire.get() {
                                let aid2 = activity_id.get_value();
                                view! {
                                    <div class="mt-6">
                                        <h3 class="text-lg font-semibold ds-text mb-4">
                                            "Activity Evaluation"
                                        </h3>
                                        <Suspense fallback=move || view! {
                                            <div class="animate-pulse h-8 bg-base-300 rounded" />
                                        }>
                                            {move || questionnaire_def.get().flatten().map(|def| {
                                                let aid3 = aid2.clone();
                                                view! {
                                                    <QuestionnaireForm
                                                        definition=def
                                                        activity_id=aid3
                                                        on_submit_complete=Callback::new(move |_: ()| {
                                                            set_show_questionnaire.set(false);
                                                            set_download_unlocked.set(true);
                                                        })
                                                    />
                                                }
                                            })}
                                        </Suspense>
                                    </div>
                                }.into_any()
                            } else {
                                view! { <span /> }.into_any()
                            }
                        }}
                    </section>
                }.into_any()
            } else if let Some(ref pdf) = pdf_filename {
                // No auth required — direct download
                let download_url = format!("/api/activities/download/{}?pdf={}", activity_id.get_value(), pdf);
                view! {
                    <section class="flex justify-center">
                        <a href=download_url class="ds-btn-primary" download>
                            "Download PDF"
                        </a>
                    </section>
                }.into_any()
            } else {
                view! { <span /> }.into_any()
            }}

            // ── Repository link ────────────────────────────────────────────
            {repository_url.map(|url| {
                view! {
                    <section class="flex items-center gap-2">
                        <span class="font-semibold ds-text">"Source code:"</span>
                        <a href=url class="link link-primary" target="_blank" rel="noopener">
                            "View on GitHub"
                        </a>
                    </section>
                }
            })}

            // ── Gallery ────────────────────────────────────────────────────
            {if !gallery.is_empty() {
                view! {
                    <section>
                        <h3 class="text-lg font-semibold ds-text mb-4">"Gallery"</h3>
                        <div class="grid grid-cols-2 md:grid-cols-3 gap-4">
                            {gallery.into_iter().enumerate().map(|(i, path)| {
                                view! {
                                    <img
                                        src=path
                                        class="rounded-lg w-full h-48 object-cover cursor-pointer hover:opacity-90 transition-opacity"
                                        alt=format!("Activity photo {}", i + 1)
                                    />
                                }
                            }).collect::<Vec<_>>()}
                        </div>
                    </section>
                }.into_any()
            } else {
                view! { <span /> }.into_any()
            }}

        </div>
    }
}
