// SPDX-License-Identifier: Apache-2.0
//! Share Center — manage active access to an album.
//!
//! Lists who currently has access and through what mechanism
//! (private link, invitation, Family key). Every entry is revocable
//! with a single tap. The page exists to make the answer to
//! "who can see this?" always visible and always reversible.

use leptos::prelude::*;
use leptos_router::hooks::{use_navigate, use_params_map};

use crate::components::confirm::ConfirmDialog;
use crate::components::icons::{
    IconChevronLeft, IconKey, IconLink, IconLock, IconPlus, IconShield, IconTrash, IconUsers,
};
use crate::state::{AppState, ToastKind};

#[derive(Clone)]
struct AccessEntry {
    id: &'static str,
    kind: AccessKind,
    label: &'static str,
    detail: &'static str,
    last_seen: &'static str,
}

#[derive(Clone, Copy)]
enum AccessKind {
    PrivateLink,
    Invitation,
    FamilyKey,
}

impl AccessKind {
    fn label(self) -> &'static str {
        match self {
            Self::PrivateLink => "Private link",
            Self::Invitation => "Invitation",
            Self::FamilyKey => "Family key",
        }
    }
    fn modifier(self) -> &'static str {
        match self {
            Self::PrivateLink => "badge--sage",
            Self::Invitation => "badge--sage",
            Self::FamilyKey => "badge--sage",
        }
    }
}

fn seed_entries() -> Vec<AccessEntry> {
    vec![
        AccessEntry {
            id: "acc_link_summer",
            kind: AccessKind::PrivateLink,
            label: "Link · expires Aug 30",
            detail: "Password required. View only.",
            last_seen: "Opened 4 times — last yesterday",
        },
        AccessEntry {
            id: "acc_inv_grandma",
            kind: AccessKind::Invitation,
            label: "Grandma Hana",
            detail: "Personal invitation — no password",
            last_seen: "Last viewed 2 days ago",
        },
        AccessEntry {
            id: "acc_family",
            kind: AccessKind::FamilyKey,
            label: "Family key · 4 members",
            detail: "Sam, Mira, Hana, Junpei",
            last_seen: "Active",
        },
    ]
}

#[component]
pub fn ShareCenterPage() -> 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 albums = st.albums;

    let entries: RwSignal<Vec<AccessEntry>> = RwSignal::new(seed_entries());
    let confirm_revoke = RwSignal::new(false);
    let pending_revoke: RwSignal<Option<&'static str>> = RwSignal::new(None);

    let album_title = Memo::new(move |_| {
        let id = album_id.get();
        albums.with(|all| {
            all.iter()
                .find(|a| a.id == id)
                .map(|a| a.title.clone())
                .unwrap_or_else(|| "Album".to_string())
        })
    });

    let nav_back = {
        let nav = navigate.clone();
        let id = album_id;
        move |_| nav(&format!("/albums/{}", id.get()), Default::default())
    };
    let nav_new = {
        let nav = navigate.clone();
        let id = album_id;
        move |_| {
            nav(
                &format!("/albums/{}/share/new", id.get()),
                Default::default(),
            )
        }
    };
    let pause_all = move |_| {
        st.toast("Sharing paused for this album.", ToastKind::Neutral);
    };
    let request_revoke = move |id: &'static str, _label: &'static str| {
        pending_revoke.set(Some(id));
        confirm_revoke.set(true);
    };
    let do_revoke = Callback::new(move |_| {
        if let Some(id) = pending_revoke.get() {
            entries.update(|v| v.retain(|e| e.id != id));
            st.toast("Access revoked. Effective immediately.", ToastKind::Success);
        }
        pending_revoke.set(None);
    });

    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 album"
            </button>
        </div>

        <header class="screen-head">
            <div class="screen-head__eyebrow">"Share Center"</div>
            <h1 class="screen-head__title">{move || album_title.get()}</h1>
            <p class="screen-head__lead">
                "Everyone who can currently see this album is listed below. Each entry
                can be revoked at any time. Revoking takes effect immediately —
                no fade-out, no grace period."
            </p>
        </header>

        // Primary actions
        <div class="card" style="margin-bottom: 1.5rem;">
            <div class="row" style="gap: 0.75rem; flex-wrap: wrap;">
                <button class="btn btn--sage" on:click=nav_new>
                    <IconPlus size=16 />
                    "New private link"
                </button>
                <button class="btn btn--ghost">
                    <IconUsers size=16 />
                    "Invite someone"
                </button>
                <button class="btn btn--ghost" on:click=pause_all style="margin-left: auto;">
                    <IconLock size=16 />
                    "Pause all sharing"
                </button>
            </div>
        </div>

        // Access list
        <div class="section-head">
            <h2 class="section-head__title">"Who has access right now"</h2>
            <span class="section-head__rule"></span>
        </div>

        <ul class="access-list">
            <For
                each=move || entries.get()
                key=|e| e.id
                children=move |e| {
                    let id = e.id;
                    let label = e.label;
                    let on_revoke = move |_| request_revoke(id, label);
                    let icon_view = match e.kind {
                        AccessKind::PrivateLink => view! { <IconLink size=18 /> }.into_any(),
                        AccessKind::Invitation => view! { <IconUsers size=18 /> }.into_any(),
                        AccessKind::FamilyKey => view! { <IconKey size=18 /> }.into_any(),
                    };
                    view! {
                        <li class="access-item">
                            <span class="access-item__icon" aria-hidden="true">{icon_view}</span>
                            <div class="access-item__main">
                                <div class="access-item__row">
                                    <span class=format!("badge {}", e.kind.modifier())>
                                        {e.kind.label()}
                                    </span>
                                    <strong class="access-item__label">{e.label}</strong>
                                </div>
                                <div class="access-item__detail">{e.detail}</div>
                                <div class="access-item__meta">{e.last_seen}</div>
                            </div>
                            <button class="btn btn--ghost btn--sm btn--danger" on:click=on_revoke>
                                <IconTrash size=14 />
                                "Revoke"
                            </button>
                        </li>
                    }
                }
            />
        </ul>

        // Trust reassurance
        <div class="trust-panel" style="margin-top: 2rem;">
            <p class="trust-panel__quote">"Sharing is always explicit. Always revocable."</p>
            <p class="text-mute" style="max-width: 50ch;">
                "There is no public link that you cannot find here. There is no
                viewer that you cannot remove. There is no algorithm deciding
                who else should see your photos. Only this list, only your choice."
            </p>
            <div class="trust-panel__badges">
                <span class="badge badge--sage">
                    <IconShield size=12 />
                    "Revoke is instant"
                </span>
                <span class="badge badge--sage">
                    <IconShield size=12 />
                    "No public discovery"
                </span>
            </div>
        </div>

        <ConfirmDialog
            open=confirm_revoke
            title="Revoke this access?"
            body="The viewer will no longer be able to see this album. \
                  Revoking is immediate. You can always create new access later."
            confirm_label="Revoke now"
            cancel_label="Keep access"
            destructive=true
            on_confirm=do_revoke
        />
    }
}
