import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class AddEventDialog extends StatefulWidget {
  const AddEventDialog({super.key});

  @override
  _AddEventDialogState createState() => _AddEventDialogState();
}

class _AddEventDialogState extends State<AddEventDialog> {
  final _formKey = GlobalKey<FormState>();
  String _title = '';
  String _description = '';
  DateTime? _selectedDate;
  String? _imagePath;
  String _location = '';
  String _category = '';
  String _link = '';
  LatLng? _selectedLatLng;

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(15.0),
      ),
      backgroundColor: const Color(0xFF2C2C3E),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildTitleField(),
              const SizedBox(height: 10),
              _buildDescriptionField(),
              const SizedBox(height: 10),
              _buildDatePicker(),
              const SizedBox(height: 10),
              _buildLocationField(context),
              const SizedBox(height: 10),
              _buildCategoryField(),
              const SizedBox(height: 10),
              _buildImagePicker(),
              const SizedBox(height: 10),
              _buildLinkField(),
              const SizedBox(height: 20),
              _buildSubmitButton(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTitleField() {
    return TextFormField(
      decoration: InputDecoration(
        labelText: 'Titre',
        labelStyle: const TextStyle(color: Colors.white70),
        filled: true,
        fillColor: Colors.white.withOpacity(0.1),
        border: const OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(10.0)),
          borderSide: BorderSide.none,
        ),
        prefixIcon: const Icon(Icons.title, color: Colors.white70),
      ),
      style: const TextStyle(color: Colors.white),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Veuillez entrer un titre';
        }
        return null;
      },
      onSaved: (value) {
        _title = value ?? '';
      },
    );
  }

  Widget _buildDescriptionField() {
    return TextFormField(
      decoration: InputDecoration(
        labelText: 'Description',
        labelStyle: const TextStyle(color: Colors.white70),
        filled: true,
        fillColor: Colors.white.withOpacity(0.1),
        border: const OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(10.0)),
          borderSide: BorderSide.none,
        ),
        prefixIcon: const Icon(Icons.description, color: Colors.white70),
      ),
      style: const TextStyle(color: Colors.white),
      maxLines: 3,
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Veuillez entrer une description';
        }
        return null;
      },
      onSaved: (value) {
        _description = value ?? '';
      },
    );
  }

  Widget _buildDatePicker() {
    return GestureDetector(
      onTap: () async {
        final DateTime? picked = await showDatePicker(
          context: context,
          initialDate: DateTime.now(),
          firstDate: DateTime.now(),
          lastDate: DateTime(2101),
        );
        if (picked != null && picked != _selectedDate) {
          setState(() {
            _selectedDate = picked;
          });
        }
      },
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.1),
          borderRadius: BorderRadius.circular(10.0),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              _selectedDate == null
                  ? 'Sélectionnez une date'
                  : '${_selectedDate!.day}/${_selectedDate!.month}/${_selectedDate!.year}',
              style: const TextStyle(color: Colors.white70),
            ),
            const Icon(Icons.calendar_today, color: Colors.white70),
          ],
        ),
      ),
    );
  }

  Widget _buildLocationField(BuildContext context) {
    return GestureDetector(
      onTap: () async {
        final LatLng? pickedLocation = await Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => const LocationPickerScreen(),
          ),
        );
        if (pickedLocation != null) {
          setState(() {
            _selectedLatLng = pickedLocation;
            _location = '${pickedLocation.latitude}, ${pickedLocation.longitude}';
          });
        }
      },
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.1),
          borderRadius: BorderRadius.circular(10.0),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              _selectedLatLng == null
                  ? 'Sélectionnez une localisation'
                  : 'Localisation: $_location',
              style: const TextStyle(color: Colors.white70),
            ),
            const Icon(Icons.location_on, color: Colors.white70),
          ],
        ),
      ),
    );
  }

  Widget _buildCategoryField() {
    return TextFormField(
      decoration: InputDecoration(
        labelText: 'Catégorie',
        labelStyle: const TextStyle(color: Colors.white70),
        filled: true,
        fillColor: Colors.white.withOpacity(0.1),
        border: const OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(10.0)),
          borderSide: BorderSide.none,
        ),
        prefixIcon: const Icon(Icons.category, color: Colors.white70),
      ),
      style: const TextStyle(color: Colors.white),
      onSaved: (value) {
        _category = value ?? '';
      },
    );
  }

  Widget _buildImagePicker() {
    return GestureDetector(
      onTap: () {
        // Logique pour sélectionner une image
      },
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.1),
          borderRadius: BorderRadius.circular(10.0),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              _imagePath == null ? 'Sélectionnez une image' : 'Image sélectionnée',
              style: const TextStyle(color: Colors.white70),
            ),
            const Icon(Icons.image, color: Colors.white70),
          ],
        ),
      ),
    );
  }

  Widget _buildLinkField() {
    return TextFormField(
      decoration: InputDecoration(
        labelText: 'Lien (optionnel)',
        labelStyle: const TextStyle(color: Colors.white70),
        filled: true,
        fillColor: Colors.white.withOpacity(0.1),
        border: const OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(10.0)),
          borderSide: BorderSide.none,
        ),
        prefixIcon: const Icon(Icons.link, color: Colors.white70),
      ),
      style: const TextStyle(color: Colors.white),
      onSaved: (value) {
        _link = value ?? '';
      },
    );
  }

  Widget _buildSubmitButton() {
    return ElevatedButton(
      onPressed: () {
        if (_formKey.currentState!.validate()) {
          _formKey.currentState!.save();
          // Logique pour soumettre les données
          Navigator.of(context).pop();
        }
      },
      style: ElevatedButton.styleFrom(
        backgroundColor: const Color(0xFF1DBF73),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8.0),
        ),
        padding: const EdgeInsets.symmetric(vertical: 12.0),
        minimumSize: const Size(double.infinity, 40),
      ),
      child: const Text('Ajouter l\'événement', style: TextStyle(color: Colors.white)),
    );
  }
}

class LocationPickerScreen extends StatelessWidget {
  const LocationPickerScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sélectionnez une localisation'),
        backgroundColor: const Color(0xFF1E1E2C),
      ),
      body: GoogleMap(
        initialCameraPosition: const CameraPosition(
          target: LatLng(48.8566, 2.3522), // Paris par défaut
          zoom: 12.0,
        ),
        markers: Set<Marker>.of(<Marker>[
          Marker(
            markerId: const MarkerId('selectedLocation'),
            position: LatLng(48.8566, 2.3522), // Position par défaut
            draggable: true,
            onDragEnd: (newPosition) {
              Navigator.of(context).pop(newPosition);
            },
          )
        ]),
        onTap: (position) {
          Navigator.of(context).pop(position);
        },
      ),
    );
  }
}
