import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/auth/data/models/administrative_division.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/identity-verification/location_selection_controller.dart';
import 'package:sigap/src/utils/constants/colors.dart';
import 'package:sigap/src/utils/constants/sizes.dart';

class LocationSelectionPage extends StatefulWidget {
  final DivisionType initialDivisionType;
  final String? parentId;
  final String? searchQuery;
  final List<String> breadcrumbs;

  const LocationSelectionPage({
    super.key,
    this.initialDivisionType = DivisionType.province,
    this.parentId,
    this.searchQuery,
    this.breadcrumbs = const [],
  });

  @override
  State<LocationSelectionPage> createState() => _LocationSelectionPageState();
}

class _LocationSelectionPageState extends State<LocationSelectionPage> {
  late final LocationSelectionController controller;
  bool manualInput = false;
  final TextEditingController manualController = TextEditingController();

  @override
  void initState() {
    super.initState();
    controller = Get.put(LocationSelectionController());
    // Set manual input to true by default
    manualInput = true;

    // Ensure controller is properly initialized before accessing reactive properties
    WidgetsBinding.instance.addPostFrameCallback((_) {
      controller.loadDivisions(widget.initialDivisionType, widget.parentId);
      if (widget.searchQuery != null && widget.searchQuery!.isNotEmpty) {
        controller.searchController.text = widget.searchQuery!;
        controller.updateSearch(widget.searchQuery!);
      }
    });
  }

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

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

    return Scaffold(
      appBar: _buildAppBar(context, isDark, controller),
      body:
          manualInput
              ? _buildManualInputSection()
              : _buildLocationSelectionSection(),
    );
  }

  // Modified to show manual input section with a more prominent UI
  Widget _buildManualInputSection() {
    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(TSizes.defaultSpace),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Title and toggle
            Row(
              children: [
                Expanded(
                  child: Text(
                    'Enter Place of Birth',
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                // TextButton.icon(
                //   onPressed: () {
                //     setState(() {
                //       manualInput = !manualInput;
                //     });
                //   },
                //   icon: const Icon(Icons.list),
                //   label: const Text('Select from list'),
                // ),
              ],
            ),
            const SizedBox(height: TSizes.md),
            // Instruction text
            Text(
              'Type the name of your place of birth below:',
              style: Theme.of(context).textTheme.bodyMedium,
            ),
            const SizedBox(height: TSizes.md),
            // Input field
            TextField(
              controller: manualController,
              decoration: const InputDecoration(
                labelText: 'Place of Birth',
                hintText: 'e.g., Jakarta, Bandung, Surabaya, etc.',
                border: OutlineInputBorder(),
                floatingLabelBehavior: FloatingLabelBehavior.always,
              ),
              textCapitalization: TextCapitalization.words,
              autofocus: true,
            ),
            const SizedBox(height: TSizes.lg),
            // Confirm button
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () {
                  if (manualController.text.trim().isNotEmpty) {
                    Get.back(result: manualController.text.trim());
                  }
                },
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: TSizes.md),
                ),
                child: const Text('Confirm'),
              ),
            ),
            // Helper text
            const SizedBox(height: TSizes.sm),
            Center(
              child: Text(
                'Please make sure you enter the correct place name',
                style: Theme.of(context).textTheme.bodySmall,
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLocationSelectionSection() {
    return Column(
      children: [
        // Toggle between select and manual input
        Padding(
          padding: const EdgeInsets.only(
            left: TSizes.defaultSpace,
            right: TSizes.defaultSpace,
            top: TSizes.defaultSpace,
            bottom: 0,
          ),
          child: Row(
            children: [
              Expanded(
                child: Text(
                  'Select Place of Birth',
                  style: Theme.of(context).textTheme.titleMedium,
                ),
              ),
              TextButton(
                onPressed: () {
                  setState(() {
                    manualInput = !manualInput;
                  });
                },
                child: const Text('Type manually'),
              ),
            ],
          ),
        ),
        Expanded(
          child: Column(
            children: [
              if (widget.breadcrumbs.isNotEmpty)
                _buildBreadcrumbs(context, controller),
              _buildSearchField(context, controller),
              Expanded(child: _buildListSection()),
            ],
          ),
        ),
      ],
    );
  }

  AppBar _buildAppBar(
    BuildContext context,
    bool isDark,
    LocationSelectionController controller,
  ) {
    String title;
    switch (widget.initialDivisionType) {
      case DivisionType.province:
        title = 'Select Province';
        break;
      case DivisionType.regency:
        title = 'Select Regency/City';
        break;
      case DivisionType.district:
        title = 'Select District';
        break;
      case DivisionType.village:
        title = 'Select Village';
        break;
    }

    return AppBar(
      title: Text(title),
      centerTitle: false,
      elevation: 0,
      backgroundColor: Colors.transparent,
      iconTheme: IconThemeData(color: isDark ? TColors.white : TColors.black),
      actions: [
        Obx(
          () =>
              controller.searchActive.value
                  ? IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: controller.clearSearch,
                  )
                  : const SizedBox.shrink(),
        ),
      ],
    );
  }

  Widget _buildBreadcrumbs(
    BuildContext context,
    LocationSelectionController controller,
  ) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: TSizes.defaultSpace),
      height: 40,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: widget.breadcrumbs.length,
        itemBuilder: (context, index) {
          final bool isLastItem = index == widget.breadcrumbs.length - 1;

          return Row(
            children: [
              // Breadcrumb item
              GestureDetector(
                onTap:
                    isLastItem
                        ? null
                        : () {
                          // Navigate back to this level
                          controller.navigateToBreadcrumb(
                            index,
                            widget.breadcrumbs,
                          );
                        },
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 4,
                  ),
                  decoration: BoxDecoration(
                    color:
                        isLastItem
                            ? Theme.of(context).primaryColor.withOpacity(0.2)
                            : Theme.of(context).cardColor,
                    borderRadius: BorderRadius.circular(TSizes.borderRadiusSm),
                    border: Border.all(
                      color:
                          isLastItem
                              ? Theme.of(context).primaryColor
                              : Theme.of(context).dividerColor,
                    ),
                  ),
                  child: Text(
                    widget.breadcrumbs[index],
                    style: TextStyle(
                      color:
                          isLastItem
                              ? Theme.of(context).primaryColor
                              : Theme.of(context).textTheme.bodyMedium?.color,
                      fontWeight:
                          isLastItem ? FontWeight.bold : FontWeight.normal,
                    ),
                  ),
                ),
              ),

              // Arrow separator
              if (!isLastItem)
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 4),
                  child: Icon(
                    Icons.chevron_right,
                    size: 16,
                    color: Theme.of(context).dividerColor,
                  ),
                ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildSearchField(
    BuildContext context,
    LocationSelectionController controller,
  ) {
    return Padding(
      padding: const EdgeInsets.all(TSizes.defaultSpace),
      child: TextField(
        controller: controller.searchController,
        onChanged: (value) => controller.updateSearch(value),
        decoration: InputDecoration(
          hintText: 'Search location...',
          prefixIcon: const Icon(Icons.search),
          suffixIcon: Obx(
            () =>
                controller.searchController.text.isNotEmpty
                    ? IconButton(
                      icon: const Icon(Icons.clear),
                      onPressed: controller.clearSearch,
                    )
                    : const SizedBox.shrink(),
          ),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(TSizes.borderRadiusMd),
          ),
          contentPadding: const EdgeInsets.symmetric(
            vertical: TSizes.sm,
            horizontal: TSizes.md,
          ),
          filled: true,
          fillColor: Theme.of(context).cardColor,
        ),
        textInputAction: TextInputAction.search,
      ),
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.location_city,
            size: 64,
            color: Theme.of(context).disabledColor,
          ),
          const SizedBox(height: TSizes.sm),
          Text(
            'No locations found',
            style: Theme.of(context).textTheme.bodyLarge?.copyWith(
              color: Theme.of(context).disabledColor,
            ),
          ),
        ],
      ),
    );
  }

  // Modified list section to avoid the GetX reactive issues
  Widget _buildListSection() {
    // Use a local snapshot of values to avoid reactive dependencies
    final isLoading = controller.isLoading.value;
    final divisions = List<AdministrativeDivision>.from(
      controller.filteredDivisions,
    );
    final isEmpty = divisions.isEmpty;

    if (isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (isEmpty) {
      return _buildEmptyState(context);
    }

    return ListView.builder(
      itemCount: divisions.length,
      itemBuilder: (context, index) {
        final division = divisions[index];
        // Take snapshot of reactive values before using them
        final isSearchActive = controller.searchActive.value;
        final searchQuery = controller.searchController.text;

        return ListTile(
          title:
              isSearchActive && searchQuery.isNotEmpty
                  ? RichText(
                    text: _highlightSearchText(
                      division.name,
                      searchQuery,
                      context,
                    ),
                  )
                  : Text(division.name),
          subtitle:
              isSearchActive && division.type != DivisionType.village
                  ? Text(_getSubtitleText(division))
                  : null,
          trailing:
              division.type != DivisionType.village
                  ? const Icon(Icons.chevron_right)
                  : null,
          onTap: () => _handleDivisionTap(division, controller, context),
          contentPadding: const EdgeInsets.symmetric(
            horizontal: TSizes.defaultSpace,
            vertical: TSizes.xs,
          ),
        );
      },
    );
  }

  TextSpan _highlightSearchText(
    String text,
    String query,
    BuildContext context,
  ) {
    final lowercaseText = text.toLowerCase();
    final lowercaseQuery = query.toLowerCase();

    if (lowercaseQuery.isEmpty || !lowercaseText.contains(lowercaseQuery)) {
      return TextSpan(text: text);
    }

    final int startIndex = lowercaseText.indexOf(lowercaseQuery);
    final int endIndex = startIndex + lowercaseQuery.length;

    return TextSpan(
      children: [
        TextSpan(text: text.substring(0, startIndex)),
        TextSpan(
          text: text.substring(startIndex, endIndex),
          style: TextStyle(
            backgroundColor: Theme.of(
              context,
            ).colorScheme.secondary.withOpacity(0.2),
            fontWeight: FontWeight.bold,
            color: Theme.of(context).colorScheme.secondary,
          ),
        ),
        TextSpan(text: text.substring(endIndex)),
      ],
    );
  }

  String _getSubtitleText(AdministrativeDivision division) {
    switch (division.type) {
      case DivisionType.province:
        return 'Province';
      case DivisionType.regency:
        return 'Regency/City';
      case DivisionType.district:
        return 'District';
      case DivisionType.village:
        return 'Village';
    }
  }

  void _handleDivisionTap(
    AdministrativeDivision division,
    LocationSelectionController controller,
    BuildContext context,
  ) async {
    try {
      // Move the reactive check to a local variable before use
      final isSearchActive = controller.searchActive.value;

      // If it's a search result, return the full breadcrumb path
      if (isSearchActive) {
        final fullLocation = await controller.getFullLocationString(division);
        Get.back(result: fullLocation);
        return;
      }

      // If it's a village (lowest level), return the selection
      if (division.type == DivisionType.village) {
        final fullLocation = await controller.getFullLocationString(division);
        Get.back(result: fullLocation);
        return;
      }

      // Otherwise navigate to the next level
      final nextDivisionType = _getNextDivisionType(division.type);
      final updatedBreadcrumbs = [...widget.breadcrumbs, division.name];

      Get.to(
        () => LocationSelectionPage(
          initialDivisionType: nextDivisionType,
          parentId: division.id,
          breadcrumbs: updatedBreadcrumbs,
        ),
      );
    } catch (e) {
      // Handle any errors that might occur during navigation
      print("Error handling division tap: $e");
    }
  }

  DivisionType _getNextDivisionType(DivisionType currentType) {
    switch (currentType) {
      case DivisionType.province:
        return DivisionType.regency;
      case DivisionType.regency:
        return DivisionType.district;
      case DivisionType.district:
        return DivisionType.village;
      default:
        return DivisionType.village; // Should not reach here
    }
  }
}
