import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import '../../../core/models/customer.dart';
import '../providers/dashboard_providers.dart';

class CustomerFormScreen extends ConsumerStatefulWidget {
  final Customer? customer;

  const CustomerFormScreen({super.key, this.customer});

  @override
  ConsumerState<CustomerFormScreen> createState() => _CustomerFormScreenState();
}

class _CustomerFormScreenState extends ConsumerState<CustomerFormScreen> {
  final _formKey = GlobalKey<FormState>();
  bool _loading = false;

  final _firstName = TextEditingController();
  final _lastName = TextEditingController();
  final _email = TextEditingController();
  final _phone = TextEditingController();
  final _nationality = TextEditingController();
  DateTime? _dob;

  @override
  void initState() {
    super.initState();
    final c = widget.customer;
    if (c != null) {
      _firstName.text = c.firstName;
      _lastName.text = c.lastName;
      _email.text = c.email ?? '';
      _phone.text = c.phone ?? '';
      _nationality.text = c.nationality ?? '';
      _dob = c.dateOfBirth;
    }
  }

  @override
  void dispose() {
    for (final c in [_firstName, _lastName, _email, _phone, _nationality]) {
      c.dispose();
    }
    super.dispose();
  }

  Future<void> _pickDob() async {
    final picked = await showDatePicker(
      context: context,
      initialDate: _dob ?? DateTime(1990),
      firstDate: DateTime(1920),
      lastDate: DateTime.now().subtract(const Duration(days: 365 * 16)),
    );
    if (picked != null) setState(() => _dob = picked);
  }

  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) return;
    setState(() => _loading = true);
    try {
      final data = {
        'firstName': _firstName.text.trim(),
        'lastName': _lastName.text.trim(),
        if (_email.text.isNotEmpty) 'email': _email.text.trim(),
        if (_phone.text.isNotEmpty) 'phone': _phone.text.trim(),
        if (_nationality.text.isNotEmpty)
          'nationality': _nationality.text.trim(),
        if (_dob != null)
          'dateOfBirth':
              '${_dob!.toIso8601String().substring(0, 10)}T00:00:00.000Z',
      };
      final svc = ref.read(customerServiceProvider);
      if (widget.customer == null) {
        await svc.createCustomer(data);
      } else {
        await svc.updateCustomer(widget.customer!.id, data);
      }
      if (mounted) Navigator.of(context).pop(true);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('Error: $e')));
      }
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final isEdit = widget.customer != null;
    return Scaffold(
      appBar: AppBar(
        title: Text(isEdit ? 'Edit Customer' : 'New Customer'),
        actions: [
          if (_loading)
            const Padding(
              padding: EdgeInsets.all(16),
              child: SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(strokeWidth: 2)),
            )
          else
            TextButton(
              onPressed: _submit,
              child: const Text('Save'),
            ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            Card(
              child: Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                child: Column(
                  children: [
                    _field('First Name', _firstName, required: true),
                    _field('Last Name', _lastName, required: true),
                    _field('Email', _email,
                        inputType: TextInputType.emailAddress),
                    _field('Phone', _phone, inputType: TextInputType.phone),
                    _field('Nationality', _nationality),
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 8),
                      child: InkWell(
                        onTap: _pickDob,
                        child: InputDecorator(
                          decoration:
                              const InputDecoration(labelText: 'Date of Birth'),
                          child: Text(
                            _dob != null
                                ? DateFormat('MMM d, yyyy').format(_dob!)
                                : 'Tap to select',
                            style: TextStyle(
                              color: _dob != null
                                  ? null
                                  : const Color(0xFF9CA3AF),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: _loading ? null : _submit,
              style: ElevatedButton.styleFrom(
                minimumSize: const Size.fromHeight(48),
              ),
              child: Text(isEdit ? 'Save Changes' : 'Create Customer'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _field(String label, TextEditingController ctrl,
      {bool required = false, TextInputType? inputType}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: TextFormField(
        controller: ctrl,
        keyboardType: inputType,
        decoration: InputDecoration(labelText: label),
        validator: required
            ? (v) => v == null || v.isEmpty ? 'Required' : null
            : null,
      ),
    );
  }
}
