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

final jobRequestsProvider = FutureProvider((ref) async {
  return ref.read(workerRepositoryProvider).getJobRequests();
});

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

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

    return Scaffold(
      appBar: AppBar(
        title: const Text('Job Requests'),
        actions: [
          IconButton(
            icon: const Icon(Icons.logout),
            onPressed: () => ref.read(authStateProvider.notifier).logout(),
          ),
        ],
      ),
      body: jobsAsync.when(
        data: (jobs) => ListView.builder(
          itemCount: jobs.length,
          itemBuilder: (context, index) {
            final job = jobs[index];
            return Card(
              margin: const EdgeInsets.all(8.0),
              child: ListTile(
                title: Text('Job #${job['id']}'),
                subtitle: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Status: ${job['status']}'),
                    Text('Address: ${job['location_address']}'),
                    Text('Time: ${job['scheduled_time']}'),
                  ],
                ),
                trailing: job['status'] == 'pending'
                    ? ElevatedButton(
                        onPressed: () {
                          // Accept Job Logic
                          ref.read(workerRepositoryProvider).updateJobStatus(job['id'], 'accepted');
                          ref.refresh(jobRequestsProvider);
                        },
                        child: const Text('Accept'),
                      )
                    : const Icon(Icons.check_circle, color: Colors.green),
              ),
            );
          },
        ),
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (err, stack) => Center(child: Text('Error: $err')),
      ),
    );
  }
}
