import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/extensions/datetime_extensions.dart';
import 'package:mypoint_flutter_app/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/screen/traffic_service/traffic_service_detail_screen.dart';
import 'package:mypoint_flutter_app/screen/traffic_service/traffic_service_viewmodel.dart';
import 'package:mypoint_flutter_app/widgets/custom_empty_widget.dart';
import 'package:mypoint_flutter_app/widgets/image_loader.dart';
import '../../extensions/date_format.dart';
import '../../resources/base_color.dart';
import '../../shared/router_gage.dart';
import '../../widgets/custom_navigation_bar.dart';

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

  @override
  State<TrafficServiceScreen> createState() => _TrafficServiceScreenState();
}

class _TrafficServiceScreenState extends State<TrafficServiceScreen> {
  final TrafficServiceViewModel _viewModel = Get.put(TrafficServiceViewModel());

  @override
  void initState() {
    super.initState();
    _viewModel.getTrafficServiceData();
  }

  @override
  Widget build(BuildContext context) {
    final tags = _viewModel.headerFilterOrder;

    return Scaffold(
      appBar: CustomNavigationBar(title: "Dịch vụ giao thông"),
      body: Column(
        children: [
          const SizedBox(height: 8),
          Obx(()
            => Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: List.generate(tags.length, (index) {
                final isSelected = index == _viewModel.selectedIndex.value;
                return GestureDetector(
                  onTap: () {
                    if (_viewModel.selectedIndex.value == index) return;
                    setState(() {
                      _viewModel.selectedIndex.value = index;
                      _viewModel.getTrafficServiceData();
                    });
                  },
                  child: Container(
                    margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                    decoration: BoxDecoration(
                      border: Border.all(color: isSelected ? BaseColor.primary500 : Colors.grey.shade300),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      tags[index].title,
                      style: TextStyle(color: isSelected ? BaseColor.primary500 : Colors.black87),
                    ),
                  ),
                );
              }),
            ),
          ),
          const Divider(height: 14, color: Colors.black12),
          const SizedBox(height: 8),
          Expanded(
            child: Obx(() {
              final products = _viewModel.trafficData.value?.products ?? [];
              return products.isEmpty
                  ? Center(child: EmptyWidget())
                  : ListView.builder(
                    itemCount: products.length,
                    itemBuilder: (context, index) {
                      final item = products[index];
                      return Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                        child: Container(
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey.shade300),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: ListTile(
                            onTap: () {
                              print('Tapped on item: ${item.licensePlate}');
                              Get.toNamed(trafficServiceDetailScreen, arguments: {'serviceId': item.itemId});
                            },
                            leading: SizedBox(
                              width: 60, // <= giới hạn rõ
                              height: 60,
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(8),
                                child: loadNetworkImage(
                                  url: item.media?.firstOrNull?.url ?? '',
                                  fit: BoxFit.cover,
                                  placeholderAsset: 'assets/images/bg_default_11.png',
                                ),
                              ),
                            ),
                            title: Text(item.licensePlate ?? '', style: TextStyle(fontWeight: FontWeight.bold)),
                            subtitle: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const SizedBox(height: 4),
                                Text(
                                  item.packageName ?? '',
                                  style: const TextStyle(
                                    fontSize: 14,
                                    color: Colors.black87,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                                const SizedBox(height: 4),
                                Text(
                                  (item.endTime ?? '').toDate()?.toFormattedString() ?? '',
                                  style: const TextStyle(
                                    fontSize: 14,
                                    color: Colors.black87,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                                const SizedBox(height: 4),
                                Text(
                                  'Cập nhật lúc ${(item.updatedAt ?? '').toDate()?.toFormattedString(format: DateFormat.ddMMyyyyhhmm) ?? ''}',
                                  style: const TextStyle(fontSize: 11, color: Colors.black54),
                                ),
                              ],
                            ),
                            trailing: Container(
                              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                              decoration: BoxDecoration(
                                color: Colors.green.shade50,
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Text(
                                item.active?.text ?? '',
                                style: const TextStyle(fontSize: 12, color: Colors.green, fontWeight: FontWeight.w500),
                              ),
                            ),
                          ),
                        ),
                      );
                    },
                  );
            }),
          ),
        ],
      ),
    );
  }
}
