"""Template tags and filters for PI FYAD."""

from django import template
from django.utils import timezone
from django.utils.safestring import mark_safe

from aa_pi_fyad.constants import (
    EVE_IMAGE_BASE,
    EXTRACTOR_STATUS_ACTIVE,
    EXTRACTOR_STATUS_EXPIRED,
    EXTRACTOR_STATUS_IDLE,
    PLANET_TYPES,
)

register = template.Library()


# ── Image Tags ──────────────────────────────────────────────────────────────

@register.simple_tag
def eve_type_icon(type_id, size=64):
    """Return an <img> tag for an EVE type icon."""
    url = f"{EVE_IMAGE_BASE}/types/{type_id}/icon?size={size}"
    return mark_safe(f'<img src="{url}" alt="Type {type_id}" width="{size}" height="{size}" loading="lazy">')


@register.simple_tag
def eve_character_portrait(character_id, size=64):
    """Return an <img> tag for a character portrait."""
    url = f"{EVE_IMAGE_BASE}/characters/{character_id}/portrait?size={size}"
    return mark_safe(f'<img src="{url}" alt="Portrait" width="{size}" height="{size}" loading="lazy" class="rounded-circle">')


@register.simple_tag
def eve_corporation_logo(corporation_id, size=64):
    """Return an <img> tag for a corporation logo."""
    url = f"{EVE_IMAGE_BASE}/corporations/{corporation_id}/logo?size={size}"
    return mark_safe(f'<img src="{url}" alt="Corp Logo" width="{size}" height="{size}" loading="lazy">')


@register.simple_tag
def eve_planet_image(planet_type_id, size=64):
    """Return an <img> tag for a planet type."""
    url = f"{EVE_IMAGE_BASE}/types/{planet_type_id}/icon?size={size}"
    return mark_safe(f'<img src="{url}" alt="Planet" width="{size}" height="{size}" loading="lazy">')


# ── Extractor Status ────────────────────────────────────────────────────────

@register.filter
def extractor_status_badge(pin):
    """Return a Bootstrap badge for extractor status."""
    status = pin.extractor_status
    if status == EXTRACTOR_STATUS_ACTIVE:
        return mark_safe('<span class="badge bg-success">Active</span>')
    elif status == EXTRACTOR_STATUS_EXPIRED:
        return mark_safe('<span class="badge bg-danger">Expired</span>')
    else:
        return mark_safe('<span class="badge bg-secondary">Idle</span>')


@register.filter
def extractor_status_class(pin):
    """Return CSS class for extractor status."""
    status = pin.extractor_status
    if status == EXTRACTOR_STATUS_ACTIVE:
        return "text-success"
    elif status == EXTRACTOR_STATUS_EXPIRED:
        return "text-danger"
    return "text-muted"


@register.filter
def time_remaining_display(pin):
    """Return human-readable time remaining for an extractor."""
    remaining = pin.time_remaining
    if remaining is None:
        return "—"

    total_seconds = int(remaining.total_seconds())
    if total_seconds <= 0:
        return "Expired"

    days = total_seconds // 86400
    hours = (total_seconds % 86400) // 3600
    minutes = (total_seconds % 3600) // 60

    parts = []
    if days > 0:
        parts.append(f"{days}d")
    if hours > 0:
        parts.append(f"{hours}h")
    if minutes > 0:
        parts.append(f"{minutes}m")

    return " ".join(parts) if parts else "<1m"


# ── Storage ─────────────────────────────────────────────────────────────────

@register.filter
def storage_fill_class(pin):
    """Return CSS class based on storage fill percentage."""
    pct = pin.storage_fill_pct
    if pct >= 95:
        return "bg-danger"
    elif pct >= 80:
        return "bg-warning"
    elif pct >= 50:
        return "bg-info"
    return "bg-success"


@register.filter
def storage_fill_bar_width(pin):
    """Return width percentage for progress bar."""
    return min(pin.storage_fill_pct, 100)


@register.filter
def format_m3(value):
    """Format a volume in m³ with appropriate precision."""
    if value is None:
        return "0 m³"
    if value >= 1000:
        return f"{value:,.0f} m³"
    return f"{value:,.1f} m³"


@register.filter
def format_quantity(value):
    """Format an integer quantity with commas."""
    if value is None:
        return "0"
    return f"{value:,}"


# ── Factory Tier ────────────────────────────────────────────────────────────

@register.filter
def factory_tier_label(tier):
    """Return human-readable factory tier label."""
    labels = {
        0: "Unknown",
        1: "Basic",
        2: "Advanced",
        3: "High-Tech",
    }
    return labels.get(tier, f"Tier {tier}")


@register.filter
def factory_tier_badge(tier):
    """Return Bootstrap badge for factory tier."""
    classes = {
        1: "bg-secondary",
        2: "bg-primary",
        3: "bg-warning text-dark",
    }
    label = factory_tier_label(tier)
    css = classes.get(tier, "bg-secondary")
    return mark_safe(f'<span class="badge {css}">{label}</span>')


# ── Planet Type ─────────────────────────────────────────────────────────────

@register.filter
def planet_type_name(planet_type_id):
    """Return the planet type name from its ID."""
    return PLANET_TYPES.get(planet_type_id, "Unknown")


@register.filter
def planet_type_class(planet_type_id):
    """Return a CSS class based on planet type for theming."""
    type_classes = {
        2014: "planet-temperate",
        2015: "planet-ice",
        2016: "planet-gas",
        2017: "planet-oceanic",
        2063: "planet-lava",
        2064: "planet-barren",
        2065: "planet-storm",
        2066: "planet-plasma",
    }
    return type_classes.get(planet_type_id, "planet-unknown")


# ── Utility ─────────────────────────────────────────────────────────────────

@register.filter
def percentage(value, decimal_places=1):
    """Format a float as a percentage."""
    if value is None:
        return "0%"
    return f"{value:.{decimal_places}f}%"


@register.filter
def multiply(value, arg):
    """Multiply two values."""
    try:
        return float(value) * float(arg)
    except (ValueError, TypeError):
        return 0


@register.simple_tag
def pi_fyad_version():
    """Return the plugin version string."""
    from aa_pi_fyad import __version__
    return __version__


@register.filter
def alert_count(planets):
    """Count total critical alerts across a list of planets."""
    count = 0
    for planet in planets:
        if hasattr(planet, "has_critical_alerts") and planet.has_critical_alerts:
            count += 1
    return count


@register.inclusion_tag("pi_fyad/partials/extractor_card.html")
def render_extractor_card(pin):
    """Render an extractor card partial."""
    return {"pin": pin}


@register.inclusion_tag("pi_fyad/partials/storage_card.html")
def render_storage_card(pin):
    """Render a storage card partial."""
    return {"pin": pin, "contents": pin.contents.all()}


@register.inclusion_tag("pi_fyad/partials/factory_group.html")
def render_factory_group(tier, factories):
    """Render a factory group partial."""
    return {"tier": tier, "factories": factories}
