from django.db import models
from django.utils.translation import gettext_lazy as _
from wagtail.admin.panels import FieldPanel, HelpPanel, MultiFieldPanel
from wagtail.contrib.settings.models import BaseSiteSetting, register_setting

from .constants import (
    DEFAULT_APP_NAME,
    DEFAULT_ACCENT_COLOR,
    DEFAULT_BACKGROUND_COLOR,
    DEFAULT_DESCRIPTION,
    DEFAULT_DISPLAY_MODE,
    DEFAULT_FOREGROUND_COLOR,
    DEFAULT_NAVIGATION_BAR_COLOR,
    DEFAULT_ORIENTATION,
    DEFAULT_SCOPE,
    DEFAULT_SHORT_NAME,
    DEFAULT_START_URL,
    DEFAULT_STATUS_BAR_COLOR,
    DEFAULT_THEME_COLOR,
    BRANDING_DASHBOARD_NOTES,
    CAPABILITY_DASHBOARD_NOTES,
    DISPLAY_MODE_CHOICES,
    ORIENTATION_CHOICES,
    THIN_WRAPPER_WARNING,
)
from .forms import MobileAppAdminForm


@register_setting(icon="site")
class MobileApp(BaseSiteSetting):
    base_form_class = MobileAppAdminForm

    enable_pwa = models.BooleanField(default=True, verbose_name=_("Enable PWA"))
    enable_android = models.BooleanField(
        default=False, verbose_name=_("Enable Android packaging")
    )
    enable_ios = models.BooleanField(
        default=False, verbose_name=_("Enable iOS packaging")
    )
    push_notifications_enabled = models.BooleanField(
        default=False,
        verbose_name=_("Push notifications enabled"),
        help_text=_("Reserved for later push-notification integrations."),
    )
    enable_push_notifications = models.BooleanField(
        default=False,
        verbose_name=_("Enable push notifications"),
        help_text=_(
            "Planning flag only. Native push setup and permission copy still need to be configured."
        ),
    )
    enable_camera_uploads = models.BooleanField(
        default=False,
        verbose_name=_("Enable camera uploads"),
        help_text=_(
            "Planning flag for camera-based upload flows. Do not request camera permission unless the app uses it."
        ),
    )
    enable_file_picker = models.BooleanField(
        default=False,
        verbose_name=_("Enable file picker"),
        help_text=_("Planning flag for document or media selection flows."),
    )
    enable_geolocation = models.BooleanField(
        default=False,
        verbose_name=_("Enable geolocation"),
        help_text=_(
            "Planning flag for location-aware features. Requires platform permission text."
        ),
    )
    enable_qr_scanner = models.BooleanField(
        default=False,
        verbose_name=_("Enable QR scanner"),
        help_text=_(
            "Planning flag for scan workflows. Typically requires camera permission and native plugin setup."
        ),
    )
    enable_secure_storage = models.BooleanField(
        default=False,
        verbose_name=_("Enable secure storage"),
        help_text=_(
            "Planning flag for native secure key/value storage. Browser fallback stays in memory only and should not be treated as durable secure storage."
        ),
    )
    enable_biometrics = models.BooleanField(
        default=False,
        verbose_name=_("Enable biometrics"),
        help_text=_(
            "Planning flag for Face ID / biometric authentication. Use only with a real authentication flow."
        ),
    )
    enable_share_sheet = models.BooleanField(
        default=False,
        verbose_name=_("Enable share sheet"),
        help_text=_("Planning flag for native sharing of app links or files."),
    )
    enable_deep_links = models.BooleanField(
        default=False,
        verbose_name=_("Enable deep links"),
        help_text=_(
            "Planning flag for Android App Links and iOS Universal Links. Domain association is still required."
        ),
    )
    ios_camera_usage_description = models.CharField(
        max_length=255,
        blank=True,
        default="",
        verbose_name=_("iOS camera usage description"),
        help_text=_(
            "Optional NSCameraUsageDescription text for generated native upload documentation."
        ),
    )

    name = models.CharField(
        max_length=255,
        default=DEFAULT_APP_NAME,
        verbose_name=_("App name"),
        help_text=_("Full app name shown in manifest and install prompts."),
    )
    short_name = models.CharField(
        max_length=64,
        default=DEFAULT_SHORT_NAME,
        verbose_name=_("Short name"),
        help_text=_("Shorter label used on home screens."),
    )
    app_id = models.CharField(
        max_length=255,
        blank=True,
        default="",
        verbose_name=_("App ID / bundle identifier"),
        help_text=_("Reverse-DNS identifier such as com.mandelblog.client."),
    )
    description = models.TextField(
        blank=True,
        default=DEFAULT_DESCRIPTION,
        verbose_name=_("Description"),
        help_text=_("Public app description used in the manifest."),
    )
    app_version = models.CharField(
        max_length=32,
        default="1.0.0",
        verbose_name=_("App version"),
        help_text=_("Human-readable app version such as 1.0.0."),
    )
    build_number = models.PositiveIntegerField(
        default=1,
        verbose_name=_("Build number"),
        help_text=_("Monotonic native build number used for release packaging."),
    )
    theme_color = models.CharField(
        max_length=7,
        default=DEFAULT_THEME_COLOR,
        verbose_name=_("Theme color"),
    )
    background_color = models.CharField(
        max_length=7,
        default=DEFAULT_BACKGROUND_COLOR,
        verbose_name=_("Background color"),
    )
    foreground_color = models.CharField(
        max_length=7,
        default=DEFAULT_FOREGROUND_COLOR,
        verbose_name=_("Foreground color"),
        help_text=_(
            "Used when generating adaptive icon foreground and splash logo treatments."
        ),
    )
    accent_color = models.CharField(
        max_length=7,
        default=DEFAULT_ACCENT_COLOR,
        verbose_name=_("Accent color"),
        help_text=_(
            "Optional accent color for generated branding metadata and future native UI styling."
        ),
    )
    status_bar_color = models.CharField(
        max_length=7,
        default=DEFAULT_STATUS_BAR_COLOR,
        verbose_name=_("Status bar color"),
        help_text=_("Used in generated native configuration for status bar styling."),
    )
    navigation_bar_color = models.CharField(
        max_length=7,
        default=DEFAULT_NAVIGATION_BAR_COLOR,
        verbose_name=_("Navigation bar color"),
        help_text=_(
            "Used in generated native configuration for navigation bar styling."
        ),
    )
    start_url = models.CharField(
        max_length=255,
        default=DEFAULT_START_URL,
        verbose_name=_("Start URL"),
        help_text=_("Relative path or absolute URL opened when the app launches."),
    )
    scope = models.CharField(
        max_length=255,
        default=DEFAULT_SCOPE,
        verbose_name=_("Scope"),
        help_text=_("Relative path or absolute URL defining the app navigation scope."),
    )
    offline_url = models.CharField(
        max_length=255,
        blank=True,
        default="",
        verbose_name=_("Offline fallback URL"),
        help_text=_(
            "Optional relative path or absolute URL. Leave blank to use the built-in offline page."
        ),
    )
    display_mode = models.CharField(
        max_length=32,
        choices=DISPLAY_MODE_CHOICES,
        default=DEFAULT_DISPLAY_MODE,
        verbose_name=_("Display mode"),
    )
    orientation = models.CharField(
        max_length=32,
        choices=ORIENTATION_CHOICES,
        default=DEFAULT_ORIENTATION,
        verbose_name=_("Orientation"),
    )

    icon = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        verbose_name=_("App icon"),
        help_text=_(
            "Square PNG image used for favicon, Apple touch icon, and Android icons."
        ),
    )
    splash_image = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        verbose_name=_("Splash image"),
        help_text=_(
            "Optional splash/source image used for generated native app assets."
        ),
    )

    tablet_screenshot = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        verbose_name=_("Tablet screenshot"),
    )
    tablet_screenshot_size = models.CharField(max_length=32, blank=True, default="")
    mobile_screenshot = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        verbose_name=_("Mobile screenshot"),
    )
    mobile_screenshot_size = models.CharField(max_length=32, blank=True, default="")

    panels = [
        HelpPanel(
            heading=_("Store readiness warning"),
            content=f"<p>{THIN_WRAPPER_WARNING}</p>",
        ),
        MultiFieldPanel(
            [
                FieldPanel("enable_pwa"),
                FieldPanel("enable_android"),
                FieldPanel("enable_ios"),
                FieldPanel("push_notifications_enabled"),
            ],
            heading=_("Platform enablement"),
        ),
        MultiFieldPanel(
            [
                HelpPanel(
                    content="".join(
                        f"<p>{note}</p>" for note in CAPABILITY_DASHBOARD_NOTES
                    )
                ),
                FieldPanel("enable_push_notifications"),
                FieldPanel("enable_camera_uploads"),
                FieldPanel("enable_file_picker"),
                FieldPanel("enable_geolocation"),
                FieldPanel("enable_qr_scanner"),
                FieldPanel("enable_secure_storage"),
                FieldPanel("enable_biometrics"),
                FieldPanel("enable_share_sheet"),
                FieldPanel("enable_deep_links"),
                FieldPanel("ios_camera_usage_description"),
            ],
            heading=_("Native capability planning"),
        ),
        MultiFieldPanel(
            [
                FieldPanel("name"),
                FieldPanel("short_name"),
                FieldPanel("app_id"),
                FieldPanel("description"),
                FieldPanel("app_version"),
                FieldPanel("build_number"),
            ],
            heading=_("App identity"),
        ),
        MultiFieldPanel(
            [
                FieldPanel("start_url"),
                FieldPanel("scope"),
                FieldPanel("offline_url"),
                FieldPanel("display_mode"),
                FieldPanel("orientation"),
            ],
            heading=_("Launch behavior"),
        ),
        MultiFieldPanel(
            [
                HelpPanel(
                    content="".join(
                        f"<p>{note}</p>" for note in BRANDING_DASHBOARD_NOTES
                    )
                ),
                FieldPanel("theme_color"),
                FieldPanel("background_color"),
                FieldPanel("foreground_color"),
                FieldPanel("accent_color"),
                FieldPanel("status_bar_color"),
                FieldPanel("navigation_bar_color"),
                FieldPanel("icon"),
                FieldPanel("splash_image"),
            ],
            heading=_("Branding and assets"),
        ),
        MultiFieldPanel(
            [
                FieldPanel("tablet_screenshot"),
                FieldPanel("mobile_screenshot"),
            ],
            heading=_("Optional screenshots"),
        ),
    ]

    class Meta:
        verbose_name = _("Mobile app settings")

    @property
    def app_name(self) -> str:
        return self.name

    def clean(self):
        super().clean()
        if self.tablet_screenshot:
            self.tablet_screenshot_size = (
                f"{self.tablet_screenshot.width}x{self.tablet_screenshot.height}"
            )
        if self.mobile_screenshot:
            self.mobile_screenshot_size = (
                f"{self.mobile_screenshot.width}x{self.mobile_screenshot.height}"
            )
