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

// Enum for bracket positions
enum BracketPosition { topLeft, topRight, bottomLeft, bottomRight }

class CameraPreviewWidget extends StatelessWidget {
  final FaceLivenessController controller;
  final double screenWidth;

  const CameraPreviewWidget({
    super.key,
    required this.controller,
    required this.screenWidth,
  });

  @override
  Widget build(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;

    return Obx(() {
      // Check if controller is disposed
      if (controller.status.value == LivenessStatus.dispose) {
        return _buildCameraPlaceholder(context, "Camera is not available");
      }

      final bool isInitialized =
          controller.cameraController?.value.isInitialized ?? false;
      final bool isCountdown =
          controller.status.value == LivenessStatus.countdown;

      if (!isInitialized) {
        return _buildCameraPlaceholder(context, "Camera is initializing...");
      }

      // Calculate aspect ratio to maintain camera feed proportions
      final cameraRatio = controller.cameraController!.value.aspectRatio;

      // Full screen camera preview with overlays
      return Stack(
        children: [
          // Camera feed takes the full available width and adjusts height based on aspect ratio
          Positioned.fill(
            child: ClipRRect(
              child: Transform.scale(
                scale: 1.1, // Slight zoom for better framing
                child: AspectRatio(
                  aspectRatio: 1 / cameraRatio,
                  child: CameraPreview(controller.cameraController!),
                ),
              ),
            ),
          ),

          // Dark overlay for better visibility of UI elements
          Positioned.fill(
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.black.withOpacity(0.3),
                    Colors.transparent,
                    Colors.transparent,
                    Colors.black.withOpacity(0.3),
                  ],
                  stops: const [0.0, 0.25, 0.75, 1.0],
                ),
              ),
            ),
          ),

          // Face outline guide with corner brackets
          Center(child: _buildFaceGuideWithBrackets(screenWidth)),

          // Face indicator icon (shows when no face is detected)
          if (!controller.isFaceInFrame.value)
            Center(
              child: Icon(
                Icons.face,
                color: Colors.white.withOpacity(0.7),
                size: 48,
              ),
            ),

          // Instructions banner at the bottom of the screen (fixed position)
          Positioned(
            bottom: screenHeight * 0.15, // Position from bottom
            left: 0,
            right: 0,
            child: Center(
              child: Container(
                margin: EdgeInsets.symmetric(horizontal: 20),
                padding: EdgeInsets.symmetric(vertical: 12, horizontal: 20),
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.5),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(_getInstructionIcon(), color: Colors.white, size: 22),
                    SizedBox(width: 12),
                    Flexible(
                      child: Text(
                        _getActionText(),
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      );
    });
  }

  // Build face guide with corner brackets
  Widget _buildFaceGuideWithBrackets(double screenWidth) {
    final guideWidth = screenWidth * 0.7;
    final guideHeight =
        guideWidth * 1.2; // Make it slightly taller than wide for face
    final color = _getFaceGuideColor();

    return SizedBox(
      width: guideWidth,
      height: guideHeight,
      child: Stack(
        children: [
          // Invisible container to define the area
          Container(
            width: guideWidth,
            height: guideHeight,
            decoration: BoxDecoration(color: Colors.transparent),
          ),

          // Top-left corner
          Positioned(
            top: 0,
            left: 0,
            child: _buildCornerBracket(color, BracketPosition.topLeft),
          ),

          // Top-right corner
          Positioned(
            top: 0,
            right: 0,
            child: _buildCornerBracket(color, BracketPosition.topRight),
          ),

          // Bottom-left corner
          Positioned(
            bottom: 0,
            left: 0,
            child: _buildCornerBracket(color, BracketPosition.bottomLeft),
          ),

          // Bottom-right corner
          Positioned(
            bottom: 0,
            right: 0,
            child: _buildCornerBracket(color, BracketPosition.bottomRight),
          ),
        ],
      ),
    );
  }

  // Build a corner bracket
  Widget _buildCornerBracket(Color color, BracketPosition position) {
    final bracketThickness = 3.0;
    final bracketLength = 25.0;

    return SizedBox(
      width: bracketLength,
      height: bracketLength,
      child: CustomPaint(
        painter: CornerBracketPainter(
          color: color,
          strokeWidth: bracketThickness,
          position: position,
        ),
      ),
    );
  }

  // Placeholder widget when camera isn't available/initialized
  Widget _buildCameraPlaceholder(BuildContext context, String message) {
    return Container(
      color: Colors.black,
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.camera_alt_outlined,
              size: 48,
              color: Colors.white.withOpacity(0.7),
            ),
            const SizedBox(height: 16),
            Text(
              message,
              style: TextStyle(color: Colors.white.withOpacity(0.7)),
            ),
          ],
        ),
      ),
    );
  }

  // Get action text based on current status
  String _getActionText() {
    switch (controller.status.value) {
      case LivenessStatus.detectingFace:
        return 'Position your face within the frame';
      case LivenessStatus.checkLeftRotation:
        return 'Turn your head to the left';
      case LivenessStatus.checkRightRotation:
        return 'Turn your head to the right';
      case LivenessStatus.checkSmile:
        return 'Please smile';
      case LivenessStatus.checkEyesOpen:
        return 'Keep your eyes open';
      case LivenessStatus.readyForPhoto:
        return 'Perfect! Hold still';
      case LivenessStatus.countdown:
        return 'Please hold your pose';
      default:
        return 'Follow instructions';
    }
  }

  // Get appropriate icon for instructions
  IconData _getInstructionIcon() {
    switch (controller.status.value) {
      case LivenessStatus.detectingFace:
        return Icons.face;
      case LivenessStatus.checkLeftRotation:
        return Icons.rotate_left;
      case LivenessStatus.checkRightRotation:
        return Icons.rotate_right;
      case LivenessStatus.checkSmile:
        return Icons.sentiment_satisfied_alt;
      case LivenessStatus.checkEyesOpen:
        return Icons.remove_red_eye;
      case LivenessStatus.readyForPhoto:
      case LivenessStatus.countdown:
        return Icons.photo_camera;
      default:
        return Icons.info;
    }
  }

  // Function to color the face guide based on detection state
  Color _getFaceGuideColor() {
    if (controller.status.value == LivenessStatus.countdown) {
      return Colors.green; // Green during countdown
    } else if (controller.isFaceInFrame.value) {
      return controller.isFaceReadyForPhoto.value
          ? Colors.green
          : TColors.primary;
    } else {
      return Colors.white;
    }
  }
}

// Custom painter for corner brackets
class CornerBracketPainter extends CustomPainter {
  final Color color;
  final double strokeWidth;
  final BracketPosition position;

  CornerBracketPainter({
    required this.color,
    required this.strokeWidth,
    required this.position,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint =
        Paint()
          ..color = color
          ..strokeWidth = strokeWidth
          ..strokeCap = StrokeCap.square
          ..style = PaintingStyle.stroke;

    final path = Path();

    switch (position) {
      case BracketPosition.topLeft:
        path.moveTo(0, size.height * 0.4);
        path.lineTo(0, 0);
        path.lineTo(size.width * 0.4, 0);
        break;
      case BracketPosition.topRight:
        path.moveTo(size.width * 0.6, 0);
        path.lineTo(size.width, 0);
        path.lineTo(size.width, size.height * 0.4);
        break;
      case BracketPosition.bottomLeft:
        path.moveTo(0, size.height * 0.6);
        path.lineTo(0, size.height);
        path.lineTo(size.width * 0.4, size.height);
        break;
      case BracketPosition.bottomRight:
        path.moveTo(size.width * 0.6, size.height);
        path.lineTo(size.width, size.height);
        path.lineTo(size.width, size.height * 0.6);
        break;
    }

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
