import 'package:flutter/material.dart';
import 'package:em2rp/views/widgets/inputs/int_stepper_field.dart';
import 'package:em2rp/views/widgets/inputs/address_autocomplete_field.dart';
import 'package:em2rp/views/widgets/event_form/travel_cost_dialog.dart';

class EventDetailsSection extends StatefulWidget {
  final TextEditingController descriptionController;
  final TextEditingController installationController;
  final TextEditingController disassemblyController;
  final TextEditingController addressController;
  final TextEditingController jaugeController;
  final TextEditingController contactEmailController;
  final TextEditingController contactPhoneController;
  final bool isMobile;
  final VoidCallback onAnyFieldChanged;
  /// Callback appelé quand l'utilisateur sélectionne un itinéraire
  /// avec le prix total calculé (pour ajouter l'option FRAIS_KM)
  final void Function(double price)? onTravelCostSelected;

  const EventDetailsSection({
    super.key,
    required this.descriptionController,
    required this.installationController,
    required this.disassemblyController,
    required this.addressController,
    required this.jaugeController,
    required this.contactEmailController,
    required this.contactPhoneController,
    required this.isMobile,
    required this.onAnyFieldChanged,
    this.onTravelCostSelected,
  });

  @override
  State<EventDetailsSection> createState() => _EventDetailsSectionState();
}

class _EventDetailsSectionState extends State<EventDetailsSection> {
  int _descriptionMaxLines = 3;

  @override
  void initState() {
    super.initState();
    widget.descriptionController.addListener(_handleDescriptionChange);
  }

  @override
  void dispose() {
    widget.descriptionController.removeListener(_handleDescriptionChange);
    super.dispose();
  }

  void _handleDescriptionChange() {
    final lines = '\n'.allMatches(widget.descriptionController.text).length + 1;
    setState(() {
      _descriptionMaxLines = lines.clamp(3, 6);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // Description et champs de contact
        widget.isMobile
          ? _buildMobileLayout()
          : _buildDesktopLayout(),

        const SizedBox(height: 20),

        // Installation et démontage
        Row(
          children: [
            Expanded(
              child: IntStepperField(
                label: 'Installation (h)',
                controller: widget.installationController,
                min: 0,
                max: 99,
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: IntStepperField(
                label: 'Démontage (h)',
                controller: widget.disassemblyController,
                min: 0,
                max: 99,
              ),
            ),
          ],
        ),
        
        const SizedBox(height: 20),

        AddressAutocompleteField(
          controller: widget.addressController,
          label: 'Adresse*',
          validator: (v) => v == null || v.isEmpty ? 'Champ requis' : null,
          onSelected: (_) => widget.onAnyFieldChanged(),
        ),
        const SizedBox(height: 12),
        // Bouton calcul frais déplacement
        SizedBox(
          width: double.infinity,
          child: OutlinedButton.icon(
            icon: const Icon(Icons.route_outlined),
            label: const Text('Calculer les frais de déplacement'),
            style: OutlinedButton.styleFrom(
              foregroundColor: Colors.blueGrey[700],
              side: BorderSide(color: Colors.blueGrey[300]!),
              padding: const EdgeInsets.symmetric(vertical: 12),
            ),
            onPressed: () async {
              final address = widget.addressController.text.trim();
              if (address.isEmpty) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('Veuillez d\'abord renseigner l\'adresse de l\'événement.'),
                    backgroundColor: Colors.orange,
                  ),
                );
                return;
              }
              final price = await showTravelCostDialog(
                context: context,
                eventAddress: address,
              );
              if (price != null && widget.onTravelCostSelected != null) {
                widget.onTravelCostSelected!(price);
              }
            },
          ),
        ),
      ],
    );
  }

  Widget _buildMobileLayout() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        _buildDescriptionField(),
        const SizedBox(height: 16),
        _buildContactFields(),
      ],
    );
  }

  Widget _buildDesktopLayout() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(
          flex: 2,
          child: _buildDescriptionField(),
        ),
        const SizedBox(width: 16),
        Expanded(
          flex: 1,
          child: _buildContactFields(),
        ),
      ],
    );
  }

  Widget _buildDescriptionField() {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 200),
      constraints: BoxConstraints(
        minHeight: 48,
        maxHeight: widget.isMobile ? 48.0 * 20 : 48.0 * 10,
      ),
      child: TextFormField(
        controller: widget.descriptionController,
        minLines: 1,
        maxLines: _descriptionMaxLines > (widget.isMobile ? 20 : 10)
            ? (widget.isMobile ? 20 : 10)
            : _descriptionMaxLines,
        decoration: const InputDecoration(
          labelText: 'Description',
          border: OutlineInputBorder(),
          prefixIcon: Icon(Icons.description),
        ),
        onChanged: (_) => widget.onAnyFieldChanged(),
      ),
    );
  }

  Widget _buildContactFields() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        TextFormField(
          controller: widget.jaugeController,
          decoration: const InputDecoration(
            labelText: 'Jauge',
            border: OutlineInputBorder(),
            prefixIcon: Icon(Icons.people),
            hintText: 'Nombre de personnes',
          ),
          keyboardType: TextInputType.number,
          onChanged: (_) => widget.onAnyFieldChanged(),
        ),
        const SizedBox(height: 12),
        TextFormField(
          controller: widget.contactEmailController,
          decoration: const InputDecoration(
            labelText: 'Email de contact',
            border: OutlineInputBorder(),
            prefixIcon: Icon(Icons.email),
            hintText: 'contact@exemple.com',
          ),
          keyboardType: TextInputType.emailAddress,
          onChanged: (_) => widget.onAnyFieldChanged(),
        ),
        const SizedBox(height: 12),
        TextFormField(
          controller: widget.contactPhoneController,
          decoration: const InputDecoration(
            labelText: 'Téléphone de contact',
            border: OutlineInputBorder(),
            prefixIcon: Icon(Icons.phone),
            hintText: '06 12 34 56 78',
          ),
          keyboardType: TextInputType.phone,
          onChanged: (_) => widget.onAnyFieldChanged(),
        ),
      ],
    );
  }
}
