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

class PostJobScreen extends ConsumerStatefulWidget {
  final Map<String, dynamic> service;
  const PostJobScreen({super.key, required this.service});

  @override
  ConsumerState<PostJobScreen> createState() => _PostJobScreenState();
}

class _PostJobScreenState extends ConsumerState<PostJobScreen> {
  final _addressController = TextEditingController();
  final _dateController = TextEditingController();
  bool _isLoading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Book ${widget.service['name']}')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _addressController,
              decoration: const InputDecoration(labelText: 'Address'),
            ),
            TextField(
              controller: _dateController,
              decoration: const InputDecoration(labelText: 'Date & Time (YYYY-MM-DD HH:MM)'),
            ),
            const SizedBox(height: 20),
            if (_isLoading)
              const CircularProgressIndicator()
            else
              ElevatedButton(
                onPressed: () async {
                  setState(() => _isLoading = true);
                  try {
                    await ref.read(serviceRepositoryProvider).postJob({
                      'service_id': widget.service['id'],
                      'location_lat': 0.0, // Mock
                      'location_lng': 0.0, // Mock
                      'location_address': _addressController.text,
                      'scheduled_time': _dateController.text,
                      'customer_id': 1, // Mock, should come from auth
                    });
                    if (context.mounted) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('Job Posted Successfully!')),
                      );
                      context.pop();
                    }
                  } catch (e) {
                    if (context.mounted) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(content: Text('Error: $e')),
                      );
                    }
                  } finally {
                    setState(() => _isLoading = false);
                  }
                },
                child: const Text('Confirm Booking'),
              ),
          ],
        ),
      ),
    );
  }
}
