//! Create-contact screen — a name + number form reached from the home FAB.
//! Save writes through to contacts-server; close returns to home.

use ltk::
{
	column, container, row, spacer, text, text_edit,
	Element,
};

use crate::app::Message;
use crate::palette;
use crate::views::components as ui;

pub fn view( name: &str, number: &str ) -> Element<Message>
{
	let palette = ltk::theme_palette();

	let can_save = !name.trim().is_empty() || !number.trim().is_empty();

	let header = container::<Message>(
		row::<Message>()
			.push( ui::round_icon_btn( "navigation/close", 22.0, palette.text_primary, Message::CloseCreateContact ) )
			.push( spacer() )
			.push( text( "New contact" ).size( palette::dp( 18.0 ) ).weight( 600 ).color( palette.text_primary ) )
			.push( spacer() )
			.push( save_action( can_save, &palette ) )
	)
		.padding_h( palette::dp( 14.0 ) )
		.padding_top( palette::dp( 10.0 ) )
		.padding_bottom( palette::dp( 8.0 ) );

	let avatar = column::<Message>()
		.align_center_x( true )
		.push( spacer().height( palette::dp( 12.0 ) ) )
		.push( ui::avatar( None, 96.0 ) )
		.push( spacer().height( palette::dp( 12.0 ) ) );

	let form = column::<Message>()
		.spacing( palette::dp( 14.0 ) )
		.push(
			text_edit::<Message>( "Name", name )
				.on_change( Message::CreateNameChanged ),
		)
		.push(
			text_edit::<Message>( "Phone number", number )
				.on_change( Message::CreateNumberChanged )
				.on_submit( Message::SaveContact ),
		);

	let body = column::<Message>()
		.push( header )
		.push( avatar )
		.push( container( form ).padding_h( palette::dp( 20.0 ) ).padding_top( palette::dp( 8.0 ) ) )
		.push( spacer() );

	container::<Message>( body ).background( palette.surface ).into()
}

fn save_action( enabled: bool, palette: &ltk::Palette ) -> Element<Message>
{
	let label = text( "Save" )
		.size( palette::dp( 16.0 ) )
		.weight( 600 )
		.color( if enabled { palette.accent } else { palette::text_tertiary() } );

	let chip = container::<Message>( label )
		.padding_h( palette::dp( 10.0 ) )
		.padding_v( palette::dp( 6.0 ) );

	if enabled
	{
		ltk::pressable( chip ).on_press( Message::SaveContact ).into()
	} else {
		chip.into()
	}
}
