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

import '../../../constant/box_name.dart';
import '../../../main.dart';
import '../../widgets/my_scafold.dart';
import '../../widgets/mycircular.dart';
import '../../../controller/admin/captain_admin_controller.dart';
import 'captain_details.dart';

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

  final CaptainAdminController captainController =
      Get.put(CaptainAdminController());
  final TextEditingController searchController = TextEditingController();

  String myPhone = box.read(BoxName.adminPhone).toString();
  bool isSuperAdmin = false;

  @override
  Widget build(BuildContext context) {
    isSuperAdmin = myPhone == '963942542053' || myPhone == '963992952235';

    return MyScafolld(
      title: 'Search for Captain'.tr,
      isleading: true,
      body: [
        Container(
          height: MediaQuery.of(context).size.height,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Theme.of(context).primaryColor.withOpacity(0.03),
                Colors.white,
              ],
            ),
          ),
          child: Column(
            children: [
              _buildHeaderSection(context),
              Expanded(
                child: GetBuilder<CaptainAdminController>(
                  builder: (controller) {
                    if (controller.isLoading) {
                      return _buildLoadingState();
                    }

                    final message = controller.captainData['message'];

                    if (message == null) {
                      return _buildEmptyState();
                    }

                    // 🔥 الحل هنا: توحيد الشكل إلى List
                    final List<dynamic> captains =
                        message is List ? message : [message];

                    if (captains.isEmpty) {
                      return _buildEmptyState();
                    }

                    return _buildResultsList(context, captains);
                  },
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // ================= HEADER =================

  Widget _buildHeaderSection(BuildContext context) {
    return Container(
      padding: const EdgeInsets.fromLTRB(20, 20, 20, 16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.04),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Theme.of(context).primaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(
                  Icons.manage_search_rounded,
                  color: Theme.of(context).primaryColor,
                  size: 24,
                ),
              ),
              const SizedBox(width: 12),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Find Captain'.tr,
                    style: const TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      color: Colors.black87,
                    ),
                  ),
                  Text(
                    'Search by phone number'.tr,
                    style: TextStyle(
                      fontSize: 13,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 20),
          _buildModernSearchBar(context),
        ],
      ),
    );
  }

  Widget _buildModernSearchBar(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: searchController,
              keyboardType: TextInputType.phone,
              style: const TextStyle(fontSize: 15),
              decoration: InputDecoration(
                hintText: '0990000000'.tr,
                hintStyle: TextStyle(color: Colors.grey[400], fontSize: 14),
                prefixIcon: Icon(Icons.phone_android_rounded,
                    color: Colors.grey[400], size: 22),
                border: InputBorder.none,
                contentPadding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
              ),
              onSubmitted: (_) => _performSearch(),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(6.0),
            child: Material(
              color: Theme.of(context).primaryColor,
              borderRadius: BorderRadius.circular(12),
              child: InkWell(
                onTap: _performSearch,
                borderRadius: BorderRadius.circular(12),
                child: const Padding(
                  padding: EdgeInsets.all(12),
                  child: Icon(Icons.search, color: Colors.white, size: 24),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _performSearch() {
    final phone = searchController.text.trim();
    if (phone.isNotEmpty) {
      captainController.find_driver_by_phone(phone);
    }
  }

  // ================= RESULTS =================

  Widget _buildResultsList(BuildContext context, List<dynamic> captains) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(20, 20, 20, 12),
          child: Row(
            children: [
              Text(
                'Search Results'.tr,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
              const SizedBox(width: 8),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: Theme.of(context).primaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  '${captains.length}',
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.bold,
                    color: Theme.of(context).primaryColor,
                  ),
                ),
              ),
            ],
          ),
        ),
        Expanded(
          child: ListView.separated(
            physics: const BouncingScrollPhysics(),
            padding: const EdgeInsets.fromLTRB(20, 0, 20, 80),
            itemCount: captains.length,
            separatorBuilder: (_, __) => const SizedBox(height: 12),
            itemBuilder: (context, index) {
              final captain = captains[index] as Map<String, dynamic>;
              return _buildModernCaptainCard(context, captain);
            },
          ),
        ),
      ],
    );
  }

  // ================= CARD =================

  Widget _buildModernCaptainCard(
      BuildContext context, Map<String, dynamic> captain) {
    final String fullName =
        '${captain['first_name'] ?? ''} ${captain['last_name'] ?? ''}';
    final String phone = captain['phone']?.toString() ?? '';
    final String? email = captain['email']?.toString();

    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.04),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(20),
          onTap: () {
            Get.to(() => const CaptainDetailsPage(),
                arguments: {'data': captain});
          },
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              children: [
                Container(
                  width: 56,
                  height: 56,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        Theme.of(context).primaryColor.withOpacity(0.8),
                        Theme.of(context).primaryColor,
                      ],
                    ),
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: const Icon(
                    Icons.person_rounded,
                    color: Colors.white,
                    size: 28,
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        fullName,
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      const SizedBox(height: 6),
                      Text(phone),
                      if (isSuperAdmin && email != null) ...[
                        const SizedBox(height: 4),
                        Text(email),
                      ],
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // ================= STATES =================

  Widget _buildLoadingState() {
    return const Center(child: MyCircularProgressIndicator());
  }

  Widget _buildEmptyState() {
    return const Center(
      child: Text("No captains found"),
    );
  }
}
