import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../controller/admin/quality_controller.dart';

class BlacklistPage extends StatelessWidget {
  const BlacklistPage({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(QualityController()).fetchBlacklist();

    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('إدارة القائمة السوداء (Blacklist)',
              style: TextStyle(fontWeight: FontWeight.bold)),
          backgroundColor: Colors.red[800],
          bottom: const TabBar(
            indicatorColor: Colors.white,
            tabs: [
              Tab(icon: Icon(Icons.drive_eta), text: 'السائقين المحظورين'),
              Tab(icon: Icon(Icons.person), text: 'الركاب المحظورين'),
            ],
          ),
        ),
        body: GetBuilder<QualityController>(
          builder: (controller) {
            if (controller.isLoading) {
              return const Center(child: CircularProgressIndicator());
            }

            return TabBarView(
              children: [
                _buildDriverList(controller),
                _buildPassengerList(controller),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildDriverList(QualityController controller) {
    if (controller.driversBlacklist.isEmpty) {
      return const Center(child: Text('لا يوجد سائقين محظورين حالياً'));
    }
    return ListView.builder(
      itemCount: controller.driversBlacklist.length,
      padding: const EdgeInsets.all(12),
      itemBuilder: (context, index) {
        var driver = controller.driversBlacklist[index];
        return Card(
          elevation: 3,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          child: ListTile(
            leading: const CircleAvatar(
              backgroundColor: Colors.redAccent,
              child: Icon(Icons.block, color: Colors.white),
            ),
            title: Text('هاتف: ${driver['phone']}',
                style: const TextStyle(fontWeight: FontWeight.bold)),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('السبب: ${driver['reason'] ?? "غير محدد"}'),
                Text('تاريخ الحظر: ${driver['created_at']}'),
              ],
            ),
            trailing: IconButton(
              icon: const Icon(Icons.settings_backup_restore,
                  color: Colors.green),
              onPressed: () {
                _showUnblockDialog(
                  Get.context!,
                  'سائق',
                  driver['phone'],
                  () => controller.unblockDriver(driver['phone'].toString()),
                );
              },
            ),
          ),
        );
      },
    );
  }

  Widget _buildPassengerList(QualityController controller) {
    if (controller.passengersBlacklist.isEmpty) {
      return const Center(child: Text('لا يوجد ركاب محظورين حالياً'));
    }
    return ListView.builder(
      itemCount: controller.passengersBlacklist.length,
      padding: const EdgeInsets.all(12),
      itemBuilder: (context, index) {
        var passenger = controller.passengersBlacklist[index];
        return Card(
          elevation: 3,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          child: ListTile(
            leading: const CircleAvatar(
              backgroundColor: Colors.orangeAccent,
              child: Icon(Icons.person_off, color: Colors.white),
            ),
            title: Text(
                'هاتف: ${passenger['phone'] ?? passenger['phone_normalized']}',
                style: const TextStyle(fontWeight: FontWeight.bold)),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('السبب: ${passenger['reason'] ?? "غير محدد"}'),
                Text('تاريخ الحظر: ${passenger['created_at']}'),
              ],
            ),
            trailing: IconButton(
              icon: const Icon(Icons.settings_backup_restore,
                  color: Colors.green),
              onPressed: () {
                _showUnblockDialog(
                  Get.context!,
                  'راكب',
                  passenger['phone_normalized'],
                  () => controller.unblockPassenger(
                      passenger['phone_normalized'].toString()),
                );
              },
            ),
          ),
        );
      },
    );
  }

  void _showUnblockDialog(BuildContext context, String type, String identifier,
      VoidCallback onConfirm) {
    Get.defaultDialog(
      title: "تأكيد فك الحظر",
      middleText:
          "هل أنت متأكد من فك الحظر عن هذا ال$type ($identifier)؟\nسيتم تسجيل هذه العملية في الـ Audit Log.",
      textConfirm: "نعم، فك الحظر",
      textCancel: "تراجع",
      confirmTextColor: Colors.white,
      buttonColor: Colors.green,
      onConfirm: () {
        Get.back();
        onConfirm();
      },
    );
  }
}
