import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:inventory_system/services/station_service.dart';
import 'package:inventory_system/screens/admin/station/station_form.dart';
import 'package:inventory_system/screens/bottom_nav_bar.dart';
import 'package:inventory_system/screens/nav_bar.dart';
import 'package:inventory_system/screens/title_bar.dart';

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

  @override
  State<StationScreen> createState() => _StationScreenState();
}

class _StationScreenState extends State<StationScreen> {
  int _selectedIndex = 0;
  final StationService _stationService = StationService();
  late Future<List<dynamic>> _stationsFuture;

  List<dynamic> _allStations = [];
  List<dynamic> _filteredStations = [];
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _stationsFuture = _fetchStations();
    _searchController.addListener(_onSearchChanged);
  }

  Future<List<dynamic>> _fetchStations() async {
    try {
      final stations = await _stationService.fetchStations();
      stations.sort((a, b) {
        final nameA = a['stationName'] as String? ?? '';
        final nameB = b['stationName'] as String? ?? '';
        return nameA.toLowerCase().compareTo(nameB.toLowerCase());
      });
      if (mounted) {
        setState(() {
          _allStations = stations;
          _filteredStations = stations;
        });
      }
      return stations;
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to load stations: $e'), backgroundColor: Colors.red),
        );
      }
      rethrow;
    }
  }

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

  void _onSearchChanged() {
    final query = _searchController.text.toLowerCase();
    setState(() {
      _filteredStations = _allStations.where((station) {
        final name = station['stationName'].toString().toLowerCase();
        final department = station['departmentName'].toString().toLowerCase();
        return name.contains(query) || department.contains(query);
      }).toList();
    });
  }

  void _handleDelete(int stationId) async {
    try {
      await _stationService.deleteStation(stationId);
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
            content: Text('Station deleted successfully'),
            backgroundColor: Colors.green),
      );
      _fetchStations();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content: Text('Failed to delete station: $e'),
              backgroundColor: Colors.red),
        );
      }
    }
  }

  void _confirmDelete(int stationId, String stationName) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Delete Station'),
        content: Text('Are you sure you want to delete $stationName?'),
        actions: [
          TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('Cancel')),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _handleDelete(stationId);
            },
            child: const Text('Delete', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

  void _navigateAndRefresh() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const StationFormScreen()),
    ).then((_) => _fetchStations());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F7),
      appBar: const TitleBar(title: 'Station'),
      drawer: const NavBar(isAdmin: true, selectedScreen: AppScreen.station),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Row(
              children: [
                ElevatedButton.icon(
                  onPressed: _navigateAndRefresh,
                  icon: const Icon(Icons.add, size: 18),
                  label: const Text('Add Station'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.purple.shade100,
                    foregroundColor: Colors.black87,
                    padding:
                        const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12)),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: TextField(
                    controller: _searchController,
                    decoration: InputDecoration(
                      hintText: 'Search',
                      hintStyle: TextStyle(color: Colors.grey.shade400),
                      prefixIcon: const Icon(Icons.search),
                      filled: true,
                      fillColor: Colors.white,
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12),
                          borderSide: BorderSide.none),
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Expanded(
              child: RefreshIndicator(
                onRefresh: _fetchStations,
                child: FutureBuilder<List<dynamic>>(
                  future: _stationsFuture,
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting &&
                        _allStations.isEmpty) {
                      return const Center(child: CircularProgressIndicator());
                    }
                    if (snapshot.hasError && _allStations.isEmpty) {
                      return Center(child: Text('Error: ${snapshot.error}'));
                    }
                    if (_filteredStations.isEmpty) {
                      return const Center(child: Text('No stations found.'));
                    }

                    return ListView.builder(
                      itemCount: _filteredStations.length,
                      itemBuilder: (context, index) {
                        final station = _filteredStations[index];
                        return Padding(
                          padding: const EdgeInsets.only(bottom: 12),
                          child: Slidable(
                            key: Key(station['stationId'].toString()),
                            endActionPane: ActionPane(
                              motion: const StretchMotion(),
                              children: [
                                SlidableAction(
                                  onPressed: (context) {
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) =>
                                              StationFormScreen(station: station)),
                                    ).then((_) => _fetchStations());
                                  },
                                  backgroundColor: Colors.blue,
                                  foregroundColor: Colors.white,
                                  icon: Icons.edit,
                                  label: 'Edit',
                                ),
                                SlidableAction(
                                  onPressed: (context) => _confirmDelete(
                                    station['stationId'],
                                    station['stationName'],
                                  ),
                                  backgroundColor: Colors.red,
                                  foregroundColor: Colors.white,
                                  icon: Icons.delete,
                                  label: 'Delete',
                                  borderRadius: const BorderRadius.horizontal(
                                      right: Radius.circular(16)),
                                ),
                              ],
                            ),
                            child: Card(
                              margin: EdgeInsets.zero,
                              color: Colors.white,
                              elevation: 1,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(16),
                                side: BorderSide(color: Colors.grey.shade300),
                              ),
                              child: ListTile(
                                contentPadding: const EdgeInsets.symmetric(
                                    vertical: 8,
                                    horizontal: 16),
                                title: Text(
                                  station['stationName'] ?? 'No Name',
                                  style: const TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.w600,
                                    color: Colors.black87,
                                  ),
                                ),
                                subtitle: Text(
                                    station['departmentName'] ?? 'No Department'),
                              ),
                            ),
                          ),
                        );
                      },
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
      bottomNavigationBar: BottomNavBar(
        selectedIndex: _selectedIndex,
        onItemTapped: (index) {
          if (index == 0) {
            Navigator.pop(context);
          } else {
            setState(() {
              _selectedIndex = index;
            });
          }
        },
      ),
    );
  }
}
