import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_tabler_icons/flutter_tabler_icons.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/onboarding/presentasion/controllers/role_selection_controller.dart';
import 'package:sigap/src/utils/constants/image_strings.dart';
import 'package:sigap/src/utils/constants/sizes.dart';
import 'package:sigap/src/utils/helpers/helper_functions.dart';
import 'package:sigap/src/utils/loaders/shimmer.dart';

class RoleSelectionScreen extends StatelessWidget {
  final void Function(String roleId)? onRoleSelected;
  const RoleSelectionScreen({super.key, this.onRoleSelected});

  @override
  Widget build(BuildContext context) {
    final controller = Get.find<RoleSelectionController>();
    final isDark = THelperFunctions.isDarkMode(Get.context!);

    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: isDark ? Brightness.light : Brightness.dark,
      ),
    );

    return Scaffold(
      backgroundColor:
          isDark ? const Color(0xFF18191A) : const Color(0xFFF7F7F5),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: Container(
                margin: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: isDark ? const Color(0xFF232425) : Colors.white,
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(
                    color:
                        isDark
                            ? const Color(0xFF343536)
                            : const Color(0xFFE5E5E5),
                    width: 1,
                  ),
                  boxShadow:
                      isDark
                          ? []
                          : [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.04),
                              blurRadius: 8,
                              offset: const Offset(0, 2),
                            ),
                          ],
                ),
                child: Padding(
                  padding: const EdgeInsets.all(32),
                  child: Column(
                    children: [
                      // Top illustration that changes based on selection
                      Expanded(
                        flex: 3,
                        child: Obx(
                          () => _buildTopIllustration(controller, isDark),
                        ),
                      ),
                      const SizedBox(height: 40),
                      Text(
                        'Choose your role',
                        style: TextStyle(
                          fontSize: 32,
                          fontWeight: FontWeight.w700,
                          color:
                              isDark ? Colors.white : const Color(0xFF2F2F2F),
                          letterSpacing: -0.5,
                        ),
                        textAlign: TextAlign.center,
                      ),
                      const SizedBox(height: 12),
                      Obx(
                        () => Text(
                          _getSubtitleText(controller, isDark),
                          style: TextStyle(
                            fontSize: 16,
                            color:
                                isDark
                                    ? Colors.white70
                                    : const Color(0xFF6B6B6B),
                            height: 1.5,
                            fontWeight: FontWeight.w400,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),
                      const SizedBox(height: 48),
                      Obx(() {
                        if (controller.isRolesLoading.value) {
                          return _buildShimmerCards(isDark);
                        } else {
                          return _buildRoleCards(controller, isDark);
                        }
                      }),
                      const SizedBox(height: 48),
                      Obx(
                        () =>
                            controller.selectedRole.value != null
                                ? _SwipeRightHint(isDark: isDark)
                                : const SizedBox(height: 48),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTopIllustration(
    RoleSelectionController controller,
    bool isDark,
  ) {
    // Default illustration when no role is selected
    if (controller.selectedRole.value == null) {
      return Container(
        decoration: BoxDecoration(
          color: isDark ? const Color(0xFF232425) : const Color(0xFFFAFAFA),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: isDark ? const Color(0xFF343536) : const Color(0xFFEEEEEE),
            width: 1,
          ),
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12),
          child: SvgPicture.asset(
            isDark ? TImages.communicationDark : TImages.communication,
            width: double.infinity,
            height: double.infinity,
            fit: BoxFit.cover,
            colorFilter:
                isDark
                    ? const ColorFilter.mode(Colors.white70, BlendMode.srcIn)
                    : null,
          ),
        ),
      );
    }

    // Change illustration based on selected role (viewer/officer only)
    final name = controller.selectedRole.value?.name.toLowerCase() ?? '';
    String asset;
    bool isSvg = false;

    if (name.contains('officer')) {
      asset = isDark ? TImages.customerSupportDark : TImages.customerSupport;
    } else {
      asset = isDark ? TImages.communication : TImages.communication;
    }

    if (asset.toLowerCase().endsWith('.svg')) {
      isSvg = true;
    }

    return Container(
      decoration: BoxDecoration(
        color: isDark ? const Color(0xFF232425) : const Color(0xFFFAFAFA),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: isDark ? const Color(0xFF343536) : const Color(0xFFEEEEEE),
          width: 1,
        ),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child:
            isSvg
                ? SvgPicture.asset(
                  asset,
                  width: double.infinity,
                  height: double.infinity,
                  fit: BoxFit.cover,
                  colorFilter:
                      isDark
                          ? const ColorFilter.mode(
                            Colors.white70,
                            BlendMode.srcIn,
                          )
                          : null,
                )
                : Image.asset(
                  asset,
                  width: double.infinity,
                  height: double.infinity,
                  fit: BoxFit.cover,
                  color: isDark ? Colors.white70 : null,
                  colorBlendMode: isDark ? BlendMode.srcIn : null,
                ),
      ),
    );
  }

  String _getSubtitleText(RoleSelectionController controller, bool isDark) {
    if (controller.selectedRole.value == null) {
      return isDark
          ? 'Select your role to start your journey.\nYou can always change it later.'
          : 'Select your role to get started with\nyour learning journey.';
    }

    final selectedRole = controller.selectedRole.value!.name.toLowerCase();
    if (selectedRole.contains('officer')) {
      return 'You will manage crime related tasks, handle reports, and ensure the safety of the community.';
    } else {
      return 'You have access to panic button for our early warning system. ';
    }
  }

  Widget _buildRoleCards(RoleSelectionController controller, bool isDark) {
    return Row(
      children: [
        // First role card
        Expanded(
          child: Obx(
            () => _buildRoleCard(
              title:
                  controller.roles.isNotEmpty
                      ? controller.roles[0].name
                      : 'Officer',
              isSelected:
                  controller.selectedRole.value?.id ==
                  (controller.roles.isNotEmpty ? controller.roles[0].id : null),
              onTap:
                  () =>
                      controller.roles.isNotEmpty
                          ? controller.selectRole(controller.roles[0])
                          : null,
              illustration: _buildCardOfficerIllustration(isDark),
              isDark: isDark,
            ),
          ),
        ),
        const SizedBox(width: 16),
        // Second role card
        Expanded(
          child: Obx(
            () => _buildRoleCard(
              title:
                  controller.roles.length > 1
                      ? controller.roles[1].name
                      : 'Viewer',
              isSelected:
                  controller.selectedRole.value?.id ==
                  (controller.roles.length > 1 ? controller.roles[1].id : null),
              onTap:
                  () =>
                      controller.roles.length > 1
                          ? controller.selectRole(controller.roles[1])
                          : null,
              illustration: _buildCardViewerIllustration(isDark),
              isDark: isDark,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildRoleCard({
    required String title,
    required bool isSelected,
    required VoidCallback? onTap,
    required Widget illustration,
    required bool isDark,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 140,
        decoration: BoxDecoration(
          color:
              isSelected
                  ? (isDark ? const Color(0xFF232425) : const Color(0xFFF8F9FA))
                  : (isDark ? const Color(0xFF18191A) : Colors.white),
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color:
                isSelected
                    ? (isDark ? Colors.white : const Color(0xFF2F2F2F))
                    : (isDark
                        ? const Color(0xFF343536)
                        : const Color(0xFFE5E5E5)),
            width: isSelected ? 2 : 1,
          ),
          boxShadow:
              isSelected && !isDark
                  ? [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.08),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ]
                  : null,
        ),
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              illustration,
              const SizedBox(height: 16),
              Text(
                title,
                style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w600,
                  color: isDark ? Colors.white : const Color(0xFF2F2F2F),
                  letterSpacing: 0.1,
                ),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildCardViewerIllustration(bool isDark) {
    return Container(
      width: 50,
      height: 50,
      decoration: BoxDecoration(
        color: isDark ? const Color(0xFF232425) : const Color(0xFFF5F5F5),
        borderRadius: BorderRadius.circular(25),
        border: Border.all(
          color: isDark ? const Color(0xFF343536) : const Color(0xFFE0E0E0),
          width: 1,
        ),
      ),
      child: Center(
        child: Container(
          width: 24,
          height: 24,
          decoration: BoxDecoration(
            color: isDark ? Colors.white : const Color(0xFF2F2F2F),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Icon(
            TablerIcons.user_star,
            color: isDark ? Colors.black : Colors.white,
            size: 14,
          ),
        ),
      ),
    );
  }

  Widget _buildCardOfficerIllustration(bool isDark) {
    return Container(
      width: 50,
      height: 50,
      decoration: BoxDecoration(
        color: isDark ? const Color(0xFF232425) : const Color(0xFFF5F5F5),
        borderRadius: BorderRadius.circular(25),
        border: Border.all(
          color: isDark ? const Color(0xFF343536) : const Color(0xFFE0E0E0),
          width: 1,
        ),
      ),
      child: Center(
        child: Container(
          width: 24,
          height: 24,
          decoration: BoxDecoration(
            color: isDark ? Colors.white : const Color(0xFF2F2F2F),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Icon(
            TablerIcons.user,
            color: isDark ? Colors.black : Colors.white,
            size: 14,
          ),
        ),
      ),
    );
  }

  Widget _buildShimmerCards(bool isDark) {
    return Row(
      children: [
        Expanded(
          child: Container(
            height: 140,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
              color: isDark ? const Color(0xFF232425) : const Color(0xFFF5F5F5),
              border: Border.all(
                color:
                    isDark ? const Color(0xFF343536) : const Color(0xFFE5E5E5),
                width: 1,
              ),
            ),
            child: const TShimmerEffect(
              width: double.infinity,
              height: 140,
              radius: 8,
            ),
          ),
        ),
        const SizedBox(width: 16),
        Expanded(
          child: Container(
            height: 140,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
              color: isDark ? const Color(0xFF232425) : const Color(0xFFF5F5F5),
              border: Border.all(
                color:
                    isDark ? const Color(0xFF343536) : const Color(0xFFE5E5E5),
                width: 1,
              ),
            ),
            child: const TShimmerEffect(
              width: double.infinity,
              height: 140,
              radius: 8,
            ),
          ),
        ),
      ],
    );
  }
}


// Tambahkan widget animasi swipe hint di bawah:
class _SwipeRightHint extends StatefulWidget {
  final bool isDark;
  const _SwipeRightHint({required this.isDark});

  @override
  State<_SwipeRightHint> createState() => _SwipeRightHintState();
}

class _SwipeRightHintState extends State<_SwipeRightHint>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1200),
    )..repeat(reverse: true);
    _animation = Tween<double>(
      begin: 0,
      end: 32,
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut));
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final color = widget.isDark ? Colors.white : const Color(0xFF2F2F2F);
    return SizedBox(
      height: 48,
      child: Center(
        child: AnimatedBuilder(
          animation: _animation,
          builder:
              (context, child) => Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    'Swipe right to register',
                    style: TextStyle(
                      fontSize: TSizes.fontSizeMd,
                      fontWeight: FontWeight.w500,
                      color: color,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Transform.translate(
                    offset: Offset(_animation.value, 0),
                    child: Icon(
                      Icons.arrow_forward_rounded,
                      color: color,
                      size: 28,
                    ),
                  ),
                ],
              ),
        ),
      ),
    );
  }
}
