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

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

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

using DXLib.Data;
using DXLib.Utils;

namespace iStatVball3;

/*
 * Implements the content area for the Account toolbar drawer, which displays info for the currently signed-in user as
 * well as the interface for making additional Team-Season purchases. Also includes entry point for admin tools interface.
 */
public class AccountContent : DXScroll
{
	/* Constants */
	private const double LabelSize = 20;

	/* Fields */
	private readonly ToolBarDrawer drawer;
	
	// Layout
	private readonly DXGridLayout layout;

	// Buttons
	private readonly DXButton logoutBtn;
	
	// Text buttons
	private readonly DXTextButton deleteBtn;

	// Purchase
	private DXVerticalLayout purchaseLayout;
	private DXButton purchaseBtn;

	private PurchaseView purchaseView;

	/* Methods */
	public AccountContent( ToolBarDrawer drawer )
	{
		this.drawer = drawer;
		
		BackgroundColor = DXColors.Light4;
		
		Padding = 0;
		Margin = 0;
		
		Horizontal = LayoutOptions.Fill;
		Vertical = LayoutOptions.Fill;

		// Layout
		layout = new DXGridLayout
		{
			Padding = 22,
			RowSpacing = 5,
			ColumnSpacing = 0
		};
		
		// Force full width on mobile landscape
		AdjustForSafeArea( layout );

		// Access logged-in user
		User user = Shell.CurrentUser;

		const double imgSize = 90;

		// Avatar
		DXImageArea imageArea = new()
		{
			DefaultIcon = "player",
			Color = DXImageArea.DefaultColor,

			WidthRequest = imgSize,
			HeightRequest = imgSize,

			Horizontal = LayoutOptions.Start
		};

		imageArea.SetImage( user.ImageUrl );
		imageArea.SetSize( imgSize, imgSize, 0.80 );

		layout.AddFixedRow( imgSize );
		layout.Add( imageArea, 0, 0 );

		// Spacer
		layout.AddFixedRow( 6 );

		// Full name
		DXLabel nameLbl = new()
		{
			Text = user.FullName,
			TextColor = DXColors.Dark1,

			Font = DXFonts.RobotoBold,
			FontSize = 17
		};

		layout.AddFixedRow( LabelSize );
		layout.Add( nameLbl, 0, 2 );

		// Username (email)
		DXLabel usernameLbl = new()
		{
			Text = user.Username,

			Font = DXFonts.Roboto,
			FontSize = 14,
			TextColor = DXColors.Dark1
		};

		layout.AddFixedRow( LabelSize );
		layout.Add( usernameLbl, 0, 3 );

		const double btnSize = 50;

		// Buttons arranged horizontally
		DXHorizontalLayout buttonLayout = new()
		{
			Spacing = 5,
			Margin = new Thickness( 0, 11, 0, 0 )
		};

        // Logout
        logoutBtn = new DXButton
        {
            Resource = "account.logout",
            Type = DXButton.ButtonType.Negative,
            ButtonWd = 90,

            // Do not allow logout while recording
            IsDisabled = Shell.Instance.IsRecording,

            IsSticky = true,
            ButtonTapped = OnLogoutTapped
        };

        logoutBtn.Init();
        
        buttonLayout.Add( logoutBtn );

		layout.AddFixedRow( btnSize );
		layout.Add( buttonLayout, 0, 4 );

		// Delete Account
		deleteBtn = new DXTextButton
		{
			Resource = "account.delete",

			TextColor = DXColors.Negative,
			Font = DXFonts.Roboto,
			FontSize = 16,

			Padding = 0,
			Margin = new Thickness( 0, -5, 0, 0 ),

			Horizontal = LayoutOptions.Start,
			Vertical = LayoutOptions.Center,

			IsSticky = true,
			ButtonTapped = OnDeleteTapped
		};

		layout.AddFixedRow( btnSize );
		layout.Add( deleteBtn, 0, layout.RowIndex );

        // Team-Seasons
        if ( user.Level >= User.LevelType.Coach )
		{
			AddPurchase();
		}

		// Admin
		if ( user.IsAdmin )
		{
			AddTools();
			AddAnalytics();
			AddArchive();
		}

		Content = layout;
		
		// Let parent handle close
		drawer.Closed = drawer.Hide;
	}

	// Logs out current user, returns to launch screen
	private void Logout()
    {
		// Delete cache
		User.Logout();

		drawer.Hide();
		Shell.Instance.ToolBar.Reset();

		// Return to landing screen
		LaunchStack.TransitionFromMain();
	}

	// PURCHASE

	// Adds purchase info and button
	private void AddPurchase()
	{
		User user = Shell.CurrentUser;

		// Clear
		if ( purchaseLayout != null )
		{
			layout.Remove( purchaseLayout );
		}

		// Inner layout
		purchaseLayout = new DXVerticalLayout
		{
			Margin = new Thickness( 0, 10, 0, 0 ),
			Spacing = 5
		};

		const double fontSize = 17;
		const double lineWd = 125;

		// 'Team-Seasons'
		DXLabel titleLbl = new()
		{
			Resource = "purchase.units",

			Font = DXFonts.RobotoBold,
			FontSize = fontSize,
			TextColor = DXColors.Dark1
		};

		purchaseLayout.Add( titleLbl );

		// Line
		DXLine line1 = new()
		{
			Thickness = 1,
			WidthRequest = lineWd,
			Color = DXColors.Dark1
		};

		purchaseLayout.Add( line1 );

		// User has purchases
		if ( PurchaseEngine.HasPurchased( user ) )
		{
			int purchased = PurchaseEngine.GetPurchased( user );
			string purchasedStr = $"{DXString.Get( "purchase.purchased" )}:  {purchased}";
		
			// 'Purchased: N'
			DXLabel purchasedLbl = new()
			{
				Text = purchasedStr,
				TextColor = DXColors.Dark1,
		
				Font = DXFonts.Roboto,
				FontSize = fontSize
			};
		
			purchaseLayout.Add( purchasedLbl );
		
			const int used = 0;
		
			PurchaseEngine.GetUsed( user );
			
			string usedStr = $"{DXString.Get( "purchase.used" )}:  {used}";
		
			// 'Used: N'
			DXLabel usedLbl = new()
			{
				Text = usedStr,
				TextColor = DXColors.Dark1,
		
				Font = DXFonts.Roboto,
				FontSize = fontSize
			};
		
			purchaseLayout.Add( usedLbl );
		
			int remaining = PurchaseEngine.GetRemaining( user );
			string remainingStr = $"{DXString.Get( "purchase.remaining" )}:  {remaining}";
		
			// 'Remaining: N'
			DXLabel remainingLbl = new()
			{
				Text = remainingStr,
		
				Font = DXFonts.RobotoBold,
				FontSize = fontSize,
				TextColor = DXColors.Dark1
			};
		
			purchaseLayout.Add( remainingLbl );
		}
		// No purchases
		else
		{
			bool trial = (PurchaseEngine.IsTrialPeriod( user ) || !PurchaseEngine.IsTrialUsed( user ));

			// Within free trial period, or has ended
			DXLabel trialLbl = new()
			{
				Resource = trial ? "purchase.trial" : "purchase.end",

				FontResource = DXFonts.Roboto,
				FontSize = fontSize,
				TextColor = DXColors.Dark1
			};

			purchaseLayout.Add( trialLbl );
		}

		// Purchase
		purchaseBtn = new DXButton
		{
			Resource = "purchase.title",
			Type = DXButton.ButtonType.Positive,

			Horizontal = LayoutOptions.Start,
			Vertical = LayoutOptions.Start,

			Margin = DXUtils.Top( 10 ),
			IsSticky = true,

			ButtonWd = 95,
			ButtonTapped = OnPurchaseTapped
		};

		purchaseBtn.Init();
		
		purchaseLayout.Add( purchaseBtn );

		layout.AddAutoRow();
		layout.Add( purchaseLayout, 0, layout.RowIndex );
	}

	// ADMIN

	// Adds button for displaying Admin Tools
	private void AddTools()
	{
		DXButton toolsBtn = new()
		{
			Resource = "tools.title",
			Type = DXButton.ButtonType.Neutral,

			Horizontal = LayoutOptions.Start,
			Vertical = LayoutOptions.End,

			ButtonWd = 120,
			ButtonTapped = OnToolsTapped
		};

		toolsBtn.Init();
		
		layout.AddFixedRow( DXButton.DefaultHt * 2 );
		layout.Add( toolsBtn, 0, layout.RowIndex );
	}

	// Adds button for displaying Analytics
	private void AddAnalytics()
	{
		DXButton analyticsBtn = new()
		{
			Resource = "analytics.title",
			Type = DXButton.ButtonType.Neutral,

			Horizontal = LayoutOptions.Start,
			Vertical = LayoutOptions.End,

			ButtonWd = 120,
			ButtonTapped = OnAnalyticsTapped
		};

		analyticsBtn.Init();
		
		layout.AddFixedRow( DXButton.DefaultHt + 5 );
		layout.Add( analyticsBtn, 0, layout.RowIndex );
	}

	// Adds button for archiving stats
	private void AddArchive()
	{
		DXButton archiveBtn = new()
		{
			Resource = "archive.title",
			Type = DXButton.ButtonType.Neutral,

			Horizontal = LayoutOptions.Start,
			Vertical = LayoutOptions.End,

			ButtonWd = 120,
			ButtonTapped = OnArchiveTapped
		};

		archiveBtn.Init();
		
		layout.AddFixedRow( DXButton.DefaultHt + 5 );
		layout.Add( archiveBtn, 0, layout.RowIndex );
	}

	/* Event Callbacks */

	// LOGOUT

	// Prompt user to confirm logout
	private void OnLogoutTapped( object sender )
	{
		DXAlert.ShowNegativeCancel( "account.logout", "account.logout.msg", "account.logout", OnLogoutConfirmed, logoutBtn.Reset );
	}

	// User confirmed, proceed with remote logout, wait for result
	private void OnLogoutConfirmed()
	{
		DXAuth.Logout( OnLogoutComplete );
		
		logoutBtn.Reset();
	}

	// Logout completed, either successfully or with error
	private void OnLogoutComplete( DXAuth.AuthResult result )
	{
		// Success
		if ( result == DXAuth.AuthResult.Success )
		{
			Logout();
		}
		// Error
		else
		{
			DXAlert.ShowNeutral( "account.logout", "account.logout.err" );
		}
	}

	// DELETE

	// User tapped Delete Account, prompt for confirmation
	private void OnDeleteTapped( object data )
	{
		DXAlert.ShowDestroy( "account.delete", "account.delete.msg", "form.delete", "form.cancel", OnDeleteConfirmed, deleteBtn.Reset );
	}

	// User confirmed deletion, prompt again
	private void OnDeleteConfirmed()
	{
		DXDeleteAlert.Show( DXString.Get( "account.delete.lbl" ), OnDeleteConfirmed2, deleteBtn.Reset );
	}

	// User confirmed final deletion
	private async void OnDeleteConfirmed2()
	{
		DXSpinner.Start();

		// Block on delete
		await Shell.CurrentUser.DeleteAll();

		DXSpinner.Stop();

		// Success, return to launch screen
		DXAlert.ShowOk( "account.delete", "account.delete.success", Logout );
	}

	// PURCHASE

	// User starting purchase flow
	private async void OnPurchaseTapped( object sender )
	{
		purchaseView = new PurchaseView()
		{
			Completed = OnCompleted,
			Cancelled = OnCancelled
		};
		
		await purchaseView.ShowProducts();
	}

	// User successfully completed purchase 
	private void OnCompleted()
	{
		purchaseView.Hide();

		// Update display
		AddPurchase();
	}

	// User cancelled purchase flow
	private void OnCancelled()
	{
		DXSpinner.Stop();

		purchaseBtn.Reset();
	}

	// ADMIN

	// User tapped Admin Tools button
	private void OnToolsTapped( object sender )
	{
		drawer.Next( "tools.title", new AdminTools(), drawer.Previous );
	}

	// User tapped Analytics button
	private void OnAnalyticsTapped( object sender )
	{
		drawer.Next( "analytics.title", new AdminAnalytics(), drawer.Previous );
	}

	// User tapped Archive button
	private void OnArchiveTapped( object sender )
	{
		drawer.Next( "archive.title", new AdminArchive(), drawer.Previous );
	}
}

//
