// SPDX-License-Identifier: Apache-2.0
//! Album Detail — view and manage one album.

use leptos::prelude::*;
use leptos_router::hooks::use_params_map;

use crate::components::confirm::ConfirmDialog;
use crate::components::icons::{
    IconCalendar, IconChevronLeft, IconDownload, IconShare, IconTrash, IconUpload,
};
use crate::mock::Photo;
use crate::state::{AppState, ToastKind};

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

    let st = AppState::get();
    let albums = st.albums;
    let photos = st.photos;
    let confirm_delete = RwSignal::new(false);
    let selected: RwSignal<Vec<String>> = RwSignal::new(Vec::new());

    let album = Memo::new(move |_| {
        let id = album_id.get();
        albums.with(|all| all.iter().find(|a| a.id == id).cloned())
    });

    let album_photos = Memo::new(move |_| {
        let id = album_id.get();
        photos.with(|all| {
            all.iter()
                .filter(|p| p.album_id == id)
                .cloned()
                .collect::<Vec<Photo>>()
        })
    });

    let selection_count = move || selected.get().len();

    let on_delete = Callback::new(move |()| {
        st.toast(
            "Album deleted (mockup — nothing was changed).",
            ToastKind::Neutral,
        );
    });

    view! {
        {move || album.get().map_or_else(
            || view! { <div class="empty"><div class="empty__title">"Album not found"</div></div> }.into_any(),
            |a| {
                if a.is_received {
                    // ── Viewer mode ───────────────────────────────────────────
                    // This album was shared with the current user by someone else.
                    // No edit, add, share, or delete controls are shown.
                    let sender = a.received_from.clone().unwrap_or_else(|| "Someone".into());
                    let bg = format!(
                        "background: linear-gradient(135deg, {} 0%, {} 100%);",
                        a.cover_palette.0, a.cover_palette.1
                    );
                    view! {
                        <header class="screen-head">
                            <a class="btn--text" href="/shared" style="margin-bottom: 0.5rem;">
                                <IconChevronLeft size=14 />
                                "Shared with you"
                            </a>
                            <div class="album-viewer-banner" style=bg>
                                <div class="album-viewer-banner__inner">
                                    <div class="album-viewer-banner__from">
                                        "Shared by " <strong>{sender.clone()}</strong>
                                        " · " {a.updated_at.clone()}
                                    </div>
                                    <h1 class="album-viewer-banner__title">{a.title.clone()}</h1>
                                    <div class="album-viewer-banner__count">{a.photo_count} " photos"</div>
                                </div>
                            </div>
                        </header>

                        // Photo grid — view-only, no selection
                        <Show
                            when=move || !album_photos.get().is_empty()
                            fallback=|| view! {
                                <div class="empty">
                                    <div class="empty__title">"No photos yet"</div>
                                    <p class="empty__body">
                                        "Photos will appear here when the owner adds them."
                                    </p>
                                </div>
                            }
                        >
                            <div class="photo-grid">
                                <For
                                    each=move || album_photos.get()
                                    key=|p| p.id.clone()
                                    children=move |p| {
                                        let bg = format!(
                                            "background: linear-gradient(135deg, {} 0%, {} 100%);",
                                            p.palette.0, p.palette.1
                                        );
                                        let href = format!("/photos/{}", p.id);
                                        view! {
                                            <a class="photo-tile" href=href>
                                                <div class="photo-tile__art" style=bg></div>
                                            </a>
                                        }
                                    }
                                />
                            </div>
                        </Show>

                        <div class="trust-panel" style="margin-top: 2.5rem;">
                            <p class="text-mute" style="max-width: 50ch; font-size: 0.9rem;">
                                {sender} " can revoke your access at any time. "
                                "When they do, this album will disappear from your inbox immediately."
                            </p>
                        </div>
                    }.into_any()
                } else {
                let share_href = format!("/albums/{}/share", a.id);
                let badge_class = format!("badge {}", a.visibility.modifier());
                view! {
                    <header class="screen-head">
                        <a class="btn--text" href="/" style="margin-bottom: 0.5rem;">
                            <IconChevronLeft size=14 />
                            "Library"
                        </a>
                        <div class="row-between">
                            <div>
                                <h1 class="screen-head__title">{a.title.clone()}</h1>
                                // Visibility dot only — count and date on the photos themselves
                                <a href=share_href.clone() class=badge_class style="margin-top:0.4rem; display:inline-flex;">
                                    <span class="badge__dot"></span>
                                    {a.visibility.label()}
                                </a>
                            </div>
                        </div>
                    </header>

                    // Toolbar: Add (primary) + Share (secondary) + ··· overflow
                    <div class="row" style="margin-bottom:1rem; gap:0.5rem;">
                        <a class="btn btn--sage" href="/upload">
                            <IconUpload size=16 />
                            "Add photos"
                        </a>
                        <a class="btn btn--ghost" href=share_href.clone()>
                            <IconShare size=16 />
                            "Share"
                        </a>
                        <details class="overflow-menu">
                            <summary class="btn btn--ghost" aria-label="More options">"···"</summary>
                            <div class="overflow-menu__panel">
                                <a class="overflow-menu__item" href="/me">
                                    <IconDownload size=14 />
                                    "Export album"
                                </a>
                                <label class="overflow-menu__item" for="sort">
                                    "Sort: "
                                    <select id="sort" class="overflow-menu__select">
                                        <option>"Captured date"</option>
                                        <option>"Uploaded date"</option>
                                    </select>
                                </label>
                            </div>
                        </details>
                    </div>

                    // Photo grid
                    <Show
                        when=move || !album_photos.get().is_empty()
                        fallback=|| view! {
                            <div class="empty">
                                <div class="empty__title">"No photos in this album yet"</div>
                                <p class="empty__body">"Photos you add here remain visible only to you until you share the album."</p>
                                <a class="btn" href="/upload">"Add photos"</a>
                            </div>
                        }
                    >
                        <div class="photo-grid photo-grid--selectable">
                            <For
                                each=move || album_photos.get()
                                key=|p| p.id.clone()
                                children=move |p| view! { <PhotoTile photo=p selected=selected /> }
                            />
                        </div>
                    </Show>

                    // Selection action bar (appears when selection > 0)
                    <Show when=move || { selection_count() > 0 } fallback=|| ()>
                        <div class="card" style="margin-top: 1.5rem; position: sticky; bottom: calc(var(--nav-height) + 16px);">
                            <div class="row-between">
                                <span><strong>{move || selection_count()}</strong> " selected"</span>
                                <div class="row">
                                    <button class="btn btn--ghost" on:click=move |_| selected.set(Vec::new())>
                                        "Clear"
                                    </button>
                                    <button class="btn btn--ghost">"Remove from album"</button>
                                    <button class="btn btn--danger" on:click=move |_| confirm_delete.set(true)>
                                        <IconTrash size=14 />
                                        "Delete photos"
                                    </button>
                                </div>
                            </div>
                        </div>
                    </Show>

                    // Privacy info section
                    <div class="section-head">
                        <h2 class="section-head__title">"Privacy summary"</h2>
                        <span class="section-head__rule"></span>
                    </div>
                    <div class="card">
                        <div class="row" style="gap: 1.5rem; flex-wrap: wrap;">
                            <div>
                                <div class="text-mono text-xs text-mute" style="text-transform: uppercase; letter-spacing: 0.1em;">"Captured date"</div>
                                <div class="row" style="margin-top: 4px;"><IconCalendar size=14 /> <span>"Retained"</span></div>
                            </div>
                            <div>
                                <div class="text-mono text-xs text-mute" style="text-transform: uppercase; letter-spacing: 0.1em;">"Location"</div>
                                <div class="row" style="margin-top: 4px;"><IconCalendar size=14 /> <span class="strike text-mute">"Removed"</span></div>
                            </div>
                            <div>
                                <div class="text-mono text-xs text-mute" style="text-transform: uppercase; letter-spacing: 0.1em;">"Device info"</div>
                                <div class="row" style="margin-top: 4px;"><span>"Removed"</span></div>
                            </div>
                            <div>
                                <div class="text-mono text-xs text-mute" style="text-transform: uppercase; letter-spacing: 0.1em;">"Original retained"</div>
                                <div class="row" style="margin-top: 4px;"><span>"No"</span></div>
                            </div>
                        </div>
                    </div>

                    <ConfirmDialog
                        open=confirm_delete
                        title="Delete selected photos?"
                        body="The selected photos will be removed from this album. If they belong to no other album, you can choose to delete them entirely from your library on the next step."
                        confirm_label="Delete photos"
                        cancel_label="Keep them"
                        destructive=true
                        on_confirm=on_delete
                    />
                }.into_any()
                } // end else (owner view)
            }
        )}
    }
}

#[component]
fn PhotoTile(photo: Photo, selected: RwSignal<Vec<String>>) -> impl IntoView {
    let style = format!(
        "--cell-a: {}; --cell-b: {};",
        photo.palette.0, photo.palette.1
    );
    let pid = photo.id.clone();
    let pid_for_pressed = pid.clone();
    let pid_for_click = pid.clone();
    let view_href = format!("/photos/{}", pid);

    let on_click = move |ev: leptos::ev::MouseEvent| {
        // If shift/meta key, toggle selection rather than open viewer.
        if ev.shift_key() || ev.meta_key() || ev.ctrl_key() {
            ev.prevent_default();
            let id = pid_for_click.clone();
            selected.update(|s| {
                if let Some(pos) = s.iter().position(|x| x == &id) {
                    s.remove(pos);
                } else {
                    s.push(id);
                }
            });
        }
    };

    view! {
        <a
            class="photo-tile"
            href=view_href
            style=style
            attr:aria-pressed=move || selected.with(|s| s.iter().any(|x| x == &pid_for_pressed)).to_string()
            aria-label=format!("Photo from {}", photo.uploaded_at)
            on:click=on_click
        >
            <span class="photo-tile__check" aria-hidden="true">"✓"</span>
            <span class="photo-tile__meta">{photo.uploaded_at.clone()}</span>
        </a>
    }
}
