 // lib/features/auth/screens/sms_verification_screen.dart

 import 'package:flutter/material.dart';
 import 'package:package_info_plus/package_info_plus.dart';
 import 'package:kmobile/api/services/send_sms_service.dart';
 import 'package:kmobile/l10n/app_localizations.dart';
 import 'package:permission_handler/permission_handler.dart';
 import 'package:uuid/uuid.dart';
 class SmsVerificationScreen extends StatefulWidget {
   const SmsVerificationScreen({super.key});

   @override
   State<SmsVerificationScreen> createState() => _SmsVerificationScreenState();
 }

 class _SmsVerificationScreenState extends State<SmsVerificationScreen> {
   String _version = '';
   final SmsService _smsService = SmsService();

   @override
   void initState() {
     super.initState();
     _loadVersion();
     _initiateSmsSequence();
   }

   void _showSnackBar(String message) {
     if (!mounted) return;
     ScaffoldMessenger.of(context).showSnackBar(
       SnackBar(
         content: Text(message),
         duration: const Duration(seconds: 3),
       ),
     );
   }

   Future<void> _initiateSmsSequence() async {
     bool hasPermission = false;

     // --- PERMISSION LOOP ---
     while (!hasPermission) {
       final status = await _smsService.handleSmsPermission();

           switch (status) {
       case PermissionStatusResult.granted:
         _showSnackBar("Permissions Granted! Proceeding...");
         hasPermission = true; // This will break the loop
         break;
       case PermissionStatusResult.denied:
         _showSnackBar("SMS and Phone permissions are required. Please try again.");
         await Future.delayed(const Duration(seconds: 3));
         break;
       case PermissionStatusResult.permanentlyDenied:
         if (mounted) {
           await showDialog(
             context: context,
             builder: (context) => AlertDialog(
               title: const Text("Permission Required"),
               content: const Text("SMS and Phone permissions are required for device verification. Please enable them in your app settings to continue."),
               actions: [
                 TextButton(
                   child: const Text("Cancel"),
                   onPressed: () => Navigator.of(context).pop(),
                 ),
                 TextButton(
                   child: const Text("Open Settings"),
                   onPressed: () {
                     openAppSettings(); // Opens the phone's settings screen for this app
                     Navigator.of(context).pop();
                   },
                 ),
               ],
             ),
           );
         }
         // Wait for user to return from settings
         await Future.delayed(const Duration(seconds: 5));
         break;
       case PermissionStatusResult.restricted:
         if (mounted) {
           await showDialog(
             context: context,
             builder: (context) => AlertDialog(
               title: const Text("Permission Restricted"),
               content: const Text(
                   "SMS and Phone permissions are restricted on this device. Please check your device settings or parental controls and enable them for this app."),
               actions: [
                 TextButton(
                   child: const Text("Cancel"),
                   onPressed: () => Navigator.of(context).pop(),
                 ),
                 TextButton(
                   child: const Text("Open Settings"),
                   onPressed: () {
                     openAppSettings();
                     Navigator.of(context).pop();
                   },
                 ),
               ],
             ),
           );
         }
         await Future.delayed(const Duration(seconds: 5));
         break;
     }
     }

     // --- SMS SENDING LOOP ---
     bool isSmsSent = false;
     while (!isSmsSent) {
        var uuid = const Uuid();
String uniqueId = uuid.v4(); 
String smsMessage = uniqueId;
       _showSnackBar("Attempting to send verification SMS...");
       isSmsSent = await _smsService.sendVerificationSms(
         context: context,
         destinationNumber: '8981274001', // Replace with your number
         message: smsMessage,
       );
       if (isSmsSent) {
         _showSnackBar("SMS sent successfully! Proceeding to login.");
         break;
       } else {
         _showSnackBar("SMS failed to send. Retrying in 5 seconds...");
         await Future.delayed(const Duration(seconds: 5));
       }
     }

     if (mounted) {
       Navigator.pushReplacementNamed(context, '/login');
     }
   }

   Future<void> _loadVersion() async {
     final PackageInfo info = await PackageInfo.fromPlatform();
     if (mounted) {
       setState(() {
         _version = 'Version ${info.version} (${info.buildNumber})';
       });
     }
   }

   @override
   Widget build(BuildContext context) {
     return Scaffold(
       body: Stack(
         fit: StackFit.expand,
         children: <Widget>[
           Positioned.fill(
             child: Image.asset(
               'assets/images/kconnect2.webp',
               fit: BoxFit.cover,
             ),
           ),
           Center(
             child: Column(
               mainAxisSize: MainAxisSize.min,
               children: [
                 Text(
                   AppLocalizations.of(context).kccbMobile,
                   style: const TextStyle(
                     fontSize: 36,
                     fontWeight: FontWeight.bold,
                     color: Color(0xFFFFFFFF),
                   ),
                 ),
                 const SizedBox(height: 12),
                 Text(
                   AppLocalizations.of(context).kccBankFull,
                   textAlign: TextAlign.center,
                   style: const TextStyle(
                     fontSize: 18,
                     color: Color(0xFFFFFFFF),
                     letterSpacing: 1.2,
                   ),
                 ),
               ],
             ),
           ),
           const Positioned(
             bottom: 40,
             left: 0,
             right: 0,
             child: Center(
               child: CircularProgressIndicator(color: Color(0xFFFFFFFF)),
             ),
           ),
           Positioned(
             bottom: 90,
             left: 0,
             right: 0,
             child: Text(
               _version,
               textAlign: TextAlign.center,
               style: const TextStyle(
                 color: Color(0xFFFFFFFF),
                 fontSize: 14,
               ),
             ),
           ),
         ],
       ),
     );
   }
 }