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

from .models import (
    UserModel as User,
    OTPModel as OTPCode,
    SessionModel as Session,
    SMSModel as MessageSMS,
    OrgModel as Organization,
    ChatPermModel as ChatRoomPermissions,
    ChatRoomModel as ChatRoom,
    MsgModel as MessageChat,
    WalletModel as Wallet,
    PaymentModel as Payment
)

from django.contrib.auth.models import User as DjangoUser


# --- Inlines ---
class MessageChatInline(admin.TabularInline):
    model = MessageChat
    extra = 0
    readonly_fields = ('timestamp',)

class WalletInline(admin.StackedInline):
    model = Wallet
    can_delete = False
    verbose_name_plural = 'Wallet Info'



class CustomUserAdmin(admin.ModelAdmin):
    inlines = [WalletInline]

admin.site.unregister(DjangoUser)
admin.site.register(DjangoUser, CustomUserAdmin)

# --- Admins ---

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    list_display = ('user', 'mobile', 'group')
    search_fields = ('user__username', 'mobile')
    list_filter = ('group',)
    # inlines = [WalletInline]

@admin.register(OTPCode)
class OTPCodeAdmin(admin.ModelAdmin):
    list_display = ('mobile_number', 'code', 'created_at')
    search_fields = ('mobile_number', 'code')
    readonly_fields = ('created_at',)

@admin.register(Session)
class SessionAdmin(admin.ModelAdmin):
    list_display = ('user', 'ip_address', 'device', 'browser', 'last_seen')
    search_fields = ('user__username', 'ip_address', 'session_key')
    list_filter = ('created_at', 'browser')
    readonly_fields = ('created_at', 'last_seen')

@admin.register(MessageSMS)
class MessageSMSAdmin(admin.ModelAdmin):
    list_display = ('mobile_number', '_from', 'status', 'created_at')
    list_filter = ('status', 'created_at')
    search_fields = ('mobile_number', 'message_text')

@admin.register(Organization)
class OrganizationAdmin(admin.ModelAdmin):
    list_display = ('name', 'uname', 'owner', 'created_at')
    search_fields = ('name', 'uname', 'owner__username')

@admin.register(ChatRoomPermissions)
class ChatRoomPermissionsAdmin(admin.ModelAdmin):
    list_display = ('get_users', 'access')
    list_filter = ('access',)
    
    def get_users(self, obj):
        return ", ".join([u.username for u in obj.user.all()])
    get_users.short_description = 'Users'

@admin.register(ChatRoom)
class ChatRoomAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'status', 'organization', 'created_at')
    list_filter = ('status', 'created_at')
    search_fields = ('name', 'descriptions')
    filter_horizontal = ('users', 'pinned_for', 'permissions', 'banneds') # برای انتخاب راحت‌تر ManyToMany
    inlines = [MessageChatInline]

@admin.register(MessageChat)
class MessageChatAdmin(admin.ModelAdmin):
    list_display = ('sender', 'chat_room', 'short_text', 'timestamp')
    list_filter = ('timestamp',)
    search_fields = ('text', 'sender__username')

    def short_text(self, obj):
        return obj.text[:50] + '...' if len(obj.text) > 50 else obj.text

@admin.register(Wallet)
class WalletAdmin(admin.ModelAdmin):
    list_display = ('user', 'amount', 'updated_at')
    search_fields = ('user__username',)
    readonly_fields = ('created_at', 'updated_at')

@admin.register(Payment)
class PaymentAdmin(admin.ModelAdmin):
    list_display = ('order_id', 'user', 'colored_status', 'amount', 'gateway_title', 'created_at')
    list_filter = ('status', 'pay_mode', 'gateway_title', 'created_at')
    search_fields = ('order_id', 'authority', 'ref_id', 'user__username', 'mobile')
    readonly_fields = ('created_at', 'updated_at', 'data', 'data_verify')
    
    fieldsets = (
        ('Basic Info', {
            'fields': ('status', 'user', 'pay_mode', 'amount', 'order_id', 'description')
        }),
        ('Contact Info', {
            'fields': ('mobile', 'email', 'callback_url')
        }),
        ('Gateway Info', {
            'fields': ('gateway_title', 'gateway_url', 'authority', 'ref_id', 'status_code', 'message')
        }),
        ('Card & Security', {
            'classes': ('collapse',), # این بخش به صورت تاشو نمایش داده می‌شود
            'fields': ('card_hash', 'card_pan', 'data', 'data_verify', 'paid_at')
        }),
    )

    def colored_status(self, obj):
        """رنگی کردن وضعیت پرداخت برای تشخیص سریع‌تر"""
        colors = {
            'paid': 'green',
            'unpaid': 'orange',
            'canceled': 'red',
            'refounded': 'blue',
        }
        return format_html(
            '<b style="color:{};">{}</b>',
            colors.get(obj.status, 'black'),
            obj.status
        )
    colored_status.short_description = 'Status'