import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../providers/dashboard_providers.dart';
import '../../../widgets/vehicle_card.dart';
import '../../../widgets/loading_list.dart';
import '../../../widgets/error_view.dart';
import 'dashboard_shell.dart';
import 'vehicle_form_screen.dart';

class VehiclesScreen extends ConsumerStatefulWidget {
  const VehiclesScreen({super.key});

  @override
  ConsumerState<VehiclesScreen> createState() => _VehiclesScreenState();
}

class _VehiclesScreenState extends ConsumerState<VehiclesScreen> {
  String? _statusFilter;
  final _searchController = TextEditingController();
  String _search = '';

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

  Map<String, dynamic> get _params => {
    'page': 1,
    'pageSize': 50,
    if (_statusFilter != null) 'status': _statusFilter,
    if (_search.isNotEmpty) 'search': _search,
  };

  @override
  Widget build(BuildContext context) {
    final vehiclesAsync = ref.watch(vehiclesProvider(_params));

    return DashboardShell(
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          final result = await Navigator.of(context).push<bool>(
            MaterialPageRoute(builder: (_) => const VehicleFormScreen()),
          );
          if (result == true) ref.invalidate(vehiclesProvider(_params));
        },
        child: const Icon(Icons.add),
      ),
      appBar: AppBar(
        title: const Text('Vehicles'),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(60),
          child: Padding(
            padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
            child: TextField(
              controller: _searchController,
              decoration: const InputDecoration(
                hintText: 'Search vehicles...',
                prefixIcon: Icon(Icons.search, size: 20),
                contentPadding: EdgeInsets.symmetric(vertical: 8),
              ),
              onChanged: (v) => setState(() => _search = v),
            ),
          ),
        ),
        actions: [
          PopupMenuButton<String?>(
            icon: Icon(
              Icons.filter_list,
              color: _statusFilter != null ? const Color(0xFF1A56DB) : null,
            ),
            onSelected: (v) => setState(() => _statusFilter = v),
            itemBuilder: (_) => [
              const PopupMenuItem(value: null, child: Text('All')),
              const PopupMenuItem(value: 'AVAILABLE', child: Text('Available')),
              const PopupMenuItem(value: 'RENTED', child: Text('Rented')),
              const PopupMenuItem(
                value: 'MAINTENANCE',
                child: Text('Maintenance'),
              ),
            ],
          ),
        ],
      ),
      body: vehiclesAsync.when(
        loading: () => const LoadingList(itemHeight: 240),
        error: (e, _) => ErrorView(
          message: 'Failed to load vehicles',
          onRetry: () => ref.invalidate(vehiclesProvider(_params)),
        ),
        data: (res) => res.data.isEmpty
            ? const Center(
                child: Text(
                  'No vehicles found',
                  style: TextStyle(color: Color(0xFF9CA3AF)),
                ),
              )
            : RefreshIndicator(
                onRefresh: () async =>
                    ref.invalidate(vehiclesProvider(_params)),
                child: GridView.builder(
                  padding: const EdgeInsets.all(16),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 1,
                    mainAxisExtent: 240,
                    mainAxisSpacing: 12,
                  ),
                  itemCount: res.data.length,
                  itemBuilder: (_, i) => VehicleCard(
                    vehicle: res.data[i],
                    onTap: () =>
                        context.push('/dashboard/vehicles/${res.data[i].id}'),
                  ),
                ),
              ),
      ),
    );
  }
}
