# 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", "thermal_paper_width", "auto_print_receipt"),
            "classes": ("collapse",),
        }),
        ("Security (2FA)", {
            "fields": ("require_2fa_for_admin", "require_2fa_for_cashier"),
            "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")
