// ignore_for_file: unused_element

import 'package:flutter/material.dart';
import 'package:kmobile/api/services/branch_service.dart';
import 'package:kmobile/di/injection.dart';
import 'package:shimmer/shimmer.dart';
import 'package:kmobile/features/service/screens/branch_details_screen.dart';

import '../../../l10n/app_localizations.dart';

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

  @override
  State<BranchLocatorScreen> createState() => _BranchLocatorScreenState();
}

class _BranchLocatorScreenState extends State<BranchLocatorScreen> {
  final TextEditingController _searchController = TextEditingController();
  var service = getIt<BranchService>();
  bool _isLoading = true;
  List<Branch> _allBranches = [];
  List<Branch> _filteredBranches = [];

  @override
  void initState() {
    super.initState();
    // _fetchAndSetLocations();
    _loadBranches();
  }

  Future<void> _loadBranches() async {
    final data = await service.fetchBranchList();
    setState(() {
      _allBranches = data;
      _filteredBranches = data;
      _isLoading = false;
    });
  }

  void _filterBranches(String query) {
    setState(() {
      if (query.isEmpty) {
        _filteredBranches = _allBranches;
      } else {
        _filteredBranches = _allBranches.where((branch) {
          final lowerQuery = query.toLowerCase();
          return branch.branch_name.toLowerCase().contains(lowerQuery);
        }).toList();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          AppLocalizations.of(context).branchlocator,
        ),
      ),
      body: Stack(
        children: [
          Column(
            children: [
              Padding(
                padding: const EdgeInsets.all(12.0),
                child: TextField(
                  controller: _searchController,
                  onChanged: _filterBranches, // Updated
                  decoration: InputDecoration(
                    hintText: AppLocalizations.of(context).searchbranch,
                    prefixIcon: const Icon(Icons.search),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                ),
              ),

              // Content area
              Expanded(
                child: _isLoading
                    ? _buildShimmerList() // Changed to shimmer
                    : _filteredBranches.isEmpty
                        ? Center(
                            child: Text(AppLocalizations.of(context)
                                .noMatchingBranchesFound)) // Updated tex
                        : ListView.builder(
                            itemCount: _filteredBranches.length,
                            itemBuilder: (context, index) {
                              final branch =
                                  _filteredBranches[index]; // Changed to
                              return _buildBranchItem(branch); // Updated
                            },
                          ),
              ),
            ],
          ),
          IgnorePointer(
            child: Center(
              child: Opacity(
                opacity: 0.07, // Reduced opacity
                child: ClipOval(
                  child: Image.asset(
                    'assets/images/logo.png',
                    width: 200, // Adjust size as needed
                    height: 200, // Adjust size as needed
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHeader(String title) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      child: Text(
        title,
        style: Theme.of(context).textTheme.titleLarge?.copyWith(
              fontWeight: FontWeight.bold,
              color: Theme.of(context).colorScheme.primary,
            ),
      ),
    );
  }

  // Helper widget to build a single branch item

  Widget _buildBranchItem(Branch branch) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      child: ListTile(
        leading: const CircleAvatar(
          child: Icon(Icons.account_balance),
        ),
        title: Text(branch.branch_name,
            style: const TextStyle(fontWeight: FontWeight.bold)),
        onTap: () {
          // This is the updated part
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (_) => BranchDetailsScreen(branch: branch),
            ),
          );
        },
      ),
    );
  }

  // Shimmer loading list
  Widget _buildShimmerList() {
    return ListView.builder(
      itemCount: 10, // Number of shimmer items
      itemBuilder: (context, index) => Shimmer.fromColors(
        baseColor: Colors.grey.shade300,
        highlightColor: Colors.grey.shade100,
        child: ListTile(
          leading: const CircleAvatar(
            radius: 24,
            backgroundColor: Colors.white,
          ),
          title: Container(
            height: 16,
            color: Colors.white,
            margin: const EdgeInsets.symmetric(vertical: 4),
          ),
        ),
      ),
    );
  }
}
