import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/resources/base_color.dart';
import '../../widgets/custom_navigation_bar.dart';
import 'location_address_viewmodel.dart';

enum LocationAddressType {
  province,
  district;

  static LocationAddressType? fromString(String? value) {
    if (value == null) return null;
    return values.cast<LocationAddressType?>().firstWhere(
          (e) => e?.key == value,
      orElse: () => null,
    );
  }

  String get key {
    switch (this) {
      case LocationAddressType.province:
        return 'province';
      case LocationAddressType.district:
        return 'district';
    }
  }
}

class LocationAddressScreen extends StatefulWidget {
  const LocationAddressScreen({super.key});

  @override
  State<LocationAddressScreen> createState() => _LocationAddressScreenState();
}

class _LocationAddressScreenState extends State<LocationAddressScreen> {
  late final LocationAddressViewModel viewModel;
  final ScrollController scrollController = ScrollController();
  var _title = "Địa chỉ";

  @override
  void initState() {
    super.initState();
    final args = Get.arguments ?? {};
    var typeRaw = args['type'] as String?;
    var selectedCode = args['selectedCode'] as String? ?? '';
    var type = LocationAddressType.fromString(typeRaw) ?? LocationAddressType.province;
    viewModel = Get.put(LocationAddressViewModel(
      type: type,
      provinceCode: args['provinceCode'] ?? '',
    ));
    _title = type == LocationAddressType.province ? "Chọn Tỉnh/Thành phố" : "Chọn Quận/Huyện";
    viewModel.selectedCode.value = selectedCode;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomNavigationBar(title: _title),
      body: SafeArea(
        child: Column(
          children: [
            Container(
              margin: const EdgeInsets.all(8),
              padding: const EdgeInsets.all(4),
              decoration: BoxDecoration(
                color: Colors.grey.shade200,
                borderRadius: const BorderRadius.all(Radius.circular(16)),
              ),
              child: TextField(
                decoration: const InputDecoration(
                  hintText: "Tìm kiếm",
                  prefixIcon: Icon(Icons.search_outlined),
                  border: InputBorder.none,
                ),
                onChanged: (value) {
                  viewModel.search(value);
                },
              ),
            ),
            const Divider(height: 1),
            Expanded(
              child: Obx(() {
                final items = viewModel.displayItems;
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  final index = items.indexWhere((e) => e.code == viewModel.selectedCode.value);
                  if (index != -1 && scrollController.hasClients) {
                    scrollController.animateTo(
                      index * 48.0, // chiều cao mỗi item
                      duration: const Duration(milliseconds: 300),
                      curve: Curves.easeInOut,
                    );
                  }
                });
                return ListView.separated(
                  controller: scrollController,
                  itemCount: items.length,
                  separatorBuilder: (_, __) => const Divider(height: 1),
                  itemBuilder: (context, index) {
                    final item = items[index];
                    final isSelected = viewModel.selectedCode.value == item.code;
                    return ListTile(
                      title: Text(item.name ?? '', style: TextStyle(color: isSelected ? BaseColor.primary500 : Colors.black87)),
                      trailing: isSelected ? const Icon(Icons.check, color: BaseColor.primary500) : null,
                      onTap: () => viewModel.select(item),
                    );
                  },
                );
              }),
            ),
          ],
        ),
      ),
    );
  }
}
