//! Store view — collects (name, value, force) and emits a submit
//! action when the user clicks. The actual encryption + write
//! happens on the worker thread.

use eframe::egui;
use zeroize::{Zeroize, Zeroizing};

use crate::worker::ReqId;

#[derive(Default)]
pub struct StoreState {
    pub name: String,
    pub value: String,
    pub force: bool,
    /// In-flight store request id. Disables the submit button while
    /// a write is pending so the user can't double-fire.
    pending: Option<ReqId>,
}

impl StoreState {
    pub fn start_submit(&mut self, id: ReqId) {
        self.pending = Some(id);
    }

    pub fn finish_submit(&mut self) {
        self.pending = None;
    }

    pub fn clear(&mut self) {
        self.name.clear();
        self.value.zeroize();
        self.force = false;
    }

    fn is_submitting(&self) -> bool {
        self.pending.is_some()
    }
}

/// What the user wants to submit. Built only when the form is valid
/// and the submit button is clicked.
pub struct StoreSubmit {
    pub name: String,
    pub value: Zeroizing<String>,
    pub force: bool,
}

pub fn render(ui: &mut egui::Ui, state: &mut StoreState) -> Option<StoreSubmit> {
    let mut submit = None;

    ui.add_space(10.0);
    ui.heading("Store a Secret");
    ui.add_space(12.0);

    egui::Frame::new()
        .fill(ui.visuals().faint_bg_color)
        .corner_radius(10.0)
        .inner_margin(20.0)
        .show(ui, |ui| {
            ui.label(egui::RichText::new("Secret name").strong());
            ui.add_space(4.0);
            ui.add(
                egui::TextEdit::singleline(&mut state.name)
                    .hint_text("e.g. cloudflare-api")
                    .desired_width(f32::INFINITY),
            );
            ui.label(
                egui::RichText::new(
                    "Lowercase identifier with hyphens. This is the reference key.",
                )
                .size(11.0)
                .weak(),
            );

            ui.add_space(12.0);
            ui.label(egui::RichText::new("Secret value").strong());
            ui.add_space(4.0);
            ui.add(
                egui::TextEdit::singleline(&mut state.value)
                    .password(true)
                    .hint_text("Paste API key, token, or credential")
                    .desired_width(f32::INFINITY),
            );
            ui.label(
                egui::RichText::new(
                    "Encrypted with AES-256-GCM on submit. Write-only — cannot be retrieved.",
                )
                .size(11.0)
                .weak(),
            );

            ui.add_space(16.0);
            ui.horizontal(|ui| {
                ui.checkbox(&mut state.force, "Overwrite if exists");
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    let enabled = !state.is_submitting()
                        && !state.name.trim().is_empty()
                        && !state.value.is_empty();
                    let label = if state.is_submitting() {
                        "Storing…"
                    } else {
                        "Encrypt and store"
                    };
                    let btn = ui.add_enabled(
                        enabled,
                        egui::Button::new(label)
                            .min_size(egui::vec2(180.0, 32.0))
                            .corner_radius(8.0),
                    );
                    if btn.clicked() && enabled {
                        submit = Some(StoreSubmit {
                            name: state.name.trim().to_string(),
                            value: Zeroizing::new(state.value.clone()),
                            force: state.force,
                        });
                    }
                });
            });
        });

    submit
}
