"""
Widgets personnalises pour l'admin Django.
"""
from django import forms
from django.utils.safestring import mark_safe


class MapPickerWidget(forms.MultiWidget):
    """
    Widget pour selectionner des coordonnees GPS sur une carte Leaflet.
    Combine deux champs (latitude, longitude) en un seul widget avec carte.
    """

    template_name = 'config/widgets/map_picker.html'

    class Media:
        css = {
            'all': (
                'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css',
                'config/css/map_picker.css',
            )
        }
        js = (
            'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js',
            'config/js/map_picker.js',
        )

    def __init__(self, attrs=None):
        widgets = [
            forms.NumberInput(attrs={
                'step': '0.000001',
                'class': 'map-picker-lat',
                'placeholder': 'Latitude',
            }),
            forms.NumberInput(attrs={
                'step': '0.000001',
                'class': 'map-picker-lng',
                'placeholder': 'Longitude',
            }),
        ]
        super().__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            return [value.get('lat'), value.get('lng')]
        return [None, None]

    def value_from_datadict(self, data, files, name):
        lat = data.get(f'{name}_0')
        lng = data.get(f'{name}_1')
        return [lat, lng]


class LatLongWidget(forms.TextInput):
    """
    Widget simple pour un champ lat/long avec bouton pour ouvrir la carte.
    S'utilise sur un seul champ (latitude ou longitude).
    """

    class Media:
        css = {
            'all': (
                'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css',
                'config/css/map_picker.css',
            )
        }
        js = (
            'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js',
            'config/js/map_picker.js',
        )

    def __init__(self, lat_field=None, lng_field=None, attrs=None):
        self.lat_field = lat_field
        self.lng_field = lng_field
        default_attrs = {
            'class': 'vTextField map-coord-field',
            'step': '0.000001',
        }
        if attrs:
            default_attrs.update(attrs)
        super().__init__(attrs=default_attrs)

    def render(self, name, value, attrs=None, renderer=None):
        # Determiner si c'est le champ latitude ou longitude
        is_lat = 'latitude' in name.lower() or 'lat' in name.lower()

        # Trouver le nom de l'autre champ
        if is_lat:
            other_field = self.lng_field or name.replace('latitude', 'longitude').replace('lat', 'lng')
            field_type = 'lat'
        else:
            other_field = self.lat_field or name.replace('longitude', 'latitude').replace('lng', 'lat')
            field_type = 'lng'

        # Ajouter les attributs data pour le JS
        if attrs is None:
            attrs = {}
        attrs['data-field-type'] = field_type
        attrs['data-other-field'] = other_field

        # Rendu du champ input
        input_html = super().render(name, value, attrs, renderer)

        # Bouton pour ouvrir la carte (seulement sur le champ latitude)
        if is_lat:
            button_html = f'''
            <button type="button"
                    class="map-picker-btn"
                    data-lat-field="id_{name}"
                    data-lng-field="id_{other_field}"
                    title="Choisir sur la carte">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                    <circle cx="12" cy="10" r="3"></circle>
                </svg>
                Carte
            </button>
            '''
            return mark_safe(f'<div class="map-picker-wrapper">{input_html}{button_html}</div>')

        return input_html


class IconPickerWidget(forms.Select):
    """
    Widget de sélection d'icônes visuel.
    Affiche les icônes FontAwesome de manière visuelle dans un sélecteur.
    """
    template_name = 'admin/widgets/icon_picker.html'

    class Media:
        css = {
            'all': (
                'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css',
                'admin/css/icon_picker.css',
            )
        }
        js = (
            'admin/js/icon_picker.js',
        )

    def __init__(self, attrs=None):
        default_attrs = {'class': 'icon-picker-select'}
        if attrs:
            default_attrs.update(attrs)
        super().__init__(attrs=default_attrs)

    def render(self, name, value, attrs=None, renderer=None):
        from django.template.loader import render_to_string
        from config.models import Icon, Icongroup

        # Récupérer les icônes groupées
        icons_by_group = {}
        for group in Icongroup.objects.all().order_by('libelle'):
            icons = Icon.objects.filter(group=group).order_by('libelle')
            if icons.exists():
                icons_by_group[group] = icons

        # Icône sélectionnée
        selected_icon = None
        if value:
            try:
                selected_icon = Icon.objects.select_related('group').get(pk=value)
            except Icon.DoesNotExist:
                pass

        widget_id = attrs.get('id', name) if attrs else name

        context = {
            'name': name,
            'value': value,
            'icons_by_group': icons_by_group,
            'selected_icon': selected_icon,
            'attrs': self.build_attrs(attrs) if attrs else {},
            'widget_id': widget_id,
        }

        return mark_safe(render_to_string(self.template_name, context))
