import 'package:flutter/material.dart';
import '../../../domain/services/obfuscate_service.dart';
import '../contacts/contact_page.dart';
import '../favorites/favorites_page.dart';
import '../history/history_page.dart';
import '../composition/composition.dart';
import '../settings/settings.dart';
import '../voicemail/voicemail_page.dart';
import '../contacts/widgets/contact_modal.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:dialer/domain/services/contact_service.dart';

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  List<Contact> _allContacts = [];
  List<Contact> _contactSuggestions = [];
  final ContactService _contactService = ContactService();
  final ObfuscateService _obfuscateService = ObfuscateService();
  final TextEditingController _searchController = TextEditingController();
  late SearchController _searchBarController;
  String _rawSearchInput = '';
  final GlobalKey<HistoryPageState> _historyPageKey = GlobalKey<HistoryPageState>();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this, initialIndex: 2);
    _tabController.addListener(_handleTabIndex);
    _searchBarController = SearchController();
    _searchBarController.addListener(() {
      if (_searchController.text != _searchBarController.text) {
        _rawSearchInput = _searchBarController.text;
        _searchController.text = _rawSearchInput;
        _onSearchChanged(_searchBarController.text);
      }
    });
    _fetchContacts();
  }

  void _fetchContacts() async {
    _allContacts = await _contactService.fetchContacts();
    _contactSuggestions = List.from(_allContacts);
    if (mounted) setState(() {});
  }

  void _clearSearch() {
    _searchController.clear();
    _searchBarController.clear();
    _rawSearchInput = '';
    _onSearchChanged('');
  }

  void _onSearchChanged(String query) {
    setState(() {
      if (query.isEmpty) {
        _contactSuggestions = List.from(_allContacts);
      } else {
        final normalizedQuery = _normalizeString(query.toLowerCase());
        _contactSuggestions = _allContacts.where((contact) {
          final normalizedName = _normalizeString(contact.displayName.toLowerCase());
          return normalizedName.contains(normalizedQuery);
        }).toList();
      }
    });
  }

  String _normalizeString(String input) {
    const accentMap = {
      'àáâãäå': 'a',
      'èéêë': 'e',
      'ìíîï': 'i',
      'òóôõö': 'o',
      'ùúûü': 'u',
      'ç': 'c',
      'ñ': 'n',
    };
    String normalized = input;
    accentMap.forEach((accents, base) {
      for (var accent in accents.split('')) {
        normalized = normalized.replaceAll(accent, base);
      }
    });
    return normalized;
  }

  @override
  void dispose() {
    _searchController.dispose();
    _searchBarController.dispose();
    _tabController.removeListener(_handleTabIndex);
    _tabController.dispose();
    super.dispose();
  }

  void _handleTabIndex() {
    setState(() {});
    // Trigger history page reload when switching to history tab (index 1)
    if (_tabController.index == 1) {
      _historyPageKey.currentState?.triggerReload();
    }
  }

  void _toggleFavorite(Contact contact) async {
    try {
      if (await FlutterContacts.requestPermission()) {
        Contact? fullContact = await FlutterContacts.getContact(
          contact.id,
          withProperties: true,
          withAccounts: true,
          withPhoto: true,
          withThumbnail: true,
        );

        if (fullContact != null) {
          fullContact.isStarred = !fullContact.isStarred;
          await FlutterContacts.updateContact(fullContact);
          _fetchContacts();
        }
      } else {
        print("Could not fetch contact details");
      }
    } catch (e) {
      print("Error updating favorite status: $e");
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to update contact favorite status')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(
              top: 24.0,
              bottom: 10.0,
              left: 16.0,
              right: 16.0,
            ),
            child: Row(
              children: [
                Expanded(
                  child: Container(
                    decoration: BoxDecoration(
                      color: const Color.fromARGB(255, 30, 30, 30),
                      borderRadius: BorderRadius.circular(12.0),
                      border: Border.all(color: Colors.grey.shade800, width: 1),
                    ),
                    child: SearchAnchor(
                      searchController: _searchBarController,
                      builder: (BuildContext context, SearchController controller) {
                        return GestureDetector(
                          onTap: () {
                            controller.openView();
                          },
                          child: Container(
                            decoration: BoxDecoration(
                              color: const Color.fromARGB(255, 30, 30, 30),
                              borderRadius: BorderRadius.circular(12.0),
                              border: Border.all(color: Colors.grey.shade800, width: 1),
                            ),
                            padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
                            child: Row(
                              children: [
                                const Icon(Icons.search, color: Colors.grey, size: 24.0),
                                const SizedBox(width: 8.0),
                                Expanded(
                                  child: Text(
                                    _rawSearchInput.isEmpty
                                        ? 'Search contacts'
                                        : _rawSearchInput,
                                    style: const TextStyle(color: Colors.grey, fontSize: 16.0),
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                if (_rawSearchInput.isNotEmpty)
                                  GestureDetector(
                                    onTap: _clearSearch,
                                    child: const Icon(
                                      Icons.clear,
                                      color: Colors.grey,
                                      size: 24.0,
                                    ),
                                  ),
                              ],
                            ),
                          ),
                        );
                      },
                      viewOnChanged: (query) {

                        if (_searchBarController.text != query) {
                          _rawSearchInput = query;
                          _searchBarController.text = query;
                          _searchController.text = query;
                        }
                        _onSearchChanged(query);
                      },
                      suggestionsBuilder: (BuildContext context, SearchController controller) {
                        return _contactSuggestions.map((contact) {
                          return ListTile(
                            key: ValueKey(contact.id),
                            title: Text(
                              _obfuscateService.obfuscateData(contact.displayName),
                              style: const TextStyle(color: Colors.white),
                            ),
                            onTap: () {
                              controller.closeView(contact.displayName);
                              showModalBottomSheet(
                                context: context,
                                isScrollControlled: true,
                                backgroundColor: Colors.transparent,
                                builder: (context) {
                                  return ContactModal(
                                    contact: contact,
                                    onEdit: () async {
                                      if (await FlutterContacts.requestPermission()) {
                                        final updatedContact = await FlutterContacts
                                            .openExternalEdit(contact.id);
                                        if (updatedContact != null) {
                                          _fetchContacts();
                                          Navigator.of(context).pop();
                                          ScaffoldMessenger.of(context).showSnackBar(
                                            SnackBar(
                                              content: Text(
                                                  '${contact.displayName} updated successfully!'),
                                            ),
                                          );
                                        } else {
                                          ScaffoldMessenger.of(context).showSnackBar(
                                            SnackBar(
                                              content: Text('Edit canceled or failed.'),
                                            ),
                                          );
                                        }
                                      }
                                    },
                                    onToggleFavorite: () => _toggleFavorite(contact),
                                    isFavorite: contact.isStarred,
                                  );
                                },
                              );
                            },
                          );
                        }).toList();
                      },
                    ),
                  ),
                ),
                PopupMenuButton<String>(
                  icon: const Icon(Icons.more_vert, color: Colors.white),
                  itemBuilder: (BuildContext context) => [
                    const PopupMenuItem<String>(
                      value: 'settings',
                      child: Text('Settings'),
                    ),
                  ],
                  onSelected: (String value) {
                    if (value == 'settings') {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => const SettingsPage()),
                      );
                    }
                  },
                ),
              ],
            ),
          ),
          Expanded(
            child: Stack(
              children: [
                TabBarView(
                  controller: _tabController,
                  children: [
                    const FavoritesPage(),
                    HistoryPage(key: _historyPageKey),
                    const ContactPage(),
                    const VoicemailPage(),
                  ],
                ),
                Positioned(
                  right: 20,
                  bottom: 20,
                  child: FloatingActionButton(
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const CompositionPage(),
                        ),
                      );
                    },
                    backgroundColor: Colors.blue,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(45),
                    ),
                    child: const Icon(Icons.dialpad, color: Colors.white),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
      bottomNavigationBar: Container(
        color: Colors.black,
        child: TabBar(
          controller: _tabController,
          tabs: [
            Tab(
                icon: Icon(_tabController.index == 0
                    ? Icons.star
                    : Icons.star_border)),
            Tab(
                icon: Icon(_tabController.index == 1
                    ? Icons.access_time_filled
                    : Icons.access_time_outlined)),
            Tab(
                icon: Icon(_tabController.index == 2
                    ? Icons.contacts
                    : Icons.contacts_outlined)),
            Tab(
              icon: Icon(_tabController.index == 3
                  ? Icons.voicemail
                  : Icons.voicemail_outlined),
            ),
          ],
          labelColor: Colors.white,
          unselectedLabelColor: const Color.fromARGB(255, 158, 158, 158),
          indicatorSize: TabBarIndicatorSize.label,
          indicatorColor: Colors.white,
        ),
      ),
    );
  }
}

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

  @override
  _MyHomePageState createState() => _MyHomePageState();
}