from django.contrib import admin
from django.db.models import Q
from django.utils.html import format_html

from accounts.models import Profile


class GPSAvailabilityFilter(admin.SimpleListFilter):
    title = 'GPS availability'
    parameter_name = 'gps'

    def lookups(self, request, model_admin):
        return (
            ('yes', 'With GPS'),
            ('no', 'Manual only'),
        )

    def queryset(self, request, queryset):
        if self.value() == 'yes':
            return queryset.filter(latitude__isnull=False, longitude__isnull=False)
        if self.value() == 'no':
            return queryset.filter(Q(latitude__isnull=True) | Q(longitude__isnull=True))
        return queryset


@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
    list_display = (
        'user',
        'delivery_readiness',
        'phone',
        'short_location',
        'has_precise_location',
        'location_updated_at',
        'is_seller',
        'image_preview',
    )
    list_select_related = ('user',)
    search_fields = ('user__username', 'user__email', 'phone', 'location_label', 'default_address')
    list_filter = ('is_seller', GPSAvailabilityFilter, 'location_updated_at')
    readonly_fields = ('location_updated_at', 'image_preview', 'maps_link')
    autocomplete_fields = ('user',)
    fieldsets = (
        ('Account', {'fields': ('user', 'is_seller')}),
        ('Delivery defaults', {'fields': ('phone', 'location_label', 'default_address')}),
        ('GPS location', {'fields': ('latitude', 'longitude', 'location_accuracy_m', 'location_updated_at', 'maps_link')}),
        ('Profile details', {'fields': ('image', 'image_preview', 'bio')}),
    )

    @admin.display(description='Delivery readiness')
    def delivery_readiness(self, obj):
        missing = []
        if not obj.phone:
            missing.append('phone')
        if not obj.formatted_delivery_address:
            missing.append('address')
        if not obj.has_precise_location:
            missing.append('GPS')
        if not missing:
            return 'Complete'
        return 'Missing ' + ', '.join(missing)

    @admin.display(description='Location')
    def short_location(self, obj):
        return obj.short_location or '-'

    @admin.display(boolean=True, description='GPS')
    def has_precise_location(self, obj):
        return obj.has_precise_location

    @admin.display(description='Map')
    def maps_link(self, obj):
        if not obj.has_precise_location:
            return '-'
        return format_html(
            '<a href="https://maps.google.com/?q={},{}" target="_blank" rel="noopener">Open map</a>',
            obj.latitude,
            obj.longitude,
        )

    @admin.display(description='Image')
    def image_preview(self, obj):
        if obj.image:
            return format_html(
                '<img src="{}" width="44" height="44" style="border-radius: 50%; object-fit: cover;" />',
                obj.image.url,
            )
        return 'No image'
