using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Media;
using Android.Nfc;
using Android.OS;
using Firebase;
using Plugin.Firebase.CloudMessaging;
using Plugin.NFC;


namespace WorkFlowCheck.MAUI
{
    [Activity(Theme = "@style/Maui.SplashTheme", 
              Icon = "@mipmap/appicon",
              MainLauncher = true, 
              LaunchMode = LaunchMode.SingleTop, 
              ConfigurationChanges = ConfigChanges.ScreenSize | 
                                     ConfigChanges.Orientation | 
                                     ConfigChanges.UiMode | 
                                     ConfigChanges.ScreenLayout | 
                                     ConfigChanges.SmallestScreenSize | 
                                     ConfigChanges.Density)]
    public class MainActivity : MauiAppCompatActivity
    {
        NfcAdapter nfcAdapter;
        PendingIntent pendingIntent;
        static Action<string> _onTagRead;

        protected async override void OnDestroy()
        {
            SecureStorage.Default.Remove("WFCUser");
            SecureStorage.Default.Remove("AuthToken");
            base.OnDestroy();
        }
        
        protected override void OnCreate(Bundle savedInstanceState)
        {
            CrossNFC.Init(this);
            Firebase.FirebaseApp.InitializeApp(this);
            base.OnCreate(savedInstanceState);
            nfcAdapter = NfcAdapter.GetDefaultAdapter(this);
            pendingIntent = PendingIntent.GetActivity(this, 0,
                            new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.SingleTop),
                            Build.VERSION.SdkInt >= BuildVersionCodes.S ? PendingIntentFlags.Mutable : PendingIntentFlags.UpdateCurrent);

            HandleIntent(Intent);
            CreateNotificationChannelIfNeeded();
        }
        
        protected override void OnNewIntent(Intent intent)
        {
            base.OnNewIntent(intent);
            HandleIntent(intent);
            CrossNFC.OnNewIntent(intent);
            
            if (intent.Action == NfcAdapter.ActionTagDiscovered)
            {
                var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
                var id = tag?.GetId();
                if (id != null)
                {
                    var hex = BitConverter.ToString(id).Replace("-", "");
                    _onTagRead?.Invoke(hex);
                }
            }
        }
        
        protected override void OnResume()
        {
            base.OnResume();

            // Plugin NFC: Restart NFC listening on resume (needed for Android 10+) 
            CrossNFC.OnResume();
        }
        
        public void StartNfc(Action<string> onTagRead)
        {
            _onTagRead = onTagRead;
            if (nfcAdapter.IsEnabled)
            {
                nfcAdapter?.EnableForegroundDispatch(this, pendingIntent, null, null);
            }
        }
       
        public void StopNfc()
        {
            _onTagRead = null;
            //if (!IsFinishing && !IsDestroyed)
            //{
            //    nfcAdapter?.DisableForegroundDispatch(this);
            //}
        }
        private static void HandleIntent(Intent intent)
        {
            FirebaseCloudMessagingImplementation.OnNewIntent(intent);
        }
        private void CreateNotificationChannelIfNeeded()
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                CreateNotificationChannel();
            }
        }
        private void CreateNotificationChannel()
        {
            var soundUri = Android.Net.Uri.Parse($"android.resource://{Android.App.Application.Context.PackageName}/raw/siren_alert");
            

            var audioAttributes = new AudioAttributes.Builder()
                    .SetUsage(AudioUsageKind.Notification)
                    .SetContentType(AudioContentType.Sonification)
                    .Build();

            var channelId = $"{PackageName}.general";
            var channel = new NotificationChannel(channelId, "General", NotificationImportance.High);
            
            channel.SetSound(soundUri, audioAttributes);
            
            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            notificationManager.CreateNotificationChannel(channel);
            FirebaseCloudMessagingImplementation.ChannelId = channelId;

            
        }
    }
}
