import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../auth/auth_provider.dart';
import 'service_repository.dart';

final categoriesProvider = FutureProvider((ref) async {
  return ref.read(serviceRepositoryProvider).getCategories();
});

class CustomerHomeScreen extends ConsumerWidget {
  const CustomerHomeScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final categoriesAsync = ref.watch(categoriesProvider);

    return Scaffold(
      appBar: AppBar(
        title: const Text('Blixora Services'),
        actions: [
          IconButton(
            icon: const Icon(Icons.logout),
            onPressed: () => ref.read(authStateProvider.notifier).logout(),
          ),
        ],
      ),
      body: categoriesAsync.when(
        data: (categories) => ListView.builder(
          itemCount: categories.length,
          itemBuilder: (context, index) {
            final category = categories[index];
            return ExpansionTile(
              title: Text(category['name']),
              children: (category['services'] as List).map<Widget>((service) {
                return ListTile(
                  title: Text(service['name']),
                  subtitle: Text('\$${service['base_price']}'),
                  trailing: ElevatedButton(
                    onPressed: () {
                      context.push('/post-job', extra: service);
                    },
                    child: const Text('Book'),
                  ),
                );
              }).toList(),
            );
          },
        ),
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (err, stack) => Center(child: Text('Error: $err')),
      ),
    );
  }
}
