/*
 * Copyright (c)2009-2025 DemiVision, LLC. All Rights Reserved. The information
 * herein is the CONFIDENTIAL and PROPRIETARY information of DemiVision, LLC.
 */

using Newtonsoft.Json;

using DXLib.UI;
using DXLib.UI.Alert;
using DXLib.UI.Layout;
using DXLib.UI.Container;

using DXLib.UI.Control;
using DXLib.UI.Control.Button;

using DXLib.UI.Form;
using DXLib.UI.Form.Control;

using DXLib.Email;
using DXLib.Utils;

namespace iStatVball3;

/*
 * Displays feedback form in a modal popup. The form includes a from email address field as well as feedback text area.
 * Used when user has indicated negative sentiment during review request.
 */
public class ReviewFeedback : DXGridLayout
{
	/* Constants */
	private const string TemplateId = "d-9e63bb702c11417fb703c28064e4ad4b";
	
	/* Fields */
	private readonly DXTextField fromField;
	private readonly DXEditor feedbackArea;
	private readonly DXButton sendBtn;

	private DXPopup popup;

	/* Methods */
	public ReviewFeedback()
	{
		BackgroundColor = DXColors.Light4;

		Padding = new Thickness( 20, 15, 20, 5 );
		RowSpacing = 20;
		ColumnSpacing = 0;

		// Title
		DXLabel titleLbl = new()
		{
			Resource = "review.msg",
			TextColor = DXColors.Dark1,

			Font = DXFonts.RobotoBold,
			FontSize = 17,

			Horizontal = LayoutOptions.Start,
			Vertical = LayoutOptions.Start
		};

		// Inner layout
		DXVerticalLayout formLayout = new()
		{
			Padding = 0,
			Spacing = 15
		};

		// From
		fromField = new DXTextField
		{
			IsRequired = true,

			Key = "from",
			Title = "review.from",
			Text = Shell.CurrentUser.Username,
			MinLength = 1,
			MaxLength = 64,
			Type = DXTextField.TextType.Email,
			Hint = DXFormControl.HintType.Email,
			Help = null,

			TextChanged = OnTextChanged
		};

		fromField.SetState( DXFormControl.ControlState.Normal );
		fromField.Init();

		// Feedback
		feedbackArea = new DXEditor
		{
			Text = null,
			
			Title = DXString.Get( "review.feedback" ),
			Placeholder = DXString.Get( "review.enter" ),
			
			MaxLength = 2048,
			LineCount = 12,
			
			TextChanged = OnTextChanged
		};

		formLayout.Add( fromField );
		formLayout.Add( feedbackArea );

		// Button layout
		DXHorizontalLayout buttonLayout = new()
		{
			Padding = 0,
			Spacing = 10,

			Horizontal = LayoutOptions.Center,
			Vertical = LayoutOptions.Center
		};

		// Cancel
		DXButton cancelBtn = new()
		{
			Resource = "alert.cancel",
			Type = DXButton.ButtonType.Neutral,
			ButtonWd = 85,

			ButtonTapped = OnCancelTapped
		};

		cancelBtn.Init();
		
		// Send
		sendBtn = new DXButton
		{
			Resource = "review.send",
			Type = DXButton.ButtonType.Action,

			ButtonTapped = OnSendTapped,

			IsSticky = true,
			IsDisabled = true
		};

		sendBtn.Init();
		
		buttonLayout.Add( cancelBtn );
		buttonLayout.Add( sendBtn );

		// 3 rows
		AddFixedRow( 20 );			// 0: title
		AddStarRow();				// 1: form
		AddFixedRow( 50 );			// 2: buttons

		// Add components
		Add( titleLbl, 0, 0 );
		Add( formLayout, 0, 1 );
		Add( buttonLayout, 0, 2 );
	}

	// Displays feedback form in modal popup
	public void Show()
	{
		popup = new DXPopup( this )
		{
			IsModal = true,

			ViewWidth = 450,
			ViewHeight = 425
		};

		popup.Show();
	}

	// Determines if all entry fields are valid
	private bool IsValid()
	{
		return fromField.IsValid() && feedbackArea.HasValue;
	}

	// Sends feedback email via SendGrid dynamic template
	private async Task<DXEmail.Result> SendFeedback()
	{
		DXSpinner.Start();

		string from = fromField.Text;

		// Async email send
		DXEmail.Result result = await DXEmail.Send( new DXEmailConfig
		{
			// From:
			FromAddress = from,
			FromName = from,
			
			// To:
			ToAddress = DXString.Get( "email.address" ),
			ToName = DXString.Get( "email.name" ),

			// Template
			TemplateId = TemplateId,
			TemplateData = new FeedbackEmail
			{
				From = from,
				Feedback = feedbackArea.Text
			},
		});

		DXSpinner.Stop();

		return result;
	}

	/* Event Callbacks */

	// User edited text, update Send button
	private void OnTextChanged()
	{
		sendBtn.IsDisabled = !IsValid();
	}

	// User cancelled feedback, dismiss popup
	private void OnCancelTapped( object sender )
	{
		popup.Hide();
	}

	// User submitting negative feedback
	private async void OnSendTapped( object sender )
	{
		// Async send
		if ( DXEmail.IsSuccess( await SendFeedback() ) )
		{
			popup.Hide();

			DXAlert.ShowOk( "review.feedback", "review.success" );
		}
		// Error
		else
		{
			DXAlert.ShowError( "review.err" );

			sendBtn.Reset();
		}

		// User will not be asked again
		await Shell.CurrentUser.UpdateReviewed();
	}
}

/*
 * Used to map feedback payload to dynamic SendGrid template.
 */
internal class FeedbackEmail
{
	/* Properties */
	[JsonProperty( "from" )]
	public string From { get; set; }

	[JsonProperty( "feedback" )]
	public string Feedback { get; set; }
}

//
