import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/main/registration_form_controller.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/selfie-verification/facial_verification_controller.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/selfie-verification/selfie_verification_controller.dart';
import 'package:sigap/src/shared/widgets/image_upload/image_uploader.dart';
import 'package:sigap/src/shared/widgets/info/tips_container.dart';
import 'package:sigap/src/shared/widgets/navigation/step_navigation_buttons.dart';
import 'package:sigap/src/shared/widgets/verification/validation_message_card.dart';
import 'package:sigap/src/utils/constants/colors.dart';
import 'package:sigap/src/utils/constants/sizes.dart';
import 'package:sigap/src/utils/helpers/helper_functions.dart';
import 'package:sigap/src/utils/popups/loaders.dart';

// Enum untuk tracking status verifikasi
enum VerificationStatus {
  initial,
  preparingCamera,
  detectingFace,
  performingLiveness,
  livenessCompleted,
  comparingWithID,
  verificationComplete,
  verificationFailed,
}

class SelfieVerificationStep extends StatelessWidget {
  const SelfieVerificationStep({super.key});

  @override
  Widget build(BuildContext context) {
    final formKey = GlobalKey<FormState>();
    final controller = Get.find<SelfieVerificationController>();
    final mainController = Get.find<FormRegistrationController>();
    final facialVerificationService = FacialVerificationService.instance;

    final isDark = THelperFunctions.isDarkMode(context);

    // Check if we need to update the skip verification flag from arguments
    final dynamic args = Get.arguments;
    if (args != null &&
        args is Map<String, dynamic> &&
        args.containsKey('skipVerification')) {
      final bool skipVerification = args['skipVerification'] as bool;
      facialVerificationService.skipFaceVerification = skipVerification;
      Logger().i(
        'Setting skipFaceVerification from arguments: $skipVerification',
      );
    }

    mainController.formKey = formKey;

    return Form(
      key: formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildHeader(),

          // Development mode indicator
          _buildDevelopmentModeIndicator(facialVerificationService),

          // Main verification flow
          _buildVerificationFlow(controller),

          const SizedBox(height: TSizes.spaceBtwSections / 2),

          // Tips container
          _buildSelfieTips(),
          
          // Add space before navigation buttons
          const SizedBox(height: TSizes.spaceBtwSections),

          // Navigation buttons with loading state
          Obx(
            () => StepNavigationButtons(
              showPrevious: true,
              isLastStep: false,
              onPrevious: mainController.previousStep,
              onNext: () => _handleNextStep(controller, mainController),
              isLoading:
                  controller.isVerifyingFace.value ||
                  controller.isComparingWithIDCard.value ||
                  controller.isPerformingLivenessCheck.value,
              errorMessage: controller.selfieError.value,
              nextButtonText: 'Continue',
            ),
          ),
        ],
      ),
    );
  }
  
  // Add a method to handle the next step validation
  void _handleNextStep(
    SelfieVerificationController controller,
    FormRegistrationController mainController,
  ) {
    // Validate that selfie is taken and verified
    if (controller.selfieImage.value == null) {
      controller.selfieError.value =
          'Please complete selfie verification to continue';
      return;
    }

    if (!controller.isMatchWithIDCard.value &&
        !controller.autoVerifyForDev.value) {
      controller.selfieError.value =
          'Your selfie verification must be completed successfully';
      return;
    }

    // If everything is valid, go to next step
    mainController.nextStep();
  }
  
  Widget _buildDevelopmentModeIndicator(FacialVerificationService service) {
    if (!service.skipFaceVerification) return const SizedBox.shrink();

    BuildContext context = Get.context!;
    final controller = Get.find<SelfieVerificationController>();
    final isDark = THelperFunctions.isDarkMode(context);
    final warningColor = isDark ? Colors.amber : TColors.warning;

    return Container(
      margin: const EdgeInsets.only(bottom: TSizes.spaceBtwItems),
      padding: const EdgeInsets.all(TSizes.sm),
      decoration: BoxDecoration(
        color: warningColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(TSizes.borderRadiusSm),
        border: Border.all(color: warningColor),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.code, color: warningColor, size: TSizes.iconSm),
              const SizedBox(width: TSizes.xs),
              Expanded(
                child: Text(
                  'Development Mode',
                  style: Theme.of(context).textTheme.labelMedium?.copyWith(
                    color: warningColor,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: TSizes.xs),

          // Bypass liveness check toggle
          Row(
            children: [
              Expanded(
                child: Text(
                  'Bypass liveness check',
                  style: Theme.of(
                    context,
                  ).textTheme.labelSmall?.copyWith(color: warningColor),
                ),
              ),
              Obx(
                () => Switch(
                  value: controller.bypassLivenessCheck.value,
                  onChanged: (value) {
                    controller.bypassLivenessCheck.value = value;
                    if (value) {
                      TLoaders.errorSnackBar(
                        title: 'Bypass Enabled',
                        message: 'Liveness check will be skipped',
                      );
                    } else {
                      // When turning off, show a notification
                      TLoaders.infoSnackBar(
                        title: 'Bypass Disabled',
                        message: 'Liveness check will be performed',
                      );
                    }
                  },
                  activeColor: warningColor,
                  activeTrackColor: warningColor.withOpacity(0.5),
                ),
              ),
            ],
          ),

          // Auto-verify toggle (with updated toggle handler)
          Row(
            children: [
              Expanded(
                child: Text(
                  'Auto-verify (auto-pass all checks)',
                  style: Theme.of(
                    context,
                  ).textTheme.labelSmall?.copyWith(color: warningColor),
                ),
              ),
              Obx(
                () => Switch(
                  value: controller.autoVerifyForDev.value,
                  onChanged: (value) {
                    controller.autoVerifyForDev.value = value;
                    if (value) {
                      TLoaders.errorSnackBar(
                        title: 'Auto-verify Enabled',
                        message: 'All checks will be auto-passed',
                      );

                      // If auto-verify is enabled, also enable bypass
                      if (!controller.bypassLivenessCheck.value) {
                        controller.bypassLivenessCheck.value = true;
                      }

                      // Auto complete verification if already on this step
                      if (controller.selfieImage.value == null) {
                        WidgetsBinding.instance.addPostFrameCallback((_) {
                          controller.autoCompleteVerification();
                        });
                      }
                    } else {
                      // When turning off auto-verify, show notification
                      TLoaders.infoSnackBar(
                        title: 'Auto-verify Disabled',
                        message:
                            'You will need to complete all checks manually',
                      );
                    }
                  },
                  activeColor: TColors.error,
                  activeTrackColor: TColors.error.withOpacity(0.5),
                ),
              ),
            ],
          ),

          const SizedBox(height: TSizes.xs),
          Text(
            'Warning: Only use in development environment!',
            style: Theme.of(context).textTheme.labelSmall?.copyWith(
              color: TColors.error,
              fontStyle: FontStyle.italic,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildVerificationFlow(SelfieVerificationController controller) {
    return Obx(() {
      // Get current verification status
      final status = _getVerificationStatus(controller);

      BuildContext context = Get.context!;

      return Column(
        children: [
          // Step indicator
          _buildStepIndicator(status, context),

          const SizedBox(height: TSizes.spaceBtwItems),

          // Main content based on status
          _buildMainContent(status, controller, context),

          const SizedBox(height: TSizes.spaceBtwItems),

          // Status messages
          _buildStatusMessage(status, controller, context),
        ],
      );
    });
  }

  VerificationStatus _getVerificationStatus(
    SelfieVerificationController controller,
  ) {
    // Determine current status based on controller state
    if (controller.selfieImage.value == null) {
      if (controller.isPerformingLivenessCheck.value) {
        return VerificationStatus.performingLiveness;
      }
      return VerificationStatus.initial;
    }

    if (controller.isVerifyingFace.value) {
      return VerificationStatus.detectingFace;
    }

    if (controller.isComparingWithIDCard.value) {
      return VerificationStatus.comparingWithID;
    }

    if (controller.faceComparisonResult.value != null) {
      return controller.isMatchWithIDCard.value
          ? VerificationStatus.verificationComplete
          : VerificationStatus.verificationFailed;
    }

    if (controller.isLivenessCheckPassed.value) {
      return VerificationStatus.livenessCompleted;
    }

    return VerificationStatus.initial;
  }

  Widget _buildStepIndicator(VerificationStatus status, BuildContext context) {
    final steps = [
      {'icon': Icons.camera_alt, 'label': 'Liveness'},
      {'icon': Icons.face, 'label': 'Detection'},
      {'icon': Icons.compare, 'label': 'Compare'},
      {'icon': Icons.verified, 'label': 'Complete'},
    ];

    final isDark = THelperFunctions.isDarkMode(context);

    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: TSizes.xs,
        vertical: TSizes.md,
      ),
      decoration: BoxDecoration(
        color: isDark ? Colors.grey.shade900 : Colors.grey.shade50,
        borderRadius: BorderRadius.circular(TSizes.borderRadiusMd),
        border: Border.all(
          color: isDark ? Colors.grey.shade700 : Colors.grey.shade200,
          width: 1,
        ),
      ),
      child: Row(
        children:
            steps.asMap().entries.map((entry) {
              final index = entry.key;
              final step = entry.value;
              final isActive = _isStepActive(index, status);
              final isCompleted = _isStepCompleted(index, status);
              final isLast = index == steps.length - 1;

              return Expanded(
                child: Row(
                  children: [
                    // Step circle and label
                    Expanded(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Container(
                            width: 36,
                            height: 36,
                            decoration: BoxDecoration(
                              color: _getStepColor(
                                isCompleted,
                                isActive,
                                isDark,
                              ),
                              shape: BoxShape.circle,
                              border:
                                  isActive && !isCompleted
                                      ? Border.all(
                                        color: TColors.primary,
                                        width: 2,
                                      )
                                      : null,
                            ),
                            child: Icon(
                              isCompleted
                                  ? Icons.check
                                  : step['icon'] as IconData,
                              color: _getIconColor(
                                isCompleted,
                                isActive,
                                isDark,
                              ),
                              size: 18,
                            ),
                          ),
                          const SizedBox(height: TSizes.xs),
                          Text(
                            step['label'] as String,
                            style: Theme.of(
                              context,
                            ).textTheme.labelSmall?.copyWith(
                              color: _getTextColor(
                                isCompleted,
                                isActive,
                                isDark,
                              ),
                              fontWeight:
                                  isActive
                                      ? FontWeight.w600
                                      : FontWeight.normal,
                              fontSize: 11,
                            ),
                            textAlign: TextAlign.center,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            }).toList(),
      ),
    );
  }

  Color _getStepColor(bool isCompleted, bool isActive, bool isDark) {
    if (isCompleted) {
      return TColors.primary;
    }

    if (isActive) {
      return isDark
          ? TColors.primary.withOpacity(0.2)
          : TColors.primary.withOpacity(0.15);
    }

    return isDark ? Colors.grey.shade700 : Colors.grey.shade200;
  }

  Color _getIconColor(bool isCompleted, bool isActive, bool isDark) {
    if (isCompleted) {
      return Colors.white;
    }

    if (isActive) {
      return TColors.primary;
    }

    return isDark ? TColors.grey : Colors.grey.shade500;
  }

  Color _getTextColor(bool isCompleted, bool isActive, bool isDark) {
    if (isCompleted || isActive) {
      return isDark ? TColors.light : TColors.primary;
    }

    return isDark ? TColors.grey : Colors.grey.shade600;
  }

  bool _isStepActive(int stepIndex, VerificationStatus status) {
    switch (stepIndex) {
      case 0:
        return status == VerificationStatus.performingLiveness;
      case 1:
        return status == VerificationStatus.detectingFace;
      case 2:
        return status == VerificationStatus.comparingWithID;
      case 3:
        return status == VerificationStatus.verificationComplete;
      default:
        return false;
    }
  }

  bool _isStepCompleted(int stepIndex, VerificationStatus status) {
    switch (stepIndex) {
      case 0:
        return status.index > VerificationStatus.performingLiveness.index;
      case 1:
        return status.index > VerificationStatus.detectingFace.index;
      case 2:
        return status.index > VerificationStatus.comparingWithID.index;
      case 3:
        return status == VerificationStatus.verificationComplete;
      default:
        return false;
    }
  }

  Widget _buildMainContent(
    VerificationStatus status,
    SelfieVerificationController controller,
    BuildContext context,
  ) {
    // Debug current state

    // Check if we need to auto-start verification (when returning from liveness detection)
    if (controller.selfieImage.value != null &&
        controller.isLivenessCheckPassed.value &&
        controller.autoStartVerification) {
      // Log detection attempt

      // Start verification after the UI is built
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!controller.isVerifyingFace.value &&
            !controller.isComparingWithIDCard.value) {
          controller.startFaceVerification();
        }
      });
    }

    switch (status) {
      case VerificationStatus.initial:
        return _buildInitialState(controller, context);

      case VerificationStatus.performingLiveness:
        return _buildLivenessState(controller);

      case VerificationStatus.detectingFace:
      case VerificationStatus.livenessCompleted:
      case VerificationStatus.comparingWithID:
      case VerificationStatus.verificationComplete:
      case VerificationStatus.verificationFailed:
        return _buildImageDisplay(controller);

      default:
        return const SizedBox.shrink();
    }
  }

  Widget _buildInitialState(
    SelfieVerificationController controller,
    BuildContext context,
  ) {
    final isDark = THelperFunctions.isDarkMode(context);
    final facialVerificationService = FacialVerificationService.instance;

    // Auto-verify for development if enabled
    if (facialVerificationService.skipFaceVerification &&
        controller.autoVerifyForDev.value &&
        !controller.hasConfirmedSelfie.value) {
      // Auto-complete verification after the UI is built
      WidgetsBinding.instance.addPostFrameCallback((_) {
        controller.autoCompleteVerification();
      });
    }

    final devAccentColor = TColors.error;
    final warningColor = isDark ? Colors.amber : TColors.warning;
    final bgColor = isDark ? TColors.darkerGrey : TColors.light;
    final borderColor = isDark ? TColors.darkGrey : TColors.grey;
    final textColor = isDark ? TColors.light : TColors.dark;
    final secondaryTextColor = isDark ? TColors.lightGrey : TColors.darkGrey;

    return Column(
      children: [
        // Add auto-verify badge when enabled
        if (facialVerificationService.skipFaceVerification &&
            controller.autoVerifyForDev.value)
          Container(
            width: double.infinity,
            margin: const EdgeInsets.only(bottom: TSizes.sm),
            padding: const EdgeInsets.symmetric(
              vertical: TSizes.xs,
              horizontal: TSizes.sm,
            ),
            decoration: BoxDecoration(
              color: devAccentColor.withOpacity(0.1),
              border: Border.all(color: devAccentColor.withOpacity(0.5)),
              borderRadius: BorderRadius.circular(TSizes.borderRadiusSm),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.developer_mode,
                  size: TSizes.iconSm,
                  color: devAccentColor,
                ),
                const SizedBox(width: TSizes.xs),
                Text(
                  'Auto-Verification Enabled',
                  style: TextStyle(
                    color: devAccentColor,
                    fontWeight: FontWeight.bold,
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ),

        // Image preview container
        Container(
          width: double.infinity,
          height: 200,
          decoration: BoxDecoration(
            color: bgColor,
            borderRadius: BorderRadius.circular(TSizes.borderRadiusMd),
            border: Border.all(color: borderColor, width: 2),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.face_retouching_natural,
                size: 60,
                color: borderColor,
              ),
              const SizedBox(height: TSizes.md),
              Text(
                'Ready for Face Verification',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: textColor,
                ),
              ),
              const SizedBox(height: TSizes.sm),
              Text(
                'Tap the button below to start',
                style: TextStyle(fontSize: 14, color: secondaryTextColor),
              ),
            ],
          ),
        ),
        const SizedBox(height: TSizes.spaceBtwItems),

        // Don't show the normal button if auto-verify is enabled
        if (!(facialVerificationService.skipFaceVerification &&
            controller.autoVerifyForDev.value))
          ElevatedButton.icon(
            onPressed: () {
              // Clear any previous images or states before starting new verification
              controller.clearSelfieImage();
              controller.resetVerificationState();

              // Use bypass if enabled
              if (facialVerificationService.skipFaceVerification &&
                  controller.bypassLivenessCheck.value) {
                controller.bypassLivenessCheckWithRandomImage();
              } else {
                // Start regular liveness detection process
                controller.performLivenessDetection();
              }
            },
            icon: const Icon(Icons.security),
            label: const Text('Start Face Verification'),
            style: ElevatedButton.styleFrom(
              backgroundColor: TColors.primary,
              foregroundColor: Colors.white,
              minimumSize: const Size(double.infinity, 45),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(TSizes.buttonRadius),
              ),
            ),
          ),

        // Show bypass button if development mode is enabled
        if (facialVerificationService.skipFaceVerification)
          Obx(() {
            if (controller.bypassLivenessCheck.value) {
              return Column(
                children: [
                  const SizedBox(height: TSizes.sm),
                  TextButton.icon(
                    onPressed: () {
                      controller.clearSelfieImage();
                      controller.resetVerificationState();
                      controller.bypassLivenessCheckWithRandomImage();
                    },
                    icon: Icon(
                      Icons.developer_mode,
                      color: warningColor,
                      size: TSizes.iconSm,
                    ),
                    label: Text(
                      'DEV: Use Random Selfie & Skip Verification',
                      style: TextStyle(color: warningColor),
                    ),
                    style: TextButton.styleFrom(
                      padding: const EdgeInsets.symmetric(
                        horizontal: TSizes.md,
                        vertical: TSizes.xs,
                      ),
                      backgroundColor: warningColor.withOpacity(0.1),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(
                          TSizes.borderRadiusSm,
                        ),
                      ),
                    ),
                  ),
                ],
              );
            } else {
              return const SizedBox.shrink();
            }
          }),

        // If auto-verify is on, show a different button
        if (facialVerificationService.skipFaceVerification &&
            controller.autoVerifyForDev.value)
          ElevatedButton.icon(
            onPressed: controller.autoCompleteVerification,
            icon: const Icon(Icons.skip_next),
            label: const Text('DEV: Skip & Auto-Complete Verification'),
            style: ElevatedButton.styleFrom(
              backgroundColor: devAccentColor,
              foregroundColor: TColors.white,
              minimumSize: const Size(double.infinity, 45),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(TSizes.buttonRadius),
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildLivenessState(SelfieVerificationController controller) {
    BuildContext context = Get.context!;
    final isDark = THelperFunctions.isDarkMode(context);
    final bgColor = isDark ? TColors.darkerGrey : TColors.light;
    final borderColor = isDark ? TColors.darkGrey : TColors.grey;
    final secondaryTextColor = isDark ? TColors.lightGrey : TColors.darkGrey;
    
    return Container(
      width: double.infinity,
      height: 200,
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(TSizes.borderRadiusMd),
        border: Border.all(
          color: borderColor,
          width: 2,
        ),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(
            width: 50,
            height: 50,
            child: CircularProgressIndicator(
              strokeWidth: 3,
              color: TColors.primary,
            ),
          ),
          const SizedBox(height: TSizes.md),
          Text(
            'Performing Liveness Check...',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: TColors.primary,
            ),
          ),
          const SizedBox(height: TSizes.sm),
          Text(
            'Please follow the on-screen instructions',
            style: TextStyle(fontSize: 14, color: secondaryTextColor),
          ),
        ],
      ),
    );
  }

  Widget _buildImageDisplay(SelfieVerificationController controller) {
    if (controller.selfieImage.value == null) return const SizedBox.shrink();

    return ImageUploader(
      image: controller.selfieImage.value,
      title: 'Selfie Verification',
      subtitle: _getImageSubtitle(controller),
      errorMessage: controller.selfieError.value,
      isUploading: controller.isUploadingSelfie.value,
      isVerifying:
          controller.isVerifyingFace.value ||
          controller.isComparingWithIDCard.value,
      isConfirmed: controller.hasConfirmedSelfie.value,
      onTapToSelect: () {}, // Disabled
      onClear:
          controller.hasConfirmedSelfie.value
              ? null
              : () {
                controller.clearSelfieImage();
                // Reset all states when clearing
                controller.resetVerificationState();
              },
      onValidate: null,
      placeholderIcon: Icons.face,
      isSuccess: controller.isMatchWithIDCard.value,
    );
  }

  String _getImageSubtitle(SelfieVerificationController controller) {
    if (controller.isVerifyingFace.value) {
      return 'Analyzing your selfie...';
    }
    if (controller.isComparingWithIDCard.value) {
      return 'Comparing with ID card...';
    }
    if (controller.isMatchWithIDCard.value) {
      return 'Verification successful!';
    }
    if (controller.faceComparisonResult.value != null &&
        !controller.isMatchWithIDCard.value) {
      return 'Verification failed - please try again';
    }
    if (controller.isLivenessCheckPassed.value) {
      return 'Liveness check passed!';
    }
    return 'Your selfie photo';
  }

  Widget _buildStatusMessage(
    VerificationStatus status,
    SelfieVerificationController controller,
    BuildContext context,
  ) {
    final isDark = THelperFunctions.isDarkMode(context);

    switch (status) {
      case VerificationStatus.initial:
      case VerificationStatus.performingLiveness:
        return const SizedBox.shrink();

      case VerificationStatus.detectingFace:
        return ValidationMessageCard(
          message: 'Analyzing your selfie image for face detection...',
          isValid: false,
          isLoading: true,
          title: 'Detecting Face',
          icon: Icons.face_retouching_natural,
          customColor: isDark ? TColors.accent : TColors.primary,
        );

      case VerificationStatus.comparingWithID:
        return ValidationMessageCard(
          message: 'Comparing your selfie with your ID card photo...',
          isValid: false,
          isLoading: true,
          title: 'Face Matching',
          icon: Icons.compare,
          customColor: isDark ? TColors.accent : TColors.primary,
        );

      case VerificationStatus.livenessCompleted:
        return ValidationMessageCard(
          message: 'Liveness check passed! Proceeding with ID comparison...',
          isValid: true,
          title: 'Liveness Check Passed',
          icon: Icons.security_update_good,
        );

      case VerificationStatus.verificationComplete:
        return ValidationMessageCard(
          message:
              'Your selfie matches your ID card photo with ${(controller.matchConfidence.value * 100).toStringAsFixed(1)}% confidence.',
          isValid: true,
          hasConfirmed: controller.hasConfirmedSelfie.value,
          title: 'Face Match Successful',
          icon: Icons.verified_user,
          onConfirm: controller.confirmSelfieImage,
          onTryAnother: () {
            controller.clearSelfieImage();
            controller.resetVerificationState();
          },
        );

      case VerificationStatus.verificationFailed:
        return ValidationMessageCard(
          message:
              'Your selfie doesn\'t appear to match your ID card photo. Please try taking another selfie.',
          isValid: false,
          title: 'Face Match Failed',
          icon: Icons.face_retouching_off,
          customColor: TColors.warning,
          customAction: TextButton.icon(
            onPressed: () {
              controller.clearSelfieImage();
              controller.resetVerificationState();
              controller.performLivenessDetection();
            },
            icon: Icon(
              Icons.refresh,
              color: TColors.warning,
              size: TSizes.iconSm,
            ),
            label: Text('Try Again', style: TextStyle(color: TColors.warning)),
            style: TextButton.styleFrom(
              padding: const EdgeInsets.symmetric(
                horizontal: TSizes.md,
                vertical: TSizes.xs,
              ),
              backgroundColor: TColors.warning.withOpacity(0.1),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(TSizes.borderRadiusSm),
              ),
            ),
          ),
        );

      default:
        return const SizedBox.shrink();
    }
  }

  Widget _buildHeader() {
    BuildContext context = Get.context!;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Selfie Verification',
          style: Theme.of(
            context,
          ).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: TSizes.sm),
        Text(
          'Take a clear selfie for identity verification',
          style: Theme.of(context).textTheme.bodyLarge,
        ),
        const SizedBox(height: TSizes.xs),
        Text(
          'We need to verify that it\'s really you by performing a liveness check',
          style: Theme.of(
            context,
          ).textTheme.bodySmall?.copyWith(fontStyle: FontStyle.italic),
        ),
        const SizedBox(height: TSizes.spaceBtwItems),
      ],
    );
  }

  Widget _buildSelfieTips() {
    return TipsContainer(
      title: 'Tips for Better Face Detection:',
      tips: [
        'Find a well-lit area with even lighting',
        'Remove glasses and face coverings if possible',
        'Look directly at the camera',
        'Keep a neutral expression initially',
        'Follow all on-screen instructions carefully',
        'Keep your face centered within the frame',
        'Ensure your entire face is visible',
        'Avoid shadows on your face',
      ],
     
    );
  }
}
