import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/onboarding/presentasion/controllers/check_location_controller.dart';

class CheckLocationScreen extends StatefulWidget {
  final VoidCallback? onSuccess;

  const CheckLocationScreen({super.key, this.onSuccess});

  @override
  State<CheckLocationScreen> createState() => _CheckLocationScreenState();
}

class _CheckLocationScreenState extends State<CheckLocationScreen> {
  // Controller
  late CheckLocationController controller;

  @override
  void initState() {
    super.initState();
    controller = Get.put(CheckLocationController(onSuccess: widget.onSuccess));
  }

  // Method to show bottom sheet
  void _showBottomSheet() {
    if (!mounted) return;

    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isDismissible: true,
      isScrollControlled: true,
      builder: (context) {
        final theme = Theme.of(context);
        return Container(
          padding: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            color: theme.cardColor,
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(24),
              topRight: Radius.circular(24),
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: 60,
                height: 5,
                margin: const EdgeInsets.only(bottom: 20),
                decoration: BoxDecoration(
                  color:
                      theme.brightness == Brightness.light
                          ? Colors.grey[300]
                          : Colors.grey[700],
                  borderRadius: BorderRadius.circular(3),
                ),
              ),
              Text(
                'Location Validation Required',
                style: theme.textTheme.titleLarge?.copyWith(
                  fontWeight: FontWeight.bold,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),
              Text(
                'This application is designed specifically for users in the Jember region. We need to validate your location to ensure all services function properly.',
                textAlign: TextAlign.center,
                style: theme.textTheme.bodyMedium,
              ),
              const SizedBox(height: 20),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.touch_app, color: theme.primaryColor),
                  const SizedBox(width: 8),
                  Text(
                    'Press "Check Location" button to proceed',
                    style: theme.textTheme.bodyMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 30),
              ElevatedButton(
                onPressed: () => Navigator.pop(context),
                style: ElevatedButton.styleFrom(
                  minimumSize: Size(200, 50),
                  backgroundColor: theme.primaryColor,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(30),
                  ),
                ),
                child: Text('Got it'),
              ),
              const SizedBox(height: 16),
            ],
          ),
        );
      },
    );
  }

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

    // Show bottom sheet when controller indicates
    // Using ever instead of direct call to avoid rebuilding issues
    ever(controller.bottomSheetShown, (shown) {
      if (shown && mounted) {
        _showBottomSheet();
      }
    });

    return Scaffold(
      backgroundColor: theme.scaffoldBackgroundColor,
      body: SafeArea(
        child: Column(
          children: [
            // Info icon - Fixed Obx usage
            Obx(
              () =>
                  controller.showUIElements.value
                      ? Align(
                        alignment: Alignment.topRight,
                        child: Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: IconButton(
                            onPressed: _showBottomSheet,
                            icon: Icon(
                              Icons.info_outline,
                              color: theme.primaryColor,
                              size: 24,
                            ),
                          ),
                        ),
                      )
                      : const SizedBox.shrink(),
            ),

            // Card carousel with zooming effect - Modify to center the current card during zoom
            Expanded(
              child: AnimatedBuilder(
                animation: controller.scaleAnimation,
                builder: (context, child) {
                  // Calculate current page as an integer for clean zooming on the correct card
                  final currentPageIndex = controller.currentPage.value;

                  // Ensure we're centered on current page during animation
                  if (controller.isLocationValid.value &&
                      controller.scaleAnimation.value > 1.0 &&
                      controller.pageController.hasClients &&
                      controller.pageController.page?.round() !=
                          currentPageIndex) {
                    controller.pageController.jumpToPage(currentPageIndex);
                  }

                  return Transform.scale(
                    scale:
                        controller.isLocationValid.value
                            ? controller.scaleAnimation.value
                            : 1.0,
                    child: child,
                  );
                },
                child: PageView.builder(
                  controller: controller.pageController,
                  onPageChanged: controller.onPageChanged,
                  itemCount: controller.slides.length,
                  physics:
                      controller.isLocationValid.value
                          ? const NeverScrollableScrollPhysics() // Lock scrolling during animation
                          : null,
                  itemBuilder: (context, index) {
                    return _buildCarouselCard(index, theme);
                  },
                ),
              ),
            ),

            // Page indicators - Fixed Obx usage
            Obx(
              () =>
                  controller.showUIElements.value
                      ? Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: List.generate(
                          controller.slides.length,
                          (index) => Container(
                            margin: const EdgeInsets.symmetric(horizontal: 4),
                            width: 8,
                            height: 8,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              color:
                                  controller.currentPage.value == index
                                      ? theme.primaryColor
                                      : theme.disabledColor.withOpacity(0.3),
                            ),
                          ),
                        ),
                      )
                      : const SizedBox.shrink(),
            ),

            const SizedBox(height: 24),

            // Title and subtitle - Fixed Obx usage
            Obx(
              () =>
                  controller.showUIElements.value
                      ? Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 32),
                        child: Column(
                          children: [
                            Text(
                              controller.slides[controller
                                  .currentPage
                                  .value]['title'],
                              style: theme.textTheme.headlineSmall?.copyWith(
                                fontWeight: FontWeight.bold,
                              ),
                              textAlign: TextAlign.center,
                            ),
                            const SizedBox(height: 12),
                            Text(
                              controller.slides[controller
                                  .currentPage
                                  .value]['subtitle'],
                              style: theme.textTheme.bodyMedium?.copyWith(
                                color:
                                    theme.brightness == Brightness.light
                                        ? Colors.grey[600]
                                        : Colors.grey[300],
                              ),
                              textAlign: TextAlign.center,
                            ),
                          ],
                        ),
                      )
                      : const SizedBox.shrink(),
            ),

            const SizedBox(height: 32),

            // Loading indicator - Fixed Obx usage
            // Obx(
            //   () =>
            //       (controller.showUIElements.value &&
            //               controller.isLoading.value)
            //           ? Padding(
            //             padding: const EdgeInsets.symmetric(vertical: 8.0),
            //             child: CircularProgressIndicator(
            //               color: theme.primaryColor,
            //             ),
            //           )
            //           : const SizedBox.shrink(),
            // ),

            // Error message - Fixed Obx usage
            Obx(
              () =>
                  (controller.showUIElements.value &&
                          !controller.isLoading.value &&
                          !controller.isLocationValid.value &&
                          controller.errorMessage.value.isNotEmpty)
                      ? Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          controller.errorMessage.value,
                          style: TextStyle(color: Colors.red),
                          textAlign: TextAlign.center,
                        ),
                      )
                      : const SizedBox.shrink(),
            ),

            // Success message - Fixed Obx usage
            Obx(
              () =>
                  (controller.showUIElements.value &&
                          !controller.isLoading.value &&
                          controller.isLocationValid.value)
                      ? Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          "Location validated successfully!",
                          style: TextStyle(color: Colors.green),
                          textAlign: TextAlign.center,
                        ),
                      )
                      : const SizedBox.shrink(),
            ),

            // Button - Fixed Obx usage
            Obx(
              () =>
                  controller.showUIElements.value
                      ? Padding(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 32.0,
                          vertical: 16.0,
                        ),
                        child: SizedBox(
                          width: double.infinity,
                          child: ElevatedButton(
                            onPressed:
                                controller.isLoading.value
                                    ? null
                                    : controller.handleButtonPress,
                            child:
                                controller.isLoading.value
                                    ? Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        SizedBox(
                                          width: 20,
                                          height: 20,
                                          child: CircularProgressIndicator(
                                            strokeWidth: 2.0,
                                            valueColor:
                                                AlwaysStoppedAnimation<Color>(
                                                  Theme.of(
                                                    context,
                                                  ).colorScheme.onPrimary,
                                                ),
                                          ),
                                        ),
                                        const SizedBox(width: 12),
                                        Text(
                                          'Checking Location...',
                                          style: TextStyle(
                                            color: Theme.of(context).colorScheme.onPrimary,
                                          ),
                                        ),
                                      ],
                                    )
                                    : Text(
                                      controller.isLocationValid.value
                                          ? 'Next'
                                          : 'Check Location',
                                    ),
                          ),
                        ),
                      )
                      : const SizedBox.shrink(),
            ),

            const SizedBox(height: 8),
          ],
        ),
      ),
    );
  }

  Widget _buildCarouselCard(int index, ThemeData theme) {
    final slide = controller.slides[index];

    // Fix: Removed nested Obx and directly use controller values
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
      margin: EdgeInsets.symmetric(
        horizontal: 10,
        vertical: index == controller.currentPage.value ? 10 : 30,
      ),
      decoration: BoxDecoration(
        color:
            theme.brightness == Brightness.light
                ? Colors.grey[200]
                : Colors.grey[800],
        borderRadius: BorderRadius.circular(24),
        boxShadow:
            index == controller.currentPage.value
                ? [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 10,
                    offset: const Offset(0, 5),
                  ),
                ]
                : [],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(24),
        child: SvgPicture.asset(slide['image'], fit: BoxFit.contain),
      ),
    );
  }
}
