import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/screen/traffic_service/traffic_service_certificate_screen.dart';
import 'package:mypoint_flutter_app/screen/traffic_service/traffic_service_model.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:url_launcher/url_launcher.dart';
import '../../resources/base_color.dart';
import '../../widgets/custom_navigation_bar.dart';

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

  @override
  State<TrafficServiceDetailScreen> createState() => _TrafficServiceDetailScreenState();
}

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

  @override
  void initState() {
    super.initState();
    int? serviceId;
    TrafficServiceDetailModel? data;
    final args = Get.arguments;
    if (args is Map) {
      serviceId = args['serviceId'];
      data = args['data'];
    }
    if (serviceId == null && data == null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Get.back();
      });
      return;
    }
    _viewModel.trafficServiceDetail.value = data;
    if (serviceId != null) {
      _viewModel.getTrafficServiceDetail(serviceId.toString());
    }
    // _viewModel.onShowAlertError = (message) {
    //   if (message.isNotEmpty) {
    //     showAlertError(content: message);
    //   }
    // };
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomNavigationBar(title: "Thông tin chi tiết"),
      body: Obx(() {
        final model = _viewModel.trafficServiceDetail.value;
        if (model == null) {
          return const Center(child: EmptyWidget());
        }
        return Column(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _sectionTitle("Thông tin xe"),
                  _rowItem("Biển số xe", model.licensePlate ?? ''),
                  const Divider(color: Colors.black12),
                  _sectionTitle("Thông tin chủ xe"),
                  _rowItem("Họ và tên", model.ownerName ?? ''),
                  _rowItem("Số điện thoại", model.phoneNumber ?? ''),
                  const Divider(color: Colors.black12),
                  _sectionTitle("Thông tin gói dịch vụ"),
                  _rowItem("Tên gói", model.packageName ?? ''),
                  _rowItem("Hiệu lực gói dịch vụ", model.dateDes),
                  GestureDetector(
                    onTap: () async {
                      final Uri phoneUri = Uri(scheme: 'tel', path: model.hotline);
                      if (await canLaunchUrl(phoneUri)) {
                        await launchUrl(phoneUri);
                      }
                    },
                    child: _rowItem("SĐT cứu hộ", model.hotline ?? '', color: Colors.red, icon: Icons.phone),
                  ),
                  const Divider(color: Colors.black12),
                ],
              ),
            ),
          ],
        );
      }),
      bottomNavigationBar: _buildBottomButtonEditMode(),
    );
  }

  Widget _sectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Text(title, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
    );
  }

  Widget _rowItem(String label, String value, {Color? color, IconData? icon}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          Expanded(child: Text(label, style: const TextStyle(color: Colors.black54, fontSize: 14))),
          if (icon != null) Icon(icon, color: color ?? Colors.black),
          const SizedBox(width: 4),
          Text(value, style: TextStyle(color: color ?? Colors.black87, fontSize: 14)),
        ],
      ),
    );
  }

  Widget _buildBottomButtonEditMode() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
      decoration: const BoxDecoration(
        color: Colors.white,
        boxShadow: [BoxShadow(color: Colors.black54, blurRadius: 8, offset: Offset(0, 4))],
      ),
      child: SafeArea(
        top: false,
        child: SizedBox(
          width: double.infinity,
          height: 48,
          child: ElevatedButton(
            onPressed: () {
              Get.to(TrafficServiceCertificateScreen(
                urlView: _viewModel.trafficServiceDetail.value?.urlView ?? '',
                urlDownload: _viewModel.trafficServiceDetail.value?.urlDownload ?? '',
                licensePlate: _viewModel.trafficServiceDetail.value?.licensePlate ?? '',
              ));
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: BaseColor.primary500,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
            ),
            child: const Text(
              'Xem giấy chứng nhận',
              style: TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),
            ),
          ),
        ),
      ),
    );
  }
}
