import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

import '../services/api_service.dart';
import '../widgets/common.dart';
import '../widgets/donor_details_sheet.dart';

class HomeScreen extends StatefulWidget {
  final int profileVersion;
  final void Function(int) onTab;
  final void Function(String districtId, String thanaId, String bloodGroupId) onDonorSearch;
  const HomeScreen({
    super.key,
    this.profileVersion = 0,
    required this.onTab,
    required this.onDonorSearch,
  });

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Map<String, dynamic>? home;
  List<Map<String, dynamic>> donors = [];
  List<Map<String, dynamic>> districts = [];
  List<Map<String, dynamic>> bloodGroups = [];
  Map<String, dynamic>? cachedUser;
  String selectedGroup = 'A+';
  String? error;
  final search = TextEditingController();

  bool groupSearchActive = false;
  bool groupPaging = false;
  String selectedBloodGroupId = '';
  String? groupError;
  int groupPage = 1;
  static const int groupPerPage = 10;
  int groupTotal = 0;
  int groupTotalPages = 1;
  int _groupRequestToken = 0;

  static const groups = ['A+', 'B+', 'O+', 'AB+', 'A-', 'B-', 'O-', 'AB-'];

  @override
  void initState() {
    super.initState();
    load();
  }

  @override
  void didUpdateWidget(covariant HomeScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.profileVersion != widget.profileVersion) {
      load();
    }
  }

  @override
  void dispose() {
    search.dispose();
    super.dispose();
  }

  Future<void> load() async {
    if (mounted) setState(() => error = null);
    try {
      final results = await Future.wait([
        ApiService.getJson('/home'),
        ApiService.getJson('/donors'),
        ApiService.cachedUser(),
        ApiService.getJson('/donor-filters'),
      ]);
      final h = _map(results[0]);
      final donorResponse = _map(results[1]);
      final user = results[2] is Map ? _map(results[2]) : <String, dynamic>{};
      final filterResponse = _map(results[3]);
      if (!mounted) return;
      setState(() {
        home = h;
        donors = _mapList(donorResponse['data']);
        cachedUser = user.isEmpty ? null : user;
        districts = _mapList(filterResponse['districts']);
        bloodGroups = _mapList(filterResponse['blood_groups']);
        error = null;
      });
    } catch (e) {
      if (mounted) setState(() => error = e.toString());
    }
  }

  Map<String, dynamic> _map(dynamic value) {
    if (value is Map<String, dynamic>) return value;
    if (value is Map) {
      return value.map((key, val) => MapEntry(key.toString(), val));
    }
    return <String, dynamic>{};
  }

  List<Map<String, dynamic>> _mapList(dynamic value) {
    if (value is! List) return <Map<String, dynamic>>[];
    return value
        .whereType<Map>()
        .map((e) => e.map((key, val) => MapEntry(key.toString(), val)))
        .toList();
  }

  List<Map<String, dynamic>> get filteredDonors =>
      groupSearchActive ? donors : donors.take(3).toList();

  int _intValue(dynamic value, int fallback) {
    if (value is int) return value;
    return int.tryParse('${value ?? ''}') ?? fallback;
  }

  Future<void> _loadBloodGroupDonors(
    String bloodGroupId,
    String group, {
    int page = 1,
  }) async {
    if (bloodGroupId.isEmpty) return;
    if (groupPaging && selectedBloodGroupId == bloodGroupId) return;

    final isNewGroup = selectedBloodGroupId != bloodGroupId;
    final requestToken = ++_groupRequestToken;
    setState(() {
      selectedGroup = group;
      selectedBloodGroupId = bloodGroupId;
      groupSearchActive = true;
      groupPaging = true;
      groupError = null;
      groupPage = page;
      if (isNewGroup) {
        donors = [];
        groupTotal = 0;
        groupTotalPages = 1;
      }
    });

    try {
      final data = await ApiService.getJson(
        '/donors',
        query: {
          'blood_group_id': bloodGroupId,
          'page': '$page',
          'per_page': '$groupPerPage',
        },
      );
      final pagination = _map(data['pagination']);
      if (!mounted || requestToken != _groupRequestToken) return;
      setState(() {
        donors = _mapList(data['data']);
        groupPage = _intValue(pagination['page'], page);
        groupTotal = _intValue(pagination['total'], donors.length);
        groupTotalPages = _intValue(pagination['total_pages'], 1);
        if (groupTotalPages < 1) groupTotalPages = 1;
        groupPaging = false;
      });
    } catch (e) {
      if (!mounted || requestToken != _groupRequestToken) return;
      setState(() {
        groupPaging = false;
        groupError = e.toString();
      });
    }
  }

  Future<void> _goGroupPage(int targetPage) async {
    if (groupPaging ||
        selectedBloodGroupId.isEmpty ||
        targetPage < 1 ||
        targetPage > groupTotalPages ||
        targetPage == groupPage) {
      return;
    }

    // No route change and no scroll jump: only this donor list is replaced.
    await _loadBloodGroupDonors(
      selectedBloodGroupId,
      selectedGroup,
      page: targetPage,
    );
  }

  @override
  Widget build(BuildContext context) {
    if (home == null) {
      return Scaffold(
        backgroundColor: Colors.white,
        body: Center(
          child: error == null
              ? const CircularProgressIndicator(color: Color(0xFFD71920))
              : Padding(
                  padding: const EdgeInsets.all(28),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(error!, textAlign: TextAlign.center),
                      const SizedBox(height: 14),
                      FilledButton(
                        onPressed: load,
                        style: FilledButton.styleFrom(backgroundColor: const Color(0xFFD71920)),
                        child: const Text('আবার চেষ্টা করুন'),
                      ),
                    ],
                  ),
                ),
        ),
      );
    }

    final stats = _map(home!['stats']);
    final activeRequests = int.tryParse('${stats['active_requests'] ?? 0}') ?? 0;

    return Scaffold(
      backgroundColor: const Color(0xFFFBFBFC),
      body: SafeArea(
        bottom: false,
        child: RefreshIndicator(
          onRefresh: load,
          color: const Color(0xFFD71920),
          child: CustomScrollView(
            physics: const AlwaysScrollableScrollPhysics(),
            slivers: [
              SliverToBoxAdapter(child: _header()),
              SliverToBoxAdapter(child: _hero()),
              SliverToBoxAdapter(child: _searchBar()),
              SliverToBoxAdapter(child: _bloodGroups()),
              SliverToBoxAdapter(child: _nearbyDonors()),
              SliverToBoxAdapter(child: _emergencyCard(activeRequests)),
              SliverToBoxAdapter(child: _oldHomeSections(stats)),
              const SliverToBoxAdapter(child: SizedBox(height: 28)),
            ],
          ),
        ),
      ),
    );
  }

  Widget _header() {
    final photo = (cachedUser?['photo_url'] ?? '').toString();
    return Container(
      height: 104,
      padding: const EdgeInsets.fromLTRB(20, 15, 18, 12),
      color: Colors.white,
      child: Row(
        children: [
          Container(
            width: 48,
            height: 58,
            decoration: BoxDecoration(
              color: const Color(0xFFD71920),
              borderRadius: BorderRadius.circular(24),
              boxShadow: const [
                BoxShadow(color: Color(0x22000000), blurRadius: 12, offset: Offset(0, 5)),
              ],
            ),
            child: const Icon(Icons.monitor_heart_rounded, color: Colors.white, size: 31),
          ),
          const SizedBox(width: 13),
          const Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'লাইফড্রপ',
                  style: TextStyle(fontSize: 24, fontWeight: FontWeight.w900, color: Color(0xFF161616), height: 1.05),
                ),
                SizedBox(height: 6),
                Text('রক্ত দিন, জীবন বাঁচান', style: TextStyle(fontSize: 14, color: Color(0xFF777777))),
              ],
            ),
          ),
          InkWell(
            onTap: () => widget.onTab(3),
            borderRadius: BorderRadius.circular(24),
            child: Stack(
              clipBehavior: Clip.none,
              children: [
                Container(
                  width: 48,
                  height: 48,
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    shape: BoxShape.circle,
                    boxShadow: [BoxShadow(color: Color(0x18000000), blurRadius: 16, offset: Offset(0, 5))],
                  ),
                  child: const Icon(Icons.notifications_none_rounded, color: Color(0xFF242424), size: 29),
                ),
                Positioned(
                  right: -1,
                  top: -2,
                  child: Container(
                    width: 20,
                    height: 20,
                    alignment: Alignment.center,
                    decoration: const BoxDecoration(color: Color(0xFFD71920), shape: BoxShape.circle),
                    child: const Text('3', style: TextStyle(color: Colors.white, fontSize: 11, fontWeight: FontWeight.w900)),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(width: 13),
          InkWell(
            onTap: () => widget.onTab(4),
            borderRadius: BorderRadius.circular(28),
            child: Container(
              width: 52,
              height: 52,
              padding: const EdgeInsets.all(3),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.white,
                border: Border.all(color: const Color(0xFFFFB5B8), width: 2),
                boxShadow: const [BoxShadow(color: Color(0x18000000), blurRadius: 10, offset: Offset(0, 4))],
              ),
              child: ClipOval(
                child: photo.isNotEmpty
                    ? CachedNetworkImage(
                        imageUrl: photo,
                        fit: BoxFit.cover,
                        errorWidget: (_, __, ___) => _avatarFallback(),
                      )
                    : _avatarFallback(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _avatarFallback() => Container(
        color: const Color(0xFFFFECEC),
        child: const Icon(Icons.person_rounded, color: Color(0xFFD71920), size: 32),
      );

  Widget _hero() {
    return GestureDetector(
      onTap: () => widget.onTab(2),
      child: SizedBox(
        width: double.infinity,
        child: Image.asset(
          'assets/images/lifedrop_home_hero.png',
          fit: BoxFit.fitWidth,
          alignment: Alignment.topCenter,
        ),
      ),
    );
  }

  List<Map<String, dynamic>> _thanasFor(String districtId) {
    if (districtId.isEmpty) return <Map<String, dynamic>>[];
    for (final district in districts) {
      if ('${district['id']}' == districtId) {
        return _mapList(district['thanas']);
      }
    }
    return <Map<String, dynamic>>[];
  }

  String _catalogName(List<Map<String, dynamic>> items, String id) {
    for (final item in items) {
      if ('${item['id']}' == id) return (item['name'] ?? '').toString();
    }
    return '';
  }

  Future<void> _openDonorFilter({String? preselectedGroupName}) async {
    if (districts.isEmpty || bloodGroups.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('ফিল্টার ডাটা পাওয়া যায়নি। Admin Panel থেকে জেলা, থানা ও রক্তের গ্রুপ যোগ করুন।')),
      );
      return;
    }

    String districtId = '';
    String thanaId = '';
    String bloodGroupId = '';
    if (preselectedGroupName != null && preselectedGroupName.isNotEmpty) {
      for (final item in bloodGroups) {
        if ((item['name'] ?? '').toString() == preselectedGroupName) {
          bloodGroupId = '${item['id']}';
          break;
        }
      }
    }

    final result = await showModalBottomSheet<List<String>>(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (sheetContext) => StatefulBuilder(
        builder: (context, setModalState) {
          final thanas = _thanasFor(districtId);
          return Container(
            padding: EdgeInsets.fromLTRB(20, 18, 20, 20 + MediaQuery.of(context).viewInsets.bottom),
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.vertical(top: Radius.circular(28)),
            ),
            child: SafeArea(
              top: false,
              child: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Center(
                      child: Container(
                        width: 44,
                        height: 5,
                        decoration: BoxDecoration(color: const Color(0xFFE2E2E2), borderRadius: BorderRadius.circular(10)),
                      ),
                    ),
                    const SizedBox(height: 18),
                    const Text('ডোনার খুঁজুন', style: TextStyle(fontSize: 22, fontWeight: FontWeight.w900)),
                    const SizedBox(height: 6),
                    const Text('প্রথমে জেলা, তারপর থানা, এরপর রক্তের গ্রুপ নির্বাচন করুন।', style: TextStyle(color: Color(0xFF777777))),
                    const SizedBox(height: 20),
                    DropdownButtonFormField<String>(
                      value: districtId.isEmpty ? null : districtId,
                      isExpanded: true,
                      decoration: _filterDecoration('১. জেলা নির্বাচন করুন', Icons.location_city_rounded),
                      items: districts
                          .map((d) => DropdownMenuItem(value: '${d['id']}', child: Text((d['name'] ?? '').toString())))
                          .toList(),
                      onChanged: (value) => setModalState(() {
                        districtId = value ?? '';
                        thanaId = '';
                      }),
                    ),
                    const SizedBox(height: 12),
                    DropdownButtonFormField<String>(
                      value: thanaId.isEmpty ? null : thanaId,
                      isExpanded: true,
                      decoration: _filterDecoration('২. থানা নির্বাচন করুন', Icons.account_balance_rounded),
                      items: thanas
                          .map((t) => DropdownMenuItem(value: '${t['id']}', child: Text((t['name'] ?? '').toString())))
                          .toList(),
                      onChanged: districtId.isEmpty ? null : (value) => setModalState(() => thanaId = value ?? ''),
                    ),
                    const SizedBox(height: 12),
                    DropdownButtonFormField<String>(
                      value: bloodGroupId.isEmpty ? null : bloodGroupId,
                      isExpanded: true,
                      decoration: _filterDecoration('৩. রক্তের গ্রুপ নির্বাচন করুন', Icons.bloodtype_rounded),
                      items: bloodGroups
                          .map((g) => DropdownMenuItem(value: '${g['id']}', child: Text((g['name'] ?? '').toString())))
                          .toList(),
                      onChanged: (value) => setModalState(() => bloodGroupId = value ?? ''),
                    ),
                    const SizedBox(height: 20),
                    SizedBox(
                      width: double.infinity,
                      height: 54,
                      child: FilledButton.icon(
                        onPressed: districtId.isEmpty || thanaId.isEmpty || bloodGroupId.isEmpty
                            ? null
                            : () => Navigator.pop(sheetContext, [districtId, thanaId, bloodGroupId]),
                        style: FilledButton.styleFrom(
                          backgroundColor: const Color(0xFFD71920),
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
                        ),
                        icon: const Icon(Icons.search_rounded),
                        label: const Text('ডোনার দেখুন', style: TextStyle(fontWeight: FontWeight.w800, fontSize: 16)),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );

    if (result == null || result.length != 3 || !mounted) return;
    final selectedDistrict = _catalogName(districts, result[0]);
    final selectedThana = _catalogName(_thanasFor(result[0]), result[1]);
    final selectedBloodGroup = _catalogName(bloodGroups, result[2]);
    search.text = '$selectedDistrict • $selectedThana • $selectedBloodGroup';
    widget.onDonorSearch(result[0], result[1], result[2]);
  }

  InputDecoration _filterDecoration(String label, IconData icon) {
    return InputDecoration(
      labelText: label,
      prefixIcon: Icon(icon, color: const Color(0xFFD71920)),
      filled: true,
      fillColor: const Color(0xFFFAFAFA),
      border: OutlineInputBorder(borderRadius: BorderRadius.circular(16), borderSide: const BorderSide(color: Color(0xFFE8E8E8))),
      enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(16), borderSide: const BorderSide(color: Color(0xFFE8E8E8))),
    );
  }

  Widget _searchBar() {
    return Transform.translate(
      offset: const Offset(0, -16),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 22),
        child: Container(
          height: 82,
          padding: const EdgeInsets.symmetric(horizontal: 16),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(23),
            boxShadow: const [BoxShadow(color: Color(0x1B000000), blurRadius: 24, offset: Offset(0, 9))],
          ),
          child: Row(
            children: [
              Container(
                width: 48,
                height: 48,
                decoration: const BoxDecoration(color: Color(0xFFFFE8E8), shape: BoxShape.circle),
                child: const Icon(Icons.location_on_rounded, color: Color(0xFFD71920), size: 28),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: TextField(
                  controller: search,
                  readOnly: true,
                  onTap: _openDonorFilter,
                  decoration: const InputDecoration(
                    border: InputBorder.none,
                    hintText: 'জেলা → থানা → রক্তের গ্রুপ নির্বাচন করুন\nতারপর আপনার এলাকার ডোনার দেখুন',
                    hintMaxLines: 2,
                    hintStyle: TextStyle(color: Color(0xFF8A8A8A), fontSize: 13.5, height: 1.35),
                  ),
                ),
              ),
              Container(width: 1, height: 42, color: const Color(0xFFEDEDED)),
              const SizedBox(width: 12),
              InkWell(
                onTap: _openDonorFilter,
                borderRadius: BorderRadius.circular(24),
                child: Container(
                  width: 50,
                  height: 50,
                  decoration: const BoxDecoration(
                    gradient: LinearGradient(colors: [Color(0xFFE62A31), Color(0xFFC80B12)]),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(Icons.search_rounded, color: Colors.white, size: 30),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _sectionHeader(String title, VoidCallback onAll) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(22, 2, 20, 13),
      child: Row(
        children: [
          Expanded(child: Text(title, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w900, color: Color(0xFF171717)))),
          InkWell(
            onTap: onAll,
            child: const Row(
              children: [
                Text('সব দেখুন', style: TextStyle(color: Color(0xFF777777), fontSize: 14)),
                SizedBox(width: 3),
                Icon(Icons.chevron_right_rounded, color: Color(0xFF777777), size: 22),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _bloodGroups() {
    final availableGroups = bloodGroups.isEmpty
        ? groups
        : bloodGroups.map((e) => (e['name'] ?? '').toString()).where((e) => e.isNotEmpty).toList();
    return Column(
      children: [
        _sectionHeader('রক্তের গ্রুপ অনুযায়ী ডোনার খুঁজুন', () => widget.onTab(1)),
        SizedBox(
          height: 82,
          child: ListView.separated(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            scrollDirection: Axis.horizontal,
            itemCount: availableGroups.length,
            separatorBuilder: (_, __) => const SizedBox(width: 11),
            itemBuilder: (_, i) {
              final group = availableGroups[i];
              final selected = selectedGroup == group;
              return InkWell(
                onTap: () {
                  String bloodGroupId = '';
                  for (final item in bloodGroups) {
                    if ((item['name'] ?? '').toString() == group) {
                      bloodGroupId = '${item['id']}';
                      break;
                    }
                  }
                  if (bloodGroupId.isEmpty) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('এই রক্তের গ্রুপের database ID পাওয়া যায়নি।')),
                    );
                    return;
                  }
                  // Blood-group shortcut stays on HOME. It searches across
                  // all districts/thanas and replaces this home donor list 10 at a time.
                  _loadBloodGroupDonors(bloodGroupId, group);
                },
                borderRadius: BorderRadius.circular(36),
                child: AnimatedContainer(
                  duration: const Duration(milliseconds: 180),
                  width: 66,
                  height: 66,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    gradient: selected
                        ? const LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [Color(0xFFFF5558), Color(0xFFD60710)])
                        : null,
                    color: selected ? null : Colors.white,
                    border: selected ? null : Border.all(color: const Color(0xFFF0F0F0)),
                    boxShadow: const [BoxShadow(color: Color(0x17000000), blurRadius: 13, offset: Offset(0, 6))],
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.water_drop_outlined, color: selected ? Colors.white : const Color(0xFFE20C16), size: 16),
                      const SizedBox(height: 1),
                      Text(
                        group,
                        style: TextStyle(color: selected ? Colors.white : const Color(0xFFD71920), fontWeight: FontWeight.w900, fontSize: 18),
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _nearbyDonors() {
    final list = filteredDonors;
    final title = groupSearchActive ? '$selectedGroup গ্রুপের ডোনার' : 'কাছাকাছি ডোনার';

    return Padding(
      padding: const EdgeInsets.only(top: 3),
      child: Column(
        children: [
          _sectionHeader(title, () => widget.onTab(1)),
          if (groupSearchActive)
            Padding(
              padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      'সকল লোকেশন থেকে মোট $groupTotal জন',
                      style: const TextStyle(
                        color: Color(0xFF6F6F6F),
                        fontSize: 12.5,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                  Text(
                    'পৃষ্ঠা $groupPage / $groupTotalPages',
                    style: const TextStyle(
                      color: Color(0xFFD71920),
                      fontSize: 12.5,
                      fontWeight: FontWeight.w800,
                    ),
                  ),
                ],
              ),
            ),
          if (groupPaging)
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: 20),
              child: LinearProgressIndicator(
                minHeight: 2,
                color: Color(0xFFD71920),
                backgroundColor: Color(0xFFFFE5E6),
              ),
            ),
          if (groupError != null)
            Padding(
              padding: const EdgeInsets.fromLTRB(20, 8, 20, 10),
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.all(14),
                decoration: BoxDecoration(
                  color: const Color(0xFFFFF3F3),
                  borderRadius: BorderRadius.circular(14),
                  border: Border.all(color: const Color(0xFFFFD2D4)),
                ),
                child: Text(
                  groupError!,
                  textAlign: TextAlign.center,
                  style: const TextStyle(color: Color(0xFFB20B12), fontSize: 12.5),
                ),
              ),
            ),
          if (list.isEmpty && !groupPaging)
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.all(22),
                decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(18)),
                child: Text(
                  groupSearchActive
                      ? '$selectedGroup গ্রুপে কোনো ডোনার পাওয়া যায়নি।'
                      : 'ডাটাবেজে এখনো ডোনার পাওয়া যায়নি। Demo donor SQL import করুন।',
                  textAlign: TextAlign.center,
                ),
              ),
            )
          else
            ...List.generate(
              list.length,
              (i) => _donorCard(
                list[i],
                i,
                serial: groupSearchActive ? ((groupPage - 1) * groupPerPage) + i + 1 : null,
              ),
            ),
          if (groupSearchActive && list.isNotEmpty) _homePaginationBar(),
        ],
      ),
    );
  }

  Widget _homePaginationBar() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 2, 20, 14),
      child: Row(
        children: [
          Expanded(
            child: OutlinedButton.icon(
              onPressed: groupPage > 1 && !groupPaging
                  ? () => _goGroupPage(groupPage - 1)
                  : null,
              icon: const Icon(Icons.chevron_left_rounded),
              label: const Text('আগের ১০ জন'),
              style: OutlinedButton.styleFrom(
                foregroundColor: const Color(0xFFD71920),
                side: const BorderSide(color: Color(0xFFFFC7C9)),
                minimumSize: const Size.fromHeight(46),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
              ),
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: FilledButton.icon(
              onPressed: groupPage < groupTotalPages && !groupPaging
                  ? () => _goGroupPage(groupPage + 1)
                  : null,
              icon: const Icon(Icons.chevron_right_rounded),
              label: const Text('পরের ১০ জন'),
              style: FilledButton.styleFrom(
                backgroundColor: const Color(0xFFD71920),
                minimumSize: const Size.fromHeight(46),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _donorCard(Map<String, dynamic> donor, int index, {int? serial}) {
    final photo = (donor['photo_url'] ?? '').toString();
    final canDonate = donor['can_donate'] == 1 || donor['can_donate'] == '1';
    final available = donor['available'] == 1 || donor['available'] == '1';
    final online = canDonate && available;
    final location = [donor['upazila'], donor['district']]
        .where((e) => e != null && e.toString().trim().isNotEmpty)
        .map((e) => e.toString())
        .join(', ');
    final distances = ['১.২ কিমি দূরে', '১.৬ কিমি দূরে', '২.৪ কিমি দূরে'];

    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 0, 20, 12),
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () => showDonorDetailsSheet(context, donor),
        child: Container(
        height: 90,
        padding: const EdgeInsets.symmetric(horizontal: 12),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(18),
          boxShadow: const [
            BoxShadow(
              color: Color(0x13000000),
              blurRadius: 16,
              offset: Offset(0, 6),
            ),
          ],
        ),
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            Row(
              children: [
                Stack(
                  children: [
                    CircleAvatar(
                      radius: 31,
                      backgroundColor: const Color(0xFFFFE8E8),
                      backgroundImage: photo.isNotEmpty
                          ? CachedNetworkImageProvider(photo)
                          : null,
                      child: photo.isEmpty
                          ? const Icon(
                              Icons.person,
                              color: Color(0xFFD71920),
                              size: 33,
                            )
                          : null,
                    ),
                    Positioned(
                      right: 0,
                      bottom: 1,
                      child: Container(
                        width: 13,
                        height: 13,
                        decoration: BoxDecoration(
                          color: online
                              ? const Color(0xFF1EBB4B)
                              : const Color(0xFFFFA000),
                          shape: BoxShape.circle,
                          border: Border.all(color: Colors.white, width: 2),
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(width: 13),
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        (donor['name'] ?? 'ডোনার').toString(),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(
                          fontSize: 16.5,
                          fontWeight: FontWeight.w900,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Row(
                        children: [
                          const Icon(
                            Icons.location_on_outlined,
                            size: 16,
                            color: Color(0xFF8C8C8C),
                          ),
                          const SizedBox(width: 3),
                          Flexible(
                            child: Text(
                              location.isEmpty
                                  ? distances[index < distances.length
                                      ? index
                                      : distances.length - 1]
                                  : location,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: const TextStyle(
                                fontSize: 12.5,
                                color: Color(0xFF888888),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  width: 58,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const Icon(
                            Icons.water_drop,
                            size: 16,
                            color: Color(0xFFD71920),
                          ),
                          const SizedBox(width: 3),
                          Text(
                            (donor['blood_group'] ?? '').toString(),
                            style: const TextStyle(
                              fontWeight: FontWeight.w900,
                              fontSize: 15,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 6),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            width: 9,
                            height: 9,
                            decoration: BoxDecoration(
                              color: online
                                  ? const Color(0xFF20B848)
                                  : const Color(0xFFFFA000),
                              shape: BoxShape.circle,
                            ),
                          ),
                          const SizedBox(width: 5),
                          Text(
                            online ? 'উপলব্ধ' : 'ব্যস্ত',
                            style: const TextStyle(
                              fontSize: 11.5,
                              color: Color(0xFF777777),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                const SizedBox(width: 6),
                _roundAction(
                  Icons.visibility_outlined,
                  outlined: true,
                  onTap: () => showDonorDetailsSheet(context, donor),
                ),
                const SizedBox(width: 8),
                _roundAction(
                  Icons.call_rounded,
                  onTap: () async {
                    final phone = (donor['phone'] ?? '').toString();
                    if (phone.isNotEmpty) {
                      await launchUrl(Uri.parse('tel:$phone'));
                    }
                  },
                ),
              ],
            ),
            if (serial != null)
              Positioned(
                left: -7,
                top: -7,
                child: Container(
                  width: 24,
                  height: 24,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    shape: BoxShape.circle,
                    border: Border.all(
                      color: const Color(0xFFD71920),
                      width: 1.5,
                    ),
                    boxShadow: const [
                      BoxShadow(
                        color: Color(0x16000000),
                        blurRadius: 5,
                        offset: Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Text(
                    '$serial',
                    style: const TextStyle(
                      color: Color(0xFFD71920),
                      fontSize: 10.5,
                      fontWeight: FontWeight.w900,
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
      ),
    );
  }

  Widget _roundAction(IconData icon, {required VoidCallback onTap, bool outlined = false}) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(27),
      child: Container(
        width: 50,
        height: 50,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: outlined ? Colors.white : const Color(0xFFE62128),
          border: outlined ? Border.all(color: const Color(0xFFFFD0D1), width: 1.4) : null,
        ),
        child: Icon(icon, color: outlined ? const Color(0xFFE62128) : Colors.white, size: 25),
      ),
    );
  }

  Widget _emergencyCard(int activeRequests) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 7, 20, 8),
      child: InkWell(
        onTap: () => widget.onTab(4),
        borderRadius: BorderRadius.circular(20),
        child: Container(
          constraints: const BoxConstraints(minHeight: 96),
          padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 13),
          decoration: BoxDecoration(
            gradient: const LinearGradient(colors: [Color(0xFFFFECEC), Color(0xFFFFF8F8)]),
            borderRadius: BorderRadius.circular(20),
            border: Border.all(color: const Color(0xFFFFD4D4)),
          ),
          child: Row(
            children: [
              Container(
                width: 56,
                height: 56,
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [Color(0xFFFF554F), Color(0xFFD10B13)],
                  ),
                  borderRadius: BorderRadius.circular(15),
                  boxShadow: const [
                    BoxShadow(color: Color(0x33D71920), blurRadius: 12, offset: Offset(0, 5)),
                  ],
                ),
                child: const Icon(Icons.volunteer_activism_rounded, color: Colors.white, size: 31),
              ),
              const SizedBox(width: 12),
              const Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      'ডোনার হিসেবে যোগ দিন',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: Color(0xFFD71920), fontWeight: FontWeight.w900, fontSize: 16),
                    ),
                    SizedBox(height: 4),
                    Text(
                      'রক্ত দিন, জীবন বাঁচান',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: Color(0xFF555555), fontSize: 11.8, height: 1.2),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 8),
              Container(
                height: 43,
                padding: const EdgeInsets.symmetric(horizontal: 11),
                decoration: BoxDecoration(
                  color: const Color(0xFFD71920),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: const Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text('আবেদন', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w800, fontSize: 12.5)),
                    SizedBox(width: 3),
                    Icon(Icons.arrow_forward_rounded, color: Colors.white, size: 18),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _oldHomeSections(Map<String, dynamic> stats) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 22, 20, 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('আগের ফিচারগুলো', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900)),
          const SizedBox(height: 13),
          SoftCard(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _stat('${stats['donors'] ?? donors.length}', 'রক্তদাতা', kRed),
                _stat('${stats['active_requests'] ?? 0}', 'চলমান অনুরোধ', Colors.orange),
                _stat('${stats['successful_donations'] ?? 0}', 'সফল রক্তদান', Colors.green),
              ],
            ),
          ),
          const SizedBox(height: 14),
          InkWell(
            onTap: () => widget.onTab(3),
            borderRadius: BorderRadius.circular(24),
            child: Container(
              width: double.infinity,
              padding: const EdgeInsets.all(22),
              decoration: BoxDecoration(
                gradient: const LinearGradient(colors: [Color(0xFFFF4438), Color(0xFFFF2B65)]),
                borderRadius: BorderRadius.circular(24),
              ),
              child: const Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Icon(Icons.water_drop, color: Colors.white, size: 36),
                  SizedBox(height: 18),
                  Text('রক্তের লাইভ রিকোয়েস্ট সমূহ', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: 19)),
                  SizedBox(height: 5),
                  Text('আপনার এলাকায় এই মুহূর্তে জরুরি রক্তের পোস্টগুলো দেখুন', style: TextStyle(color: Colors.white70)),
                ],
              ),
            ),
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Expanded(child: _oldAction(Icons.search_rounded, 'রক্ত দাতা খুঁজুন', const Color(0xFF25243B), () => widget.onTab(1))),
              const SizedBox(width: 12),
              Expanded(child: _oldAction(Icons.add_circle, 'রক্তের আবেদন', const Color(0xFFFFA000), () => widget.onTab(2))),
            ],
          ),
        ],
      ),
    );
  }

  Widget _stat(String n, String t, Color c) => Column(
        children: [
          Text(n, style: TextStyle(color: c, fontSize: 21, fontWeight: FontWeight.w900)),
          const SizedBox(height: 3),
          Text(t, style: const TextStyle(fontSize: 11.5, color: Colors.black54)),
        ],
      );

  Widget _oldAction(IconData icon, String title, Color color, VoidCallback onTap) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(20),
      child: Container(
        height: 104,
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(20)),
        child: Row(
          children: [
            Icon(icon, color: Colors.white, size: 30),
            const SizedBox(width: 9),
            Expanded(child: Text(title, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w900))),
          ],
        ),
      ),
    );
  }
}
