// ignore_for_file: unused_element

import 'package:flutter/material.dart';
import '../../../l10n/app_localizations.dart';

// Enum to define the type of location
enum LocationType { branch, atm }

class Location {
  final String name;
  final String? code; // Nullable for ATMs
  final String? ifsc; // Nullable for ATMs
  final String address;
  final LocationType type;

  Location({
    required this.name,
    this.code,
    this.ifsc,
    required this.address,
    required this.type,
  });
}

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

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

class _BranchLocatorScreenState extends State<BranchLocatorScreen> {
  final TextEditingController _searchController = TextEditingController();

  final List<Location> _allLocations = [
    Location(
      name: "Dharamsala - Head Office",
      code: "002",
      ifsc: "KACE0000002",
      address: "Civil Lines Dharmashala, Kangra, HP - 176215",
      type: LocationType.branch,
    ),
    Location(
      name: "Kangra",
      code: "033",
      ifsc: "KACE0000033",
      address: "Rajput Bhawankangrapo, Kangra, HP ",
      type: LocationType.branch,
    ),
    Location(
      name: "Dharamsala ATM",
      address: "Near Main Square, Dharamsala",
      type: LocationType.atm,
    ),
    Location(
      name: "Kangra ATM",
      address: "Opposite Bus Stand, Kangra",
      type: LocationType.atm,
    ),
  ];

  List<Location> _filteredLocations = [];
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    // _fetchAndSetLocations();
    _filteredLocations = _allLocations;
  }

// Example of a future API fetching function
/*
Future<void> _fetchAndSetLocations() async {
  setState(() {
    _isLoading = true;
  });
  try {
    // final locations = await yourApiService.getLocations();
    // setState(() {
    //   _allLocations = locations;
    //   _filteredLocations = locations;
    // });
  } catch (e) {
    // Handle error
  } finally {
    setState(() {
      _isLoading = false;
    });
  }
}
*/
  void _filterLocations(String query) {
    setState(() {
      if (query.isEmpty) {
        _filteredLocations = _allLocations;
      } else {
        _filteredLocations = _allLocations.where((location) {
          final lowerQuery = query.toLowerCase();
          return location.name.toLowerCase().contains(lowerQuery) ||
              (location.code?.toLowerCase().contains(lowerQuery) ?? false) ||
              (location.ifsc?.toLowerCase().contains(lowerQuery) ?? false) ||
              location.address.toLowerCase().contains(lowerQuery);
        }).toList();
      }
    });
  }

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

          // Content area
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _filteredLocations.isEmpty
                    ? const Center(child: Text("No matching locations found"))
                    : ListView.builder(
                        itemCount: _filteredLocations.length,
                        itemBuilder: (context, index) {
                          final location = _filteredLocations[index];
                          return _buildLocationItem(location);
                        },
                      ),
          ),
        ],
      ),
    );
  }

  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 location item
  Widget _buildLocationItem(Location location) {
    final isBranch = location.type == LocationType.branch;
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      child: ListTile(
        leading: CircleAvatar(
          child: Icon(isBranch ? Icons.location_city : Icons.currency_rupee),
        ),
        title: Text(location.name,
            style: const TextStyle(fontWeight: FontWeight.bold)),
        subtitle: Text(
          isBranch
              ? "Code: ${location.code} | IFSC: ${location.ifsc}\nAddress: ${location.address}"
              : "Address: ${location.address}",
        ),
        onTap: () {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text("Selected ${location.name}")),
          );
        },
      ),
    );
  }
}
