# companies/admin.py
from django.contrib import admin
from .models import Plan, Company, CompanySettings


class CompanySettingsInline(admin.StackedInline):
    model = CompanySettings
    extra = 0
    can_delete = False
    fieldsets = (
        ("POS & Stock", {"fields": (
            "pos_interface_mode", "enable_camera_scanner",
            "enable_unlimited_stock",
        )}),
        ("Feature Overrides (Per-Company)", {
            "fields": ("enable_audit_log",),
            "description": "Enable these features for this company regardless of their plan.",
        }),
        ("Currency & Tax", {"fields": (
            "currency", "currency_symbol", "decimal_places", "use_comma_separator", "vat_rate",
        )}),
        ("Receipt", {"fields": ("receipt_header", "receipt_footer", "show_receipt_logo")}),
        ("Visibility Toggles", {"fields": ("show_inventory", "show_receipts", "show_analytics", "show_reports")}),
        ("WhatsApp / SMS (requires plan feature + global activation)", {
            "fields": (
                "whatsapp_api_url", "whatsapp_api_key",
                "sms_api_key", "sms_sender_id",
                "send_receipt_via_whatsapp", "send_credit_via_whatsapp", "send_lowstock_via_whatsapp",
            ),
            "classes": ("collapse",),
        }),
        ("Thermal Printing", {
            "fields": ("thermal_printer_name", "receipt_width_mm", "auto_print_on_sale"),
            "classes": ("collapse",),
        }),
        ("Security (2FA)", {
            "fields": ("require_2fa_for_admin", "require_2fa_for_manager"),
            "classes": ("collapse",),
        }),
    )


@admin.register(Plan)
class PlanAdmin(admin.ModelAdmin):
    list_display = (
        "name", "price_monthly", "max_products", "max_staff", "max_branches",
        "feature_pos_terminal_v2_grid", "feature_barcode_pos", "feature_multi_branch",
        "feature_audit_logs", "is_public", "is_active",
    )
    list_filter = ("is_active", "is_public")
    list_editable = ("is_public", "is_active")
    search_fields = ("name",)
    fieldsets = (
        ("Visibility & Ordering", {
            "fields": ("is_public", "display_order"),
            "description": (
                "✅ is_public = ON → plan appears on ALL company subscription/upgrade pages. "
                "❌ is_public = OFF → plan is HIDDEN from companies but can still be manually assigned by an admin."
            ),
        }),
        ("Basic Info", {"fields": ("name", "price_monthly", "price_bimonthly", "price_trimonthly", "price_yearly", "is_active")}),
        ("Usage Limits", {"fields": (
            "max_orders_per_day", "max_products", "max_customers",
            "max_categories", "max_staff", "max_branches",
        )}),
        ("Features — POS & Stock", {"fields": (
            "feature_pos_terminal_v1", "feature_pos_terminal_v2_grid",
            "feature_barcode_pos", "feature_bulk_import", "feature_export",
            "feature_multi_branch", "feature_wholesale_price",
            "feature_discount", "feature_promo", "feature_credit_sales",
        )}),
        ("Features — Reporting & Security", {"fields": (
            "feature_profit_loss", "feature_audit_logs", "feature_suspicious_activity",
            "feature_advanced_reports", "feature_2fa",
        )}),
        ("Features — Phase 2 (Advanced)", {"fields": (
            "feature_product_variants",
            "feature_stock_transfers",
            "feature_price_lists",
            "feature_bundles",
            "feature_online_store",
            "feature_whatsapp_sms",
        ), "description": "Phase 2 features. Enable per subscription tier."}),
        ("Mobile & Integrations", {"fields": (
            "feature_android_app",
        )}),
    )


@admin.register(Company)
class CompanyAdmin(admin.ModelAdmin):
    list_display = ("name", "slug", "plan", "is_active", "expiry_date", "created_at")
    list_filter = ("is_active", "plan")
    search_fields = ("name", "slug", "email", "phone")
    prepopulated_fields = {"slug": ("name",)}
    inlines = [CompanySettingsInline]
    readonly_fields = ("created_at", "updated_at")
    fieldsets = (
        ("Company Info", {"fields": ("name", "slug", "email", "phone", "address", "logo")}),
        ("Subscription", {"fields": ("plan", "is_active", "activation_code", "expiry_date")}),
        ("Timestamps", {"fields": ("created_at", "updated_at"), "classes": ("collapse",)}),
    )
    list_display = ("name", "slug", "plan", "is_active", "expiry_date", "created_at", "action_import_db")

    def get_urls(self):
        from django.urls import path
        urls = super().get_urls()
        custom_urls = [
            path('<int:company_id>/import_db/', self.admin_site.admin_view(self.import_db_view), name='company-import-db'),
        ]
        return custom_urls + urls

    def import_db_view(self, request, company_id):
        from django.shortcuts import render, redirect
        from django.contrib import messages
        from django.core.files.storage import FileSystemStorage
        from .utils import parse_legacy_sql_and_import
        
        company = self.get_object(request, company_id)
        if request.method == 'POST':
            sql_file = request.FILES.get('sql_file')
            if sql_file:
                fs = FileSystemStorage()
                filename = fs.save(sql_file.name, sql_file)
                try:
                    summary, stats = parse_legacy_sql_and_import(fs.path(filename), company)
                    messages.success(request, summary)
                    if stats.get('errors'):
                        for err in stats['errors'][:5]:
                            messages.warning(request, f"⚠️ {err}")
                except Exception as e:
                    messages.error(request, f"Error parsing SQL file: {e}")
                fs.delete(filename)
                return redirect('admin:companies_company_change', company_id)
            else:
                messages.error(request, "No file uploaded")
                
        context = dict(
            self.admin_site.each_context(request),
            company=company,
            opts=self.model._meta,
        )
        return render(request, 'admin/import_db.html', context)

    def action_import_db(self, obj):
        from django.utils.html import format_html
        return format_html('<a class="button" href="{}/import_db/">Import Legacy DB</a>', obj.pk)
    action_import_db.short_description = 'Import DB'


@admin.register(CompanySettings)
class CompanySettingsAdmin(admin.ModelAdmin):
    list_display = ("company", "business_name", "currency", "pos_interface_mode")
    search_fields = ("company__name", "business_name")


# ─────────────────────────────────────────────────────────────────────────────
# SUPERADMIN 2FA ADMIN
# ─────────────────────────────────────────────────────────────────────────────

from .models import SuperAdmin2FA


@admin.register(SuperAdmin2FA)
class SuperAdmin2FAAdmin(admin.ModelAdmin):
    list_display  = ('user', 'is_enabled', 'method', 'updated_at')
    list_filter   = ('is_enabled', 'method')
    list_editable = ('is_enabled', 'method')
    search_fields = ('user__username', 'user__email')
    readonly_fields = ('totp_secret_display', 'qr_code_display', 'created_at', 'updated_at')

    fieldsets = (
        ('Account', {
            'fields': ('user',),
        }),
        ('2FA Configuration', {
            'fields': ('is_enabled', 'method'),
            'description': (
                '⚠️ Select the method first, then Save. '
                'If you choose Google Authenticator, a QR code will appear below for scanning.'
            ),
        }),
        ('Google Authenticator Setup', {
            'fields': ('totp_secret_display', 'qr_code_display'),
            'description': (
                'Scan the QR code below with Google Authenticator, Authy, or any TOTP app. '
                'Only visible when method = Google Authenticator.'
            ),
            'classes': ('collapse',),
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',),
        }),
    )

    def totp_secret_display(self, obj):
        from django.utils.html import format_html
        if not obj.pk or obj.method != SuperAdmin2FA.METHOD_TOTP:
            return '— (only shown for Google Authenticator method)'
        secret = obj.get_or_create_totp_secret()
        return format_html(
            '<code style="font-size:1.1rem;letter-spacing:3px;'
            'background:#f1f5f9;padding:6px 12px;border-radius:6px;">{}</code>',
            secret
        )
    totp_secret_display.short_description = 'TOTP Secret (manual entry)'

    def qr_code_display(self, obj):
        from django.utils.html import format_html
        if not obj.pk or obj.method != SuperAdmin2FA.METHOD_TOTP:
            return format_html(
                '<p style="color:#94a3b8;">QR code only shown when method is '
                '<strong>Google Authenticator</strong>.</p>'
            )
        try:
            import qrcode
            import qrcode.image.svg
            import io, base64

            uri = obj.get_totp_uri()

            # Generate PNG QR code as base64
            qr = qrcode.QRCode(box_size=6, border=2)
            qr.add_data(uri)
            qr.make(fit=True)
            img = qr.make_image(fill_color='#1e1b4b', back_color='white')
            buf = io.BytesIO()
            img.save(buf, format='PNG')
            b64 = base64.b64encode(buf.getvalue()).decode()

            return format_html(
                '<div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:12px;'
                'padding:16px;display:inline-block;text-align:center;">'
                '<img src="data:image/png;base64,{}" alt="QR Code" '
                'style="width:180px;height:180px;display:block;margin:0 auto 10px;">'
                '<p style="margin:0;font-size:12px;color:#64748b;">'
                'Scan with Google Authenticator, Authy, or any TOTP app'
                '</p></div>',
                b64
            )
        except Exception as e:
            return f'QR generation failed: {e}'

    qr_code_display.short_description = 'QR Code (scan with Authenticator)'
