use crate::ui::prelude::*;
use ltk::{ date_picker, time_picker };

pub( crate ) fn view_datetime( state: &State ) -> Element<Msg>
{
	let mut col = column::<Msg>()
		.padding( 24.0 )
		.spacing( 8.0 )
		.push( header( &tr!( "home.datetime" ) ) )
		.push( toggle_row( tr!( "datetime.auto" ), state.ntp_on, Msg::ToggleNtp ) )
		.push( separator() )
		.push( list_item( tr!( "datetime.date" ) ).trailing( &state.date_str ) )
		.push( list_item( tr!( "datetime.time" ) ).trailing( &state.time_str ) )
		.push( list_item( tr!( "datetime.timezone" ) ).trailing( &state.tz_str ) );

	if !state.ntp_on
	{
		col = col.push( separator() );
		col = col.push( t_sec!( tr!( "datetime.set_manually" ) ).size( 13.0 ) );

		let sel_date = format!(
			"{:04}-{:02}-{:02}",
			state.dt_date.year, state.dt_date.month, state.dt_date.day,
		);

		let mut body = column::<Msg>().padding( 0.0 ).spacing( 8.0 );
		body = body.push(
			list_item( tr!( "datetime.date" ) )
				.trailing( &sel_date )
				.on_press( Msg::ToggleDateEdit )
		);
		if state.dt_cal_open
		{
			use chrono::Datelike;
			let now   = chrono::Local::now();
			let today = ltk::Date::new( now.year(), now.month() as u8, now.day() as u8 );
			body = body.push(
				date_picker( state.dt_date )
					.view( state.dt_view.0, state.dt_view.1 )
					.today( today )
					.on_change( Msg::DateChanged )
					.on_navigate( Msg::DateView )
			);
		}
		body = body.push(
			time_picker( state.dt_time )
				.on_change( Msg::TimeChanged )
		);
		if state.dt_apply_failed
		{
			body = body.push( t_sec!( tr!( "datetime.set_failed" ) ).size( 13.0 ) );
		}
		body = body.push( button( tr!( "common.apply" ) ).on_press( Msg::ApplyDateTime ) );
		return col.push( scroll( body ) ).into();
	}

	col.push( spacer() ).into()
}
