// SPDX-License-Identifier: Apache-2.0
//! Create Share Link — generate a new private link for an album.
//!
//! Every option on this screen is reassuring rather than aggressive:
//! password-required is the default, expiry is encouraged, and the
//! generated link is shown only once the user has chosen.

use leptos::ev::Event;
use leptos::prelude::*;
use leptos_router::hooks::{use_navigate, use_params_map};
use wasm_bindgen::JsCast;

use crate::components::icons::{IconChevronLeft, IconCopy, IconLink, IconLock, IconShield};
use crate::state::{AppState, ToastKind};

#[derive(Clone, Copy, PartialEq, Eq)]
enum Expiry {
    Days7,
    Days30,
    Days90,
    Never,
}

impl Expiry {
    fn code(self) -> &'static str {
        match self {
            Self::Days7 => "7d",
            Self::Days30 => "30d",
            Self::Days90 => "90d",
            Self::Never => "never",
        }
    }
    fn label(self) -> &'static str {
        match self {
            Self::Days7 => "7 days (recommended)",
            Self::Days30 => "30 days",
            Self::Days90 => "90 days",
            Self::Never => "No expiry",
        }
    }
    fn description(self) -> &'static str {
        match self {
            Self::Days7 => "Short by default — easy to renew if needed.",
            Self::Days30 => "A month of access. Good for family events.",
            Self::Days90 => "A season. Use for projects with a defined end.",
            Self::Never => "The link stays valid until you revoke it.",
        }
    }
}

#[component]
pub fn CreateShareLinkPage() -> impl IntoView {
    let params = use_params_map();
    let album_id = Memo::new(move |_| params.with(|p| p.get("album_id").unwrap_or_default()));
    let navigate = use_navigate();
    let st = AppState::get();

    let name = RwSignal::new(String::from("Private link"));
    let expiry = RwSignal::new(Expiry::Days7);
    let require_password = RwSignal::new(true);
    let allow_download = RwSignal::new(false);
    let generated = RwSignal::new(false);

    let on_name = move |ev: Event| {
        if let Some(target) = ev.target() {
            if let Ok(input) = target.dyn_into::<web_sys::HtmlInputElement>() {
                name.set(input.value());
            }
        }
    };

    let make_nav_back = || {
        let nav = navigate.clone();
        let id = album_id;
        move |_| nav(&format!("/albums/{}/share", id.get()), Default::default())
    };
    let nav_back = make_nav_back();
    let nav_back_cancel = make_nav_back();
    let nav_done: Callback<()> = {
        let nav = navigate.clone();
        let id = album_id;
        Callback::new(move |_| {
            st.toast("Link created. Share it with care.", ToastKind::Success);
            nav(&format!("/albums/{}/share", id.get()), Default::default());
        })
    };
    let do_generate = move |_| generated.set(true);
    let do_copy = move |_| {
        st.toast("Link copied to clipboard.", ToastKind::Success);
    };

    view! {
        <div class="row" style="margin-bottom: 1.25rem; gap: 0.5rem;">
            <button class="btn btn--ghost btn--sm" on:click=nav_back>
                <IconChevronLeft size=16 />
                "Back to Share Center"
            </button>
        </div>

        <header class="screen-head">
            <div class="screen-head__eyebrow">"New private link"</div>
            <h1 class="screen-head__title">"Create a link only for them."</h1>
            <p class="screen-head__lead">
                "Private links are not discoverable. They can be revoked any time,
                password-protected, and given an automatic expiry."
            </p>
        </header>

        // Link name
        <div class="form-block">
            <label class="form-block__label" for="link-name">"Link nickname"</label>
            <p class="form-block__hint">
                "For your reference only. Recipients never see this name."
            </p>
            <input
                id="link-name"
                class="form-block__input"
                type="text"
                value=move || name.get()
                on:input=on_name
                placeholder="e.g. Grandma — birthday album"
            />
        </div>

        // Expiry
        <div class="section-head">
            <h2 class="section-head__title">"How long should it work?"</h2>
            <span class="section-head__rule"></span>
        </div>

        <div class="radio-cards">
            {[Expiry::Days7, Expiry::Days30, Expiry::Days90, Expiry::Never]
                .iter()
                .map(|&opt| {
                    let is_selected = Memo::new(move |_| expiry.get() == opt);
                    view! {
                        <label class="radio-card">
                            <input
                                type="radio"
                                name="expiry"
                                value=opt.code()
                                prop:checked=move || is_selected.get()
                                on:change=move |_| expiry.set(opt)
                            />
                            <div class="radio-card__body">
                                <div class="radio-card__title">{opt.label()}</div>
                                <div class="radio-card__desc">{opt.description()}</div>
                            </div>
                        </label>
                    }
                })
                .collect_view()}
        </div>

        // Toggles
        <div class="section-head" style="margin-top: 2rem;">
            <h2 class="section-head__title">"Extra protection"</h2>
            <span class="section-head__rule"></span>
        </div>

        <div class="card" style="margin-bottom: 1rem;">
            <label class="toggle-row">
                <div class="toggle-row__main">
                    <div class="toggle-row__title">
                        <IconLock size=14 />
                        "Require a password"
                    </div>
                    <div class="toggle-row__desc">
                        "Recommended. We will generate a short password to share separately."
                    </div>
                </div>
                <input
                    type="checkbox"
                    class="toggle"
                    prop:checked=move || require_password.get()
                    on:change=move |_| require_password.update(|v| *v = !*v)
                />
            </label>
        </div>

        <div class="card" style="margin-bottom: 2rem;">
            <label class="toggle-row">
                <div class="toggle-row__main">
                    <div class="toggle-row__title">"Allow download"</div>
                    <div class="toggle-row__desc">
                        "Off by default. Viewers can see photos but not save copies
                         unless you allow it."
                    </div>
                </div>
                <input
                    type="checkbox"
                    class="toggle"
                    prop:checked=move || allow_download.get()
                    on:change=move |_| allow_download.update(|v| *v = !*v)
                />
            </label>
        </div>

        // Generated link area (revealed after generation)
        <Show when=move || generated.get()>
            <div class="card" style="margin-bottom: 1.5rem; background: var(--paper-2);">
                <div class="form-block__label" style="margin-bottom: 0.5rem;">
                    <IconLink size=14 />
                    " Your private link"
                </div>
                <div class="row" style="gap: 0.5rem; align-items: stretch;">
                    <code class="link-display">
                        "https://hejpics.app/share/k3m9-x7vp-w2nt"
                    </code>
                    <button class="btn btn--ghost btn--sm" on:click=do_copy>
                        <IconCopy size=14 />
                        "Copy"
                    </button>
                </div>
                <Show when=move || require_password.get()>
                    <div style="margin-top: 1rem;">
                        <div class="form-block__label" style="margin-bottom: 0.5rem;">
                            <IconLock size=14 />
                            " Password (share separately)"
                        </div>
                        <div class="row" style="gap: 0.5rem; align-items: stretch;">
                            <code class="link-display">"warm-sage-92"</code>
                            <button class="btn btn--ghost btn--sm" on:click=do_copy>
                                <IconCopy size=14 />
                                "Copy"
                            </button>
                        </div>
                        <p class="text-mute" style="margin-top: 0.5rem; font-size: 0.88rem;">
                            "Send the link and the password through different channels —
                             for example, the link by email and the password by message."
                        </p>
                    </div>
                </Show>
            </div>
        </Show>

        <div class="action-bar">
            <button class="btn btn--ghost" on:click=nav_back_cancel>"Cancel"</button>
            <Show
                when=move || generated.get()
                fallback=move || view! {
                    <button class="btn btn--sage" on:click=do_generate>
                        <IconLink size=16 />
                        "Generate link"
                    </button>
                }
            >
                <button class="btn" on:click=move |_| nav_done.run(())>"Done"</button>
            </Show>
        </div>

        // Trust reassurance
        <div class="trust-panel" style="margin-top: 2rem;">
            <div class="trust-panel__badges">
                <span class="badge badge--sage">
                    <IconShield size=12 />
                    "Not indexed by search engines"
                </span>
                <span class="badge badge--sage">
                    <IconShield size=12 />
                    "Revoke at any time"
                </span>
                <span class="badge badge--sage">
                    <IconShield size=12 />
                    "End-to-end transport encryption"
                </span>
            </div>
        </div>
    }
}
