from django.conf import settings
from django.contrib import admin
from django.utils.html import format_html

from shortener.models import UrlData
from .models import Business, Industry, Product, Customer, SaleRecord, Reward, Redeem


# class ProductInline(admin.TabularInline):
#     model = Product
#     extra = 1

class IndustryAdmin(admin.ModelAdmin):
    fields = ['name']
    list_display = ['id', 'name', 'created_at']


class ProductAdmin(admin.ModelAdmin):
    list_display = ['id', 'name', 'industry', 'created_at']
    search_fields = ['name', ]
    list_filter = ['industry']


class BusinessAdmin(admin.ModelAdmin):
    list_display = ['id',
                    'country',
                    'industry',
                    'name',
                    'manager_full_name',
                    'manager_mobile',
                    'email',
                    'created_at']
    search_fields = ['name', 'manager_mobile', 'manager_full_name']
    ordering = ('-created_at',)

    fields = [
        "manager_full_name",
        "manager_mobile",
        "manager_email",
        "name",
        "loyalty_model",
        "point_amount_value",
        "country",
        "industry",
        "email",
        "phone",
        "address",
        "google_place_id",
        "address_link",
        "purchase_link",
        "web_site",
        "instagram",
        "icon",
        "empty_survey_link",
        "google_place_link",
    ]
    readonly_fields = [
        "empty_survey_link",
        "google_place_link",
    ]

    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        google_place_id = form.cleaned_data.get("google_place_id")
        if google_place_id:
            obj.google_link = f'https://search.google.com/local/writereview?placeid={google_place_id}'
        else:
            obj.google_link = ''
        obj.save()

    def empty_survey_link(self, obj: Business):
        try:
            url = f'{settings.RAPID_BASE_URL}survey?business={obj.id}&customer=empty'
            url_data = UrlData.objects.get(url=url)
            shorl_url = f'{settings.APP_SHORT_URL}u/{url_data.slug}'
        except UrlData.DoesNotExist:
            return '-'
        return format_html("<a href='{url}' target='_blank'>{url}</a>", url=shorl_url)

    def google_place_link(self, obj: Business):
        if obj.google_link:
            return format_html("<a href='{url}' target='_blank'>{url}</a>", url=obj.google_link)
        else:
            return '-'


class CustomerAdmin(admin.ModelAdmin):
    search_fields = ['id', 'full_name', ]
    list_filter = ['business']
    list_display = ['id',
                    'full_name',
                    'business',
                    'phone_verification',
                    'phone',
                    'created_at']
    readonly_fields = ['magic_link', 'acquisition_channel', 'id', ]

    def phone(self, obj):
        return f'+{obj.country_code}{obj.mobile}'

    def magic_link(self, obj: Customer):
        url = f'{settings.APP_BASE_URL}userverification?code={obj.validation_code}&redirect=/profile'
        return format_html("<a href='{url}' target='_blank'>{url}</a>", url=url)


class ProductInline(admin.TabularInline):
    model = SaleRecord.products.through
    extra = 0
    verbose_name = 'Product'
    verbose_name_plural = 'Products'


class SalesAdmin(admin.ModelAdmin):
    inlines = [ProductInline, ]
    list_filter = ['business']
    list_display = ['id',
                    'customer_id',
                    'customer',
                    'business',
                    'rate',
                    'is_verified',
                    'created_at',
                    'updated_at', ]
    exclude = ["products"]
    search_fields = ['customer__full_name', 'customer__business__name', ]


class RewardAdmin(admin.ModelAdmin):
    list_display = ['id',
                    'business',
                    'name',
                    'loyalty_weight',
                    'start_date',
                    'end_date',
                    'capacity',
                    'remaining',
                    'reusable',
                    'is_enabled',
                    'created_at']

    actions = ['make_enabled', 'make_disabled']

    def remaining(self, obj):
        if obj.capacity == 0:
            return 9999
        usage = Redeem.objects.filter(reward=obj).count()
        return obj.capacity - usage

    @admin.action(description="Mark selected rewards as enabled")
    def make_enabled(self, request, queryset):
        queryset.update(is_enabled=True)

    @admin.action(description="Mark selected rewards as disabled")
    def make_disabled(self, request, queryset):
        queryset.update(is_enabled=False)

    remaining.short_description = 'Remaining'


class RedeemAdmin(admin.ModelAdmin):
    list_display = ['id',
                    'customer',
                    'reward',
                    'created_at', ]


admin.site.register(Business, BusinessAdmin)
admin.site.register(Product, ProductAdmin)
admin.site.register(Industry, IndustryAdmin)
admin.site.register(Customer, CustomerAdmin)
admin.site.register(SaleRecord, SalesAdmin)
admin.site.register(Reward, RewardAdmin)
admin.site.register(Redeem, RedeemAdmin)
