import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../core/constants/translation_keys.dart';
import '../../../custom_widgets/custom_app_bar.dart';
import '../../../custom_widgets/custom_no_record.dart';
import '../../../res/app_colors.dart';
import '../../../res/app_dimensions.dart';
import '../controllers/contacts_screen_controller.dart';

class ContactsScreenView extends GetView<ContactsScreenController> {
  const ContactsScreenView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    String className = runtimeType.toString().split('.').last;
    return Scaffold(
      appBar: DashBoardAppBar(
        title: TranslationKeys.makeTranslation("Contacts"),
        onBackButtonPressed: () {
          Get.back();
        },
      ),
      body: Padding(
        padding: EdgeInsets.symmetric(vertical: AppDimensions.screenVerticalPadding, horizontal: AppDimensions.screenHorizontalPadding),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
                style: Theme.of(context).textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w400, fontSize: 12),
                decoration: const InputDecoration(
                  suffixIconColor: AppColors.colorPrimary,
                  filled: true,
                  fillColor: AppColors.colorGrey200,
                  enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(width: 1, color: Colors.transparent)),
                  border: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(width: 1, color: AppColors.colorGrey500)),
                  focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(width: 1, style: BorderStyle.solid, color: Colors.transparent)),
                  hintText: 'Search contact number',
                  hintStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.w400, color: AppColors.colorGrey500),
                  suffixIcon: Icon(Icons.search_rounded, size: 22),
                ),
                onChanged: (value) {
                  controller.filterContacts(value);
                }),
            const SizedBox(height: 20),
            Text(TranslationKeys.makeTranslation("Contacts"), style: Theme.of(context).textTheme.bodyMedium),
            const SizedBox(height: 10),
            Obx(() {
              return controller.filteredContacts.isEmpty
                  ? const Center(
                      child: CustomNoRecord(title: "No Record Found", description: "We couldn't find any activity at this moment"),
                    )
                  : Expanded(
                      flex: 2,
                      child: ListView.builder(
                        itemCount: controller.filteredContacts.length,
                        itemBuilder: (context, index) {
                          final contact = controller.filteredContacts[index];
                          final phoneNumber = contact.phones.isNotEmpty ? contact.phones[0].number : 'No phone number';
                          return ListTile(
                            onTap: () {
                              controller.handleContactSelection(contact);
                            },
                            title: Text(contact.displayName),
                            subtitle: Text(
                              phoneNumber,
                              style: Theme.of(context).textTheme.bodySmall,
                            ),
                            leading: CircleAvatar(
                              backgroundColor: AppColors.colorPrimary,
                              backgroundImage: contact.photo != null ? MemoryImage(contact.photo!) : null,
                              child: Text(
                                getInitials(contact.displayName),
                                style: Theme.of(context).textTheme.titleSmall?.copyWith(color: Colors.white),
                              ),
                            ),
                          );
                        },
                      ),
                    );
            }),
          ],
        ),
      ),
    );
  }

  String getInitials(String fullName) {
    if (fullName.isEmpty) {
      return "";
    }

    // Split the full name into words
    List<String> nameParts = fullName.trim().split(' ');

    // Check if there's at least a first and last name
    if (nameParts.length < 2) {
      return fullName.substring(0, 1).toUpperCase(); // Get first character
    }

    // Get first characters of first and last name
    String firstInitial = nameParts[0].substring(0, 1).toUpperCase();
    String lastInitial = nameParts[nameParts.length - 1].substring(0, 1).toUpperCase();

    return firstInitial + lastInitial;
  }
}
