import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../main_controller.dart';

class DriverPage extends StatelessWidget {
  DriverPage({super.key});

  final MainController mainController = Get.find<MainController>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GetBuilder<MainController>(builder: (mainController) {
        Map data = mainController.driverData['message'][0];

        return CupertinoPageScaffold(
          navigationBar: CupertinoNavigationBar(
            middle: Text('${data['first_name']} ${data['last_name']}'),
          ),
          child: SafeArea(
            child: CupertinoScrollbar(
              child: ListView(
                children: [
                  _buildDriverInfoSection(data),
                  _buildCommunicationSection(data, context),
                  _buildStatisticsSection(data),
                  _buildCarInfoSection(data),
                  _buildLicenseInfoSection(data),
                  _buildBankInfoSection(data),
                  const SizedBox(height: 40),
                ],
              ),
            ),
          ),
        );
      }),
    );
  }

  // ============================================================
  // REUSABLE EDIT ROW
  // ============================================================
  Widget _buildEditableRow(String label, String key, Map data) {
    return CupertinoListTile(
      title: Text(label),
      trailing: Text(
        data[key].toString(),
        style: const TextStyle(color: CupertinoColors.systemGrey),
      ),
      onTap: () => _openEditSheet(label, key, data[key]),
    );
  }

  void _openEditSheet(String label, String key, dynamic value) {
    final TextEditingController controller =
        TextEditingController(text: value.toString());

    Get.bottomSheet(
      CupertinoPageScaffold(
        navigationBar: CupertinoNavigationBar(
          middle: Text("Edit $label"),
          trailing: GestureDetector(
            child: const Text(
              "Save",
              style: TextStyle(color: CupertinoColors.activeBlue),
            ),
            onTap: () {
              mainController.updateDriverField(key, controller.text);
              Get.back();
            },
          ),
        ),
        child: SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: CupertinoTextField(
              controller: controller,
              autofocus: true,
            ),
          ),
        ),
      ),
    );
  }

  // ============================================================
  // SECTIONS
  // ============================================================

  Widget _buildDriverInfoSection(Map data) {
    return CupertinoListSection.insetGrouped(
      header: Text('Driver Information'.tr),
      children: [
        _buildEditableRow('Name Arabic'.tr, 'name_arabic', data),
        // _buildEditableRow('Name English'.tr, 'name_english', data),
        _buildEditableRow('Phone'.tr, 'phone', data),
        _buildEditableRow('Email'.tr, 'email', data),
        _buildEditableRow('Gender'.tr, 'gender', data),
        _buildEditableRow('Birthdate'.tr, 'birthdate', data),
        _buildEditableRow('National Number'.tr, 'national_number', data),
        // _buildEditableRow('Religion'.tr, 'religion', data),
        // _buildEditableRow('Occupation'.tr, 'occupation', data),
        // _buildEditableRow('Education'.tr, 'education', data),
      ],
    );
  }

  Widget _buildStatisticsSection(Map data) {
    return CupertinoListSection.insetGrouped(
      header: Text('Driver Statistics'.tr),
      children: [
        _buildInfoRow('Total Rides'.tr, data['countRide'].toString()),
        _buildInfoRow('Average Rating'.tr, data['rating'].toString()),
        _buildInfoRow('Total Payments'.tr, data['totalPayment'].toString()),
        _buildInfoRow(
            'Wallet Balance'.tr, data['totalDriverWallet'].toString()),
        _buildInfoRow('Complaints'.tr, data['countComplaint'].toString()),
        _buildInfoRow('Scam Reports'.tr, data['countScam'].toString()),
        _buildInfoRow(
            'Passengers Rated'.tr, data['DRatingPassengersCount'].toString()),
        _buildInfoRow(
            'Avg Passenger Rating'.tr, data['avgDRatingPassenger'].toString()),
      ],
    );
  }

// Read-only row widget
  Widget _buildInfoRow(String label, String value) {
    return CupertinoListTile(
      title: Text(label),
      trailing: Text(
        value,
        style: const TextStyle(color: CupertinoColors.systemGrey),
      ),
    );
  }

  Widget _buildCarInfoSection(Map data) {
    return CupertinoListSection.insetGrouped(
      header: Text('Vehicle Information'.tr),
      children: [
        // _buildEditableRow('VIN'.tr, 'vin', data),
        _buildEditableRow('Plate Number'.tr, 'car_plate', data),
        _buildEditableRow('Make'.tr, 'make', data),
        _buildEditableRow('Model'.tr, 'model', data),
        _buildEditableRow('Year'.tr, 'year', data),
        _buildEditableRow('Color'.tr, 'color', data),
        _buildEditableRow('Fuel Type'.tr, 'fuel', data),
        // _buildEditableRow('Displacement'.tr, 'displacement', data),
        _buildEditableRow('Registration Date'.tr, 'registration_date', data),
        _buildEditableRow('Expiration Date'.tr, 'expiration_date', data),
      ],
    );
  }

  Widget _buildLicenseInfoSection(Map data) {
    return CupertinoListSection.insetGrouped(
      header: Text('License Information'.tr),
      children: [
        _buildEditableRow('License Type'.tr, 'license_type', data),
        _buildEditableRow('Card ID'.tr, 'card_id', data),
        _buildEditableRow('Issue Date'.tr, 'issue_date', data),
        _buildEditableRow('Expiry Date'.tr, 'expiry_date', data),
        _buildEditableRow('Categories'.tr, 'license_categories', data),
      ],
    );
  }

  Widget _buildBankInfoSection(Map data) {
    return CupertinoListSection.insetGrouped(
      header: Text('Bank Information'.tr),
      children: [
        _buildEditableRow('Account Number'.tr, 'accountBank', data),
        _buildEditableRow('Bank Code'.tr, 'bankCode', data),
      ],
    );
  }

  Widget _buildCommunicationSection(Map data, BuildContext context) {
    String phone = data['phone'] ?? '';
    String name = data['first_name'] ?? '';

    return CupertinoListSection.insetGrouped(
      header: Text('Quick Communication'.tr),
      children: [
        CupertinoListTile(
          title: Text('Call Driver'.tr),
          leading: const Icon(CupertinoIcons.phone_fill, color: Colors.green),
          onTap: () => mainController.makePhoneCall(phone),
        ),
        CupertinoListTile(
          title: Text('WhatsApp: Activation'.tr),
          leading: const Icon(Icons.send, color: Colors.green),
          onTap: () => mainController.launchCommunication(
            'whatsapp',
            phone,
            'أهلاً بك يا كابتن $name في سيرو! تم تفعيل حسابك بنجاح وأصبحت مستعداً لاستقبال الرحلات.',
          ),
        ),
        CupertinoListTile(
          title: Text('WhatsApp: Missing Docs'.tr),
          leading: const Icon(Icons.send, color: Colors.orange),
          onTap: () => mainController.launchCommunication(
            'whatsapp',
            phone,
            'مرحباً كابتن $name، يرجى تزويدنا بالأوراق الناقصة أو غير الواضحة عبر الواتساب لإكمال تفعيل حسابك.',
          ),
        ),
        CupertinoListTile(
          title: Text('WhatsApp: Support'.tr),
          leading: const Icon(Icons.send, color: Colors.blue),
          onTap: () => mainController.launchCommunication(
            'whatsapp',
            phone,
            'مرحباً كابتن $name، معك الدعم الفني من شركة سيرو. كيف يمكنني مساعدتك اليوم؟',
          ),
        ),

      ],
    );
  }
}


