import 'dart:developer' as dev;
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/selfie-verification/face_liveness_detection_controller.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/selfie-verification/selfie_verification_controller.dart';
import 'package:sigap/src/utils/constants/colors.dart';
import 'package:sigap/src/utils/constants/sizes.dart';

class CapturedSelfieView extends StatefulWidget {
  final FaceLivenessController controller;
  final SelfieVerificationController? selfieController;

  const CapturedSelfieView({
    super.key,
    required this.controller,
    this.selfieController,
  });

  @override
  State<CapturedSelfieView> createState() => _CapturedSelfieViewState();
}

class _CapturedSelfieViewState extends State<CapturedSelfieView>
    with TickerProviderStateMixin {
  // Use standard ValueNotifier instead of GetX observables
  final ValueNotifier<bool> isComparingWithID = ValueNotifier(false);
  final ValueNotifier<String?> errorMessage = ValueNotifier(null);
  bool isDisposed = false;

  late AnimationController _fadeController;
  late AnimationController _scaleController;
  late AnimationController _slideController;

  late Animation<double> _fadeAnimation;
  late Animation<double> _scaleAnimation;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    // Immediately pause detection to prevent state changes during transition
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!isDisposed && mounted) {
        widget.controller.pauseDetection();
      }
    });

    // Initialize animations
    _fadeController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );

    _scaleController = AnimationController(
      duration: const Duration(milliseconds: 600),
      vsync: this,
    );

    _slideController = AnimationController(
      duration: const Duration(milliseconds: 700),
      vsync: this,
    );

    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _fadeController, curve: Curves.easeInOut),
    );

    _scaleAnimation = Tween<double>(begin: 0.8, end: 1.0).animate(
      CurvedAnimation(parent: _scaleController, curve: Curves.elasticOut),
    );

    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(
      CurvedAnimation(parent: _slideController, curve: Curves.easeOutCubic),
    );

    // Start animations
    _startAnimations();
  }

  void _startAnimations() async {
    // Check if widget is still mounted before running animations
    if (!mounted) return;

    try {
      await Future.delayed(const Duration(milliseconds: 100));
      // Check mounted again after the delay
      if (!mounted || isDisposed) return;
      _fadeController.forward();

      await Future.delayed(const Duration(milliseconds: 200));
      if (!mounted || isDisposed) return;
      _scaleController.forward();

      await Future.delayed(const Duration(milliseconds: 300));
      if (!mounted || isDisposed) return;
      _slideController.forward();
    } catch (e) {
      dev.log('Error starting animations: $e', name: 'SELFIE_VIEW');
      // No need to rethrow - just log the error
    }
  }

  @override
  void dispose() {
    // Mark as disposed before calling dispose on controllers
    isDisposed = true;
    
    // Dispose ValueNotifiers
    isComparingWithID.dispose();
    errorMessage.dispose();

    // Safety check to prevent calling methods on disposed controllers
    try {
      if (_fadeController.isAnimating) _fadeController.stop();
      if (_scaleController.isAnimating) _scaleController.stop();
      if (_slideController.isAnimating) _slideController.stop();

      _fadeController.dispose();
      _scaleController.dispose();
      _slideController.dispose();
    } catch (e) {
      dev.log('Error disposing animation controllers: $e', name: 'SELFIE_VIEW');
    }
    
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isDarkMode = theme.brightness == Brightness.dark;

    // Use ValueListenableBuilder instead of Obx
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors:
                isDarkMode
                    ? [
                      TColors.dark,
                      TColors.dark.withGreen(20),
                      TColors.primary.withOpacity(0.1),
                    ]
                    : [
                      TColors.white,
                      TColors.primary.withOpacity(0.05),
                      TColors.primary.withOpacity(0.15),
                    ],
          ),
        ),
        child: SafeArea(
          child: SingleChildScrollView(
            physics: const BouncingScrollPhysics(),
            child: Padding(
              padding: const EdgeInsets.all(TSizes.defaultSpace),
              child: Column(
                children: [
                  const SizedBox(height: TSizes.spaceBtwSections),

                  // Animated success header
                  FadeTransition(
                    opacity: _fadeAnimation,
                    child: ScaleTransition(
                      scale: _scaleAnimation,
                      child: _buildSuccessHeader(theme, isDarkMode),
                    ),
                  ),

                  const SizedBox(height: TSizes.spaceBtwSections * 1.5),

                  // Animated selfie image
                  FadeTransition(
                    opacity: _fadeAnimation,
                    child: ScaleTransition(
                      scale: _scaleAnimation,
                      child: _buildSelfieImage(),
                    ),
                  ),

                  const SizedBox(height: TSizes.spaceBtwSections * 1.5),

                  // Animated completed steps
                  SlideTransition(
                    position: _slideAnimation,
                    child: FadeTransition(
                      opacity: _fadeAnimation,
                      child: _buildCompletedStepsList(),
                    ),
                  ),

                  const SizedBox(height: TSizes.spaceBtwSections),

                  // Error message with animation - use ValueListenableBuilder
                  ValueListenableBuilder<String?>(
                    valueListenable: errorMessage,
                    builder: (context, errorMsg, _) {
                      return errorMsg != null
                          ? SlideTransition(
                              position: _slideAnimation,
                              child: _buildErrorMessage(theme, isDarkMode),
                            )
                          : const SizedBox.shrink();
                    },
                  ),

                  const SizedBox(height: TSizes.spaceBtwSections),

                  // Animated action buttons - use ValueListenableBuilder
                  SlideTransition(
                    position: _slideAnimation,
                    child: FadeTransition(
                      opacity: _fadeAnimation,
                      child: ValueListenableBuilder<bool>(
                        valueListenable: isComparingWithID,
                        builder: (context, isComparing, _) {
                          return _buildActionButtons(theme, isComparing);
                        },
                      ),
                    ),
                  ),

                  const SizedBox(height: TSizes.spaceBtwSections),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildSuccessHeader(ThemeData theme, bool isDarkMode) {
    return Column(
      children: [
        // Enhanced success icon with glow effect
        Container(
          padding: const EdgeInsets.all(TSizes.lg),
          decoration: BoxDecoration(
            gradient: RadialGradient(
              colors: [
                TColors.primary.withOpacity(0.3),
                TColors.primary.withOpacity(0.1),
                Colors.transparent,
              ],
            ),
            shape: BoxShape.circle,
          ),
          child: Container(
            padding: const EdgeInsets.all(TSizes.md),
            decoration: BoxDecoration(
              color: TColors.primary.withOpacity(0.15),
              shape: BoxShape.circle,
              border: Border.all(
                color: TColors.primary.withOpacity(0.3),
                width: 2,
              ),
            ),
            child: Icon(Icons.verified, color: TColors.primary, size: 56),
          ),
        ),

        const SizedBox(height: TSizes.spaceBtwItems),

        // Enhanced title with gradient text effect
        ShaderMask(
          shaderCallback:
              (bounds) => LinearGradient(
                colors: [TColors.primary, TColors.primary.withOpacity(0.8)],
              ).createShader(bounds),
          child: Text(
            'Verification Complete!',
            style: theme.textTheme.headlineMedium?.copyWith(
              fontWeight: FontWeight.bold,
              color: Colors.white,
              letterSpacing: 0.5,
            ),
            textAlign: TextAlign.center,
          ),
        ),

        const SizedBox(height: TSizes.sm),

        Text(
          'Your identity has been successfully verified',
          style: theme.textTheme.bodyLarge?.copyWith(
            color: theme.textTheme.bodyMedium?.color?.withOpacity(0.8),
            height: 1.4,
          ),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  Widget _buildSelfieImage() {
    if (widget.controller.capturedImage == null) return const SizedBox.shrink();

    return Hero(
      tag: 'selfie_image',
      child: Container(
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              TColors.primary.withOpacity(0.2),
              TColors.primary.withOpacity(0.1),
            ],
          ),
          boxShadow: [
            BoxShadow(
              color: TColors.primary.withOpacity(0.3),
              blurRadius: 30,
              spreadRadius: 0,
              offset: const Offset(0, 10),
            ),
            BoxShadow(
              color: TColors.dark.withOpacity(0.1),
              blurRadius: 20,
              spreadRadius: 2,
              offset: const Offset(0, 5),
            ),
          ],
        ),
        padding: const EdgeInsets.all(6),
        child: Container(
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(color: TColors.white, width: 4),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(120),
            child: Image.file(
              File(widget.controller.capturedImage!.path),
              width: 220,
              height: 220,
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildCompletedStepsList() {
    final theme = Theme.of(context);
    final isDarkMode = theme.brightness == Brightness.dark;

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(TSizes.lg),
      decoration: BoxDecoration(
        color:
            isDarkMode
                ? TColors.dark.withOpacity(0.8)
                : TColors.white.withOpacity(0.9),
        borderRadius: BorderRadius.circular(TSizes.cardRadiusLg),
        border: Border.all(color: TColors.primary.withOpacity(0.1), width: 1),
        boxShadow: [
          BoxShadow(
            color: TColors.dark.withOpacity(0.08),
            blurRadius: 20,
            spreadRadius: 0,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.green.withOpacity(0.15),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(
                  Icons.shield_outlined,
                  color: Colors.green.shade600,
                  size: 24,
                ),
              ),
              const SizedBox(width: TSizes.md),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Security Verification',
                      style: theme.textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.w600,
                        color: Colors.green.shade700,
                      ),
                    ),
                    Text(
                      'All checks completed successfully',
                      style: theme.textTheme.bodySmall?.copyWith(
                        color: theme.textTheme.bodySmall?.color?.withOpacity(
                          0.7,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),

          const SizedBox(height: TSizes.md),

          Divider(color: TColors.primary.withOpacity(0.1), thickness: 1),

          const SizedBox(height: TSizes.md),

          ...widget.controller.successfulSteps.asMap().entries.map((entry) {
            final index = entry.key;
            final step = entry.value;

            return TweenAnimationBuilder<double>(
              duration: Duration(milliseconds: 300 + (index * 100)),
              tween: Tween(begin: 0.0, end: 1.0),
              builder: (context, value, child) {
                  return Transform.translate(
                    offset: Offset(20 * (1 - value), 0),
                    child: Opacity(
                      opacity: value,
                      child: Padding(
                        padding: const EdgeInsets.only(bottom: TSizes.sm),
                        child: Row(
                          children: [
                            Container(
                              padding: const EdgeInsets.all(6),
                              decoration: BoxDecoration(
                                color: Colors.green.withOpacity(0.15),
                                shape: BoxShape.circle,
                              ),
                              child: Icon(
                                Icons.check_rounded,
                                color: Colors.green.shade600,
                                size: 16,
                              ),
                            ),
                            const SizedBox(width: TSizes.md),
                            Expanded(
                              child: Text(
                                step,
                                style: theme.textTheme.bodyMedium?.copyWith(
                                  height: 1.4,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              );
          }),
        ],
      ),
    );
  }

  // Update error message widget to use ValueNotifier
  Widget _buildErrorMessage(ThemeData theme, bool isDarkMode) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(TSizes.md),
      decoration: BoxDecoration(
        color:
            isDarkMode
                ? TColors.warning.withOpacity(0.1)
                : TColors.warning.withOpacity(0.05),
        borderRadius: BorderRadius.circular(TSizes.cardRadiusMd),
        border: Border.all(color: TColors.warning.withOpacity(0.3)),
      ),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: TColors.warning.withOpacity(0.2),
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.warning_amber_rounded,
              color: TColors.warning,
              size: 20,
            ),
          ),
          const SizedBox(width: TSizes.md),
          Expanded(
            child: ValueListenableBuilder<String?>(
              valueListenable: errorMessage,
              builder: (context, msg, _) {
                return Text(
                  msg ?? '',
                  style: theme.textTheme.bodyMedium?.copyWith(
                    color: TColors.warning,
                    height: 1.4,
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  // Update action buttons to use ValueNotifier
  Widget _buildActionButtons(ThemeData theme, bool isComparing) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // Continue button with enhanced styling
        ElevatedButton(
          onPressed: isComparing ? null : _handleContinueButton,
          style: ElevatedButton.styleFrom(
            backgroundColor: TColors.primary,
            foregroundColor: TColors.white,
            elevation: isComparing ? 0 : 8,
            shadowColor: TColors.primary.withOpacity(0.4),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(TSizes.cardRadiusMd),
            ),
            padding: const EdgeInsets.symmetric(vertical: TSizes.md),
          ),
          child: isComparing
              ? Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(
                      color: TColors.white,
                      strokeWidth: 2,
                    ),
                  ),
                  const SizedBox(width: TSizes.md),
                  const Text(
                    'Processing...',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              )
              : Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Text(
                    'Continue',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(width: TSizes.sm),
                  Icon(
                    Icons.arrow_forward_rounded,
                    size: 20,
                    color: TColors.white,
                  ),
                ],
              ),
        ),

        const SizedBox(height: TSizes.md),

        // Try again button when there's an error
        ValueListenableBuilder<String?>(
          valueListenable: errorMessage,
          builder: (context, msg, _) {
            return msg != null
                ? OutlinedButton(
                    onPressed: () {
                      if (!isDisposed) {
                        errorMessage.value = null;
                      }
                      widget.controller.disposeCamera();
                      Get.back();
                    },
                    style: OutlinedButton.styleFrom(
                      side: BorderSide(color: TColors.primary),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(
                          TSizes.cardRadiusMd,
                        ),
                      ),
                      padding: const EdgeInsets.symmetric(vertical: TSizes.md),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.refresh_rounded,
                          size: 20,
                          color: TColors.primary,
                      ),
                        const SizedBox(width: TSizes.sm),
                      Text(
                          'Try Again',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w500,
                            color: TColors.primary,
                          ),
                        ),
                      ],
                    ),
                  )
                : const SizedBox.shrink();
          },
        ),
      ],
    );
  }

  // Fix the continue button handler to navigate directly to the selfie verification step
  Future<void> _handleContinueButton() async {
    if (!mounted || isDisposed) return;
    
    try {
      if (widget.controller.capturedImage == null) {
        dev.log('Error: No captured image available', name: 'LIVENESS_DEBUG');
        errorMessage.value = 'No image was captured. Please try again.';
        return;
      }

      isComparingWithID.value = true;
      
      if (widget.selfieController != null) {
        errorMessage.value = null;

        dev.log(
          'Found SelfieVerificationController, setting captured selfie',
          name: 'LIVENESS_DEBUG',
        );

        // Create a copy of the captured image path to ensure it remains valid
        final imagePath = widget.controller.capturedImage!.path;
        dev.log('Captured image path: $imagePath', name: 'LIVENESS_DEBUG');

        // Create a new XFile instance from the path
        final xFile = XFile(imagePath);

        // Set the liveness flag first
        widget.selfieController!.isLivenessCheckPassed.value = true;

        // Set flag to automatically start verification upon returning
        widget.selfieController!.autoStartVerification = true;

        // Set the captured image in the selfie controller
        widget.selfieController!.selfieImage.value = xFile;

        dev.log(
          'Successfully set image in selfie controller',
          name: 'LIVENESS_DEBUG',
        );

        // Now dispose the camera after we've handled the image
        widget.controller.disposeCamera();

        // Simply go back to the previous screen (selfie verification step)
        Get.back();
      } else {
        widget.controller.disposeCamera();
        
        if (mounted && !isDisposed) {
          Get.back(result: widget.controller.capturedImage);
        }
      }
    } catch (e) {
      dev.log(
        'Error connecting with SelfieVerificationController: $e',
        name: 'LIVENESS_DEBUG',
      );

      if (mounted && !isDisposed) {
        isComparingWithID.value = false;
        errorMessage.value = 'Failed to process the captured image: $e';
      }
    }
  }
}
