from django import forms
from django.contrib import admin
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from shop.views import send_ticket_reply_email, send_ticket_reply_whatsapp
from .models import BanshixContact, Category, InventoryLog, ProductImage, Product, ProductFeature, ProductViewLog, Order, ProductVariant, Wishlist, OfferRequest, TicketReply, Review, ChatMessage, Ticket, Profile, Discount, ProductVideo, StockAdjustment, Cart, CartItem, PaymentLog, OrderItem
from django.utils.text import slugify
from django.contrib.admin import AdminSite
from django_ckeditor_5.widgets import CKEditor5Widget

User=get_user_model()
class BanshiMartAdminSite(AdminSite):
    site_header = _("BanshiMart Admin")
    site_title = _("BanshiMart Administration")
    index_title = _("Dashboard")
    site_url = "/"  # Link back to your main site

    def get_app_list(self, request):
        app_list = super().get_app_list(request)
        # Optional: Reorder apps
        order = ['shop', 'auth']
        app_list.sort(key=lambda x: order.index(x['app_label']) if x['app_label'] in order else 99)
        return app_list

# Replace default admin site
admin_site = BanshiMartAdminSite(name='admin')


class BanshixContactForm(forms.ModelForm):
    emails_text = forms.CharField(
        widget=forms.Textarea(attrs={'rows': 3, 'placeholder': 'Enter one email per line'}),
        required=False,
        help_text="Enter multiple email addresses, one per line."
    )

    class Meta:
        model = BanshixContact
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance and self.instance.pk and self.instance.emails:
            # Convert JSON list to newline-separated text
            self.fields['emails_text'].initial = '\n'.join(self.instance.emails)

    def save(self, commit=True):
        instance = super().save(commit=False)
        emails_text = self.cleaned_data.get('emails_text', '')
        # Convert newline-separated text to JSON list
        if emails_text.strip():
            instance.emails = [email.strip() for email in emails_text.split('\n') if email.strip()]
        else:
            instance.emails = None
        if commit:
            instance.save()
        return instance


class ProductFeatureInline(admin.TabularInline):
    model = ProductFeature
    extra = 3
    fields = ('name', 'value')
    verbose_name = 'Feature'
    verbose_name_plural = 'Product Features'


class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False

class CustomUserAdmin(UserAdmin):
    inlines = (ProfileInline,)


@admin.register(Ticket)
class TicketAdmin(admin.ModelAdmin):
    list_display = ('id', 'user', 'subject', 'status', 'priority', 'created_at')
    list_filter = ('status', 'priority', 'created_at')
    search_fields = ('user__username', 'subject', 'description')
    readonly_fields = ('ai_chat_session_id', 'created_at', 'updated_at')
    
    formfield_overrides = {
        Ticket.description: {'widget': CKEditor5Widget(config_name='extends')},
    }
    
    actions = ['reply_via_email', 'reply_via_whatsapp']

    change_form_template = 'admin/shop/ticket/change_form.html'  # We'll create this
    
    def reply_via_email(self, request, queryset):
        if len(queryset) > 1:
            self.message_user(request, "Please select only one ticket for reply.", level='warning')
            return
        ticket = queryset[0]
        
        # Simple form simulation — in real production, use a custom admin form
        # For now, we can redirect to a custom reply view or use a quick message
        # Here we show a basic implementation (you can expand with a form later)
        reply_text = "Dear customer, thank you for your patience. Our team is looking into your issue and will provide an update within 24 hours."
        
        send_ticket_reply_email(ticket, reply_text)
        ticket.status = 'In Progress'  # Auto-update status
        ticket.save()
        
        self.message_user(request, f"Email reply sent successfully for Ticket #{ticket.id}")
    
    reply_via_email.short_description = "Reply to selected ticket via Email"

    def reply_via_whatsapp(self, request, queryset):
        if len(queryset) > 1:
            self.message_user(request, "Please select only one ticket for reply.", level='warning')
            return
        ticket = queryset[0]
        
        reply_text = "Hello! We have received your escalation. Our support team will contact you shortly on WhatsApp or call. Ticket status updated."
        
        success = send_ticket_reply_whatsapp(ticket, reply_text)
        if success:
            ticket.status = 'In Progress'
            ticket.save()
            self.message_user(request, f"WhatsApp reply sent for Ticket #{ticket.id}")
        else:
            self.message_user(request, f"Could not send WhatsApp (phone missing?) for Ticket #{ticket.id}", level='error')
    
    reply_via_whatsapp.short_description = "Reply to selected ticket via WhatsApp"


class ProductImageInline(admin.TabularInline):
    model = ProductImage
    extra = 10                         # Allow 10 empty slots for new images
    max_num = None                     # Remove the limit on total images (None = unlimited)
    fields = ('image_preview', 'image', 'alt_text', 'is_primary', 'created_at')
    readonly_fields = ('image_preview', 'created_at')
    ordering = ('-is_primary', 'created_at')
    
    def image_preview(self, obj):
        if obj.image:
            return format_html(
                '<img src="{}" style="max-height: 85px; border-radius: 8px; border: 2px solid #eee;" />',
                obj.image.url
            )
        return format_html('<span class="text-muted">No image uploaded</span>')
    
    image_preview.short_description = 'Preview'

    # Make the form more user-friendly
    formfield_overrides = {
        ProductImage.image: {'widget': admin.widgets.AdminFileWidget},
    }


class ProductVideoInline(admin.TabularInline):
    model = ProductVideo
    extra = 1
    max_num = 5
    fields = ('video', 'title', 'is_primary', 'created_at')
    readonly_fields = ('created_at',)
    ordering = ('-is_primary', 'created_at')


class ProductVariantInline(admin.TabularInline):
    model = ProductVariant
    extra = 3
    fields = ('sku', 'price', 'stock', 'is_active', 'attributes')
    filter_horizontal = ('attributes',)

@admin.register(InventoryLog)
class InventoryLogAdmin(admin.ModelAdmin):
    list_display = ('product', 'action', 'quantity', 'previous_stock', 'new_stock', 'performed_by', 'created_at')
    list_filter = ('action', 'created_at')
    search_fields = ('product__name', 'notes')
    readonly_fields = ('previous_stock', 'new_stock')
    ordering = ('-created_at',)
    
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ('name', 'category', 'price', 'stock', 'view_count', 'allow_customer_offer', 'main_image_preview', 'created_at')
    list_filter = ('category', 'created_at', 'stock', 'allow_customer_offer')
    search_fields = ('name', 'description')
    list_editable = ('price', 'stock', 'allow_customer_offer')
    ordering = ('-created_at',)
    
    prepopulated_fields = {'slug': ('name',)}
    
    fieldsets = (
        (None, {
            'fields': ('name', 'slug', 'category', 'description')
        }),
        ('Pricing & Inventory', {
            'fields': ('price', 'stock', 'allow_customer_offer', 'min_offer_price')
        }),
    )
    
    formfield_overrides = {
        Product.description: {'widget': CKEditor5Widget(config_name='extends')},
    }
    
    # Add nice inline editors for images, variants, and product features
    inlines = [ProductFeatureInline, ProductImageInline, ProductVideoInline, ProductVariantInline]
    
    
    def generate_barcodes(self, request, queryset):
        for product in queryset:
            product.generate_barcode()
            product.save()
        self.message_user(request, "Barcodes and QR codes generated successfully.")

    generate_barcodes.short_description = "Generate Barcode & QR Code for selected products"

    def low_stock_alert(self, obj):
        if obj.stock <= 5:
            return format_html('<span class="badge bg-danger">Low Stock: {}</span>', obj.stock)
        elif obj.stock <= 20:
            return format_html('<span class="badge bg-warning">Low: {}</span>', obj.stock)
        return format_html('<span class="badge bg-success">{}</span>', obj.stock)
    
    low_stock_alert.short_description = 'Stock Status'
    

    def main_image_preview(self, obj):
        primary = obj.images.filter(is_primary=True).first()
        image = primary or obj.images.first()
        if image and image.image:
            return format_html(
                '<img src="{}" style="max-height: 65px; border-radius: 6px; border: 1px solid #ddd;" />',
                image.image.url
            )
        return format_html('<span class="text-muted small">No image</span>')

    main_image_preview.short_description = 'Main Image'

    def restock_selected(self, request, queryset):
        for product in queryset:
            old_stock = product.stock
            product.stock += 50
            product.save()
            InventoryLog.objects.create(
                product=product,
                action='restock',
                quantity=50,
                previous_stock=old_stock,
                new_stock=product.stock,
                notes='Bulk restock from admin',
                performed_by=request.user
            )
        self.message_user(request, "Selected products have been restocked by 50 units.")

    restock_selected.short_description = "Restock selected products (+50)"

    # Custom actions
    actions = ['restock_selected']


@admin.register(ProductViewLog)
class ProductViewLogAdmin(admin.ModelAdmin):
    list_display = ('product', 'user', 'session_key', 'ip_address', 'referer', 'viewed_at')
    list_filter = ('viewed_at', 'product')
    search_fields = ('product__name', 'user__username', 'session_key', 'ip_address', 'referer')
    readonly_fields = ('product', 'user', 'session_key', 'ip_address', 'referer', 'user_agent', 'viewed_at')
    date_hierarchy = 'viewed_at'

    # No write actions for view logs; keep logs read-only.

    # Auto-generate unique slug
    def save_model(self, request, obj, form, change):
        if not obj.slug and obj.name:
            from django.utils.text import slugify
            base_slug = slugify(obj.name)
            obj.slug = base_slug
            counter = 1
            while Product.objects.filter(slug=obj.slug).exclude(pk=obj.pk).exists():
                obj.slug = f"{base_slug}-{counter}"
                counter += 1
        super().save_model(request, obj, form, change)


@admin.register(OfferRequest)
class OfferRequestAdmin(admin.ModelAdmin):
    list_display = ('id', 'product', 'user', 'offered_price', 'status', 'created_at')
    list_filter = ('status', 'created_at')
    search_fields = ('product__name', 'user__username', 'message')
    readonly_fields = ('product', 'user', 'offered_price', 'message', 'created_at', 'updated_at')
    fields = ('product', 'user', 'offered_price', 'message', 'status', 'admin_response', 'created_at', 'updated_at')
    
    formfield_overrides = {
        OfferRequest.message: {'widget': CKEditor5Widget(config_name='extends')},
        OfferRequest.admin_response: {'widget': CKEditor5Widget(config_name='extends')},
    }


# ====================== ORDER ADMIN ======================
@admin.register(Order, site=admin_site)
class OrderAdmin(admin.ModelAdmin):
    list_display = ('id', 'user', 'total', 'status', 'created_at')
    list_filter = ('status', 'created_at')
    search_fields = ('id', 'user__username')
    readonly_fields = ('total',)
         
        
# ====================== CATEGORY ADMIN ======================
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'slug', 'product_count')
    list_filter = ('name',)
    search_fields = ('name', 'slug')
    prepopulated_fields = {'slug': ('name',)}   # Auto-generate slug from name
    ordering = ('name',)
    
    formfield_overrides = {
        Category.description: {'widget': CKEditor5Widget(config_name='extends')},
    }
    
    # Show number of products in each category
    def product_count(self, obj):
        return obj.products.count()
    
    product_count.short_description = 'Products'
    product_count.admin_order_field = 'products__count'  # Enables sorting

    # Optional: Make the change form nicer
    fieldsets = (
        (None, {
            'fields': ('name', 'slug')
        }),
        ('Additional Info', {
            'fields': ('description',),   # Add description field if you have it
            'classes': ('collapse',)
        }),
    )

             
# ====================== DISCOUNT ADMIN ======================
@admin.register(Discount)
class DiscountAdmin(admin.ModelAdmin):
    list_display = ('name', 'discount_type', 'discount_value', 'status_badge', 'usage_display', 'created_at')
    list_filter = ('is_active', 'discount_type', 'created_at')
    search_fields = ('name', 'code', 'description')
    readonly_fields = ('usage_count', 'created_at', 'updated_at')
    filter_horizontal = ('products', 'categories')
    
    formfield_overrides = {
        Discount.description: {'widget': CKEditor5Widget(config_name='extends')},
    }
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'code', 'description', 'created_by')
        }),
        ('Discount Details', {
            'fields': ('discount_type', 'discount_value', 'min_purchase')
        }),
        ('Applicability', {
            'fields': ('products', 'categories'),
            'description': 'Leave both empty to apply to all products'
        }),
        ('Availability', {
            'fields': ('is_active', 'start_date', 'end_date')
        }),
        ('Usage Limits', {
            'fields': ('usage_limit', 'usage_count', 'usage_limit_per_user')
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def status_badge(self, obj):
        if obj.is_valid():
            return format_html('<span class="badge bg-success">Active</span>')
        else:
            return format_html('<span class="badge bg-danger">Inactive</span>')
    
    status_badge.short_description = 'Status'
    
    def usage_display(self, obj):
        if obj.usage_limit:
            return f"{obj.usage_count} / {obj.usage_limit}"
        return f"{obj.usage_count} (unlimited)"
    
    usage_display.short_description = 'Usage'
    
    def save_model(self, request, obj, form, change):
        if not change:  # Creating new discount
            obj.created_by = request.user
        super().save_model(request, obj, form, change)



@admin.register(Review)
class ReviewAdmin(admin.ModelAdmin):
    list_display = ('user', 'product', 'rating', 'created_at')
    list_filter = ('rating', 'created_at')
    search_fields = ('user__username', 'product__name', 'comment')
    readonly_fields = ('user', 'product', 'rating', 'created_at', 'updated_at')
    
    formfield_overrides = {
        Review.comment: {'widget': CKEditor5Widget(config_name='extends')},
    }

# Custom admin for BanshixContact with email handling
@admin.register(BanshixContact)
class BanshixContactAdmin(admin.ModelAdmin):
    form = BanshixContactForm
    list_display = ('user', 'phone', 'is_active', 'email_count', 'facebook', 'twitter', 'instagram')
    list_editable = ('is_active',)
    list_filter = ('is_active', 'facebook', 'twitter')
    search_fields = ('user__username', 'phone', 'address')
    readonly_fields = ('user',)

    def email_count(self, obj):
        if obj.emails:
            return len(obj.emails)
        return 0
    email_count.short_description = 'Email Count'

    fieldsets = (
        (None, {
            'fields': ('user', 'phone', 'address', 'is_active')
        }),
        ('Emails', {
            'fields': ('emails_text',),
            'description': 'Enter multiple email addresses, one per line.'
        }),
        ('Social Media', {
            'fields': ('facebook', 'twitter', 'instagram', 'linkedin', 'youtube'),
            'classes': ('collapse',)
        }),
        ('Other', {
            'fields': ('whatsapp',),
            'classes': ('collapse',)
        }),
    )

# Register additional models
admin.site.register(StockAdjustment)
admin.site.register(Cart)
admin.site.register(CartItem)
admin.site.register(PaymentLog)
admin.site.register(Profile)
admin.site.register(OrderItem)
admin.site.register(TicketReply)
admin.site.register([Wishlist, ChatMessage, ProductFeature, ProductVariant,])