from __future__ import annotations

from urllib.parse import urlencode

from django.urls import NoReverseMatch, reverse

from contract.models import User
from market.models import SellerProfile
from market.services import can_manage_market_products
from market.services.access import resolve_company_for_user


RANGE_OPTIONS = (
    (30, "30 Days"),
    (90, "90 Days"),
    (180, "6 Months"),
    (365, "12 Months"),
)


def safe_reverse(route_name: str, *, query: dict[str, str] | None = None, args=None, kwargs=None, fallback: str = "#") -> str:
    try:
        url = reverse(route_name, args=args or (), kwargs=kwargs or {})
    except NoReverseMatch:
        return fallback
    if query:
        return f"{url}?{urlencode(query)}"
    return url


def resolve_dashboard_profile(
    user,
    seller_profile: SellerProfile | None = None,
    company_profile=None,
) -> str:
    if getattr(user, "is_superuser", False) or getattr(user, "type", None) == User.Types.ADMIN:
        return "admin"
    if getattr(user, "type", None) == User.Types.FIELD_OFFICER:
        return "field_officer"
    if getattr(user, "type", None) == User.Types.FARMER:
        return "farmer"
    if company_profile or resolve_company_for_user(user):
        return "company"
    if getattr(user, "type", None) == User.Types.BUSINESS_PERSON:
        return "seller"
    if seller_profile or can_manage_market_products(user):
        return "seller"
    return "operations"


def build_dashboard_filters(request, selected_range: int) -> list[dict[str, str | bool]]:
    filters = []
    current_path = request.path
    current_params = request.GET.copy()
    for value, label in RANGE_OPTIONS:
        params = current_params.copy()
        params["range"] = str(value)
        filters.append(
            {
                "label": label,
                "url": f"{current_path}?{params.urlencode()}",
                "is_active": int(selected_range) == int(value),
            }
        )
    return filters


def build_dashboard_meta(user, profile: str) -> dict[str, str]:
    profile_map = {
        "admin": {
            "eyebrow": "Platform Overview",
            "title": "Bomabest Dashboard",
            "subtitle": "Keep approvals, contracts, payments, and marketplace activity in view from one place.",
            "chip": "Admin workspace",
            "hero_hint": "Start with the priority cards and queues below to move the platform forward.",
        },
        "field_officer": {
            "eyebrow": "Field Overview",
            "title": "Bomabest Dashboard",
            "subtitle": "Track assigned farmers, listings, collections, and support work in one clear workspace.",
            "chip": "Field operations",
            "hero_hint": "Review assignments, listing follow-up, and overdue items first.",
        },
        "farmer": {
            "eyebrow": "Farmer Overview",
            "title": "Bomabest Dashboard",
            "subtitle": "See your contracts, payments, groups, and product activity in one place.",
            "chip": "Farmer workspace",
            "hero_hint": "Check the next actions below to keep contracts and listings moving.",
        },
        "seller": {
            "eyebrow": "Seller Overview",
            "title": "Bomabest Dashboard",
            "subtitle": "Track products, orders, storefront visibility, and seller status from one place.",
            "chip": "Seller workspace",
            "hero_hint": "Focus on pending products and active orders to keep momentum high.",
        },
        "company": {
            "eyebrow": "Company Overview",
            "title": "Bomabest Dashboard",
            "subtitle": "Track company approvals, salespeople, products, and active offer work from one place.",
            "chip": "Company workspace",
            "hero_hint": "Focus on approvals, staff, and live product movement to keep the company active.",
        },
        "operations": {
            "eyebrow": "Workspace Overview",
            "title": "Bomabest Dashboard",
            "subtitle": "Open the tools, alerts, and reports available to your account.",
            "chip": "Internal workspace",
            "hero_hint": "Use the quick actions and sections below to reach the right workflow faster.",
        },
    }
    meta = profile_map.get(profile, profile_map["operations"]).copy()
    meta["welcome_name"] = user.get_full_name() or getattr(user, "email", "") or "Team"
    return meta


def build_dashboard_quick_actions(user, profile: str, seller_profile: SellerProfile | None = None, company_profile=None) -> list[dict[str, str]]:
    actions: list[dict[str, str]] = []

    if profile == "admin":
        actions.extend(
            [
                {
                    "label": "Review Users",
                    "description": "Approve accounts and manage roles.",
                    "icon": "fa-users-cog",
                    "tone": "emerald",
                    "url": safe_reverse("contract_market_place:user_list"),
                },
                {
                    "label": "Moderate Sellers",
                    "description": "Process seller applications waiting for review.",
                    "icon": "fa-user-clock",
                    "tone": "amber",
                    "url": safe_reverse("market:seller_review_list"),
                },
                {
                    "label": "Moderate Products",
                    "description": "Clear pending marketplace products and listings.",
                    "icon": "fa-box-open",
                    "tone": "blue",
                    "url": safe_reverse("market:product_review_list"),
                },
                {
                    "label": "Order Queue",
                    "description": "Assign paid seller orders to staff.",
                    "icon": "fa-truck-fast",
                    "tone": "slate",
                    "url": safe_reverse("market:market_admin_order_queue"),
                },
                {
                    "label": "Input Shop Orders",
                    "description": "Watch operational order fulfilment and payment status.",
                    "icon": "fa-cart-flatbed",
                    "tone": "emerald",
                    "url": safe_reverse("contract_market_place:input_shop_orders_admin"),
                },
                {
                    "label": "Field Assignments",
                    "description": "Maintain farmer-to-officer coverage.",
                    "icon": "fa-user-tie",
                    "tone": "blue",
                    "url": safe_reverse("contract_market_place:field_officer_list"),
                },
                {
                    "label": "Companies",
                    "description": "Review company records, members, and documents.",
                    "icon": "fa-building",
                    "tone": "emerald",
                    "url": safe_reverse("market:company_admin_list"),
                },
                {
                    "label": "Company Approvals",
                    "description": "Open the pending company approval queue.",
                    "icon": "fa-circle-check",
                    "tone": "amber",
                    "url": safe_reverse("market:company_admin_approvals"),
                },
            ]
        )
    elif profile == "field_officer":
        actions.extend(
            [
                {
                    "label": "Register Farmer",
                    "description": "Create and link a new farmer to your portfolio.",
                    "icon": "fa-user-plus",
                    "tone": "emerald",
                    "url": safe_reverse("market:field_officer_register_farmer"),
                },
                {
                    "label": "Link Farmer",
                    "description": "Attach an existing farmer to your assignment list.",
                    "icon": "fa-link",
                    "tone": "blue",
                    "url": safe_reverse("market:field_officer_link_farmer"),
                },
                {
                    "label": "Post Listing",
                    "description": "Create a farmer product and prepare it for review.",
                    "icon": "fa-seedling",
                    "tone": "amber",
                    "url": safe_reverse("market:farmer_listing_create"),
                },
                {
                    "label": "Listing Queue",
                    "description": "Work through approvals, changes, and fee follow-up.",
                    "icon": "fa-clipboard-check",
                    "tone": "slate",
                    "url": safe_reverse("market:farmer_listing_approval_list"),
                },
                {
                    "label": "Farmer Contracts",
                    "description": "Open contracts tied to your assigned farmers.",
                    "icon": "fa-file-signature",
                    "tone": "emerald",
                    "url": safe_reverse("contract_market_place:contract_list"),
                },
                {
                    "label": "Group Contracts",
                    "description": "Watch cooperative contract progress and signatures.",
                    "icon": "fa-users",
                    "tone": "blue",
                    "url": safe_reverse("contract_market_place:group_contract_list"),
                },
            ]
        )
    elif profile == "farmer":
        actions.extend(
            [
                {
                    "label": "Request Contract",
                    "description": "Start with the contract-focused input shop flow.",
                    "icon": "fa-file-circle-plus",
                    "tone": "emerald",
                    "url": safe_reverse("contract_market_place:input_shop_contracts"),
                },
                {
                    "label": "My Contracts",
                    "description": "Review personal contracts, signatures, and balances.",
                    "icon": "fa-file-contract",
                    "tone": "blue",
                    "url": safe_reverse("contract_market_place:contract_list"),
                },
                {
                    "label": "My Groups",
                    "description": "Open group memberships and cooperative details.",
                    "icon": "fa-people-group",
                    "tone": "slate",
                    "url": safe_reverse("contract_market_place:my_groups"),
                },
                {
                    "label": "Payments",
                    "description": "Track installments, overdue schedules, and receipts.",
                    "icon": "fa-money-bill-wave",
                    "tone": "amber",
                    "url": safe_reverse("payments:farmer_payment_list"),
                },
                {
                    "label": "Marketplace",
                    "description": "Browse Bomabest Soko and monitor your public product visibility.",
                    "icon": "fa-store",
                    "tone": "emerald",
                    "url": safe_reverse("market:catalog_list"),
                },
            ]
        )
    elif profile == "seller":
        has_approved_seller = bool(seller_profile and seller_profile.status == SellerProfile.Status.APPROVED)
        storefront_url = safe_reverse(
            "market:seller_storefront",
            kwargs={"seller_id": seller_profile.id},
            fallback=safe_reverse("market:seller_status"),
        ) if seller_profile else safe_reverse("market:seller_status")
        actions.extend(
            [
                {
                    "label": "Seller Status",
                    "description": "Check approval and account readiness.",
                    "icon": "fa-id-card",
                    "tone": "amber",
                    "url": safe_reverse("market:seller_status"),
                },
                {
                    "label": "Apply / Update",
                    "description": "Submit or refine your seller profile details.",
                    "icon": "fa-store",
                    "tone": "emerald",
                    "url": safe_reverse("market:seller_apply"),
                },
                {
                    "label": "Manage Products",
                    "description": "Open product catalog management and review statuses.",
                    "icon": "fa-boxes-stacked",
                    "tone": "blue",
                    "url": safe_reverse("market:seller_product_list"),
                },
            ]
        )
        if has_approved_seller:
            actions.extend(
                [
                    {
                        "label": "Add Product",
                        "description": "Create a new marketplace draft.",
                        "icon": "fa-plus-circle",
                        "tone": "emerald",
                        "url": safe_reverse("market:seller_product_create"),
                    },
                    {
                        "label": "Storefront",
                        "description": "Preview your public storefront presence.",
                        "icon": "fa-shop",
                        "tone": "slate",
                        "url": storefront_url,
                    },
                ]
            )
    elif profile == "company":
        company_workspace_url = safe_reverse("market:company_workspace")
        actions.extend(
            [
                {
                    "label": "Company workspace",
                    "description": "Open the company profile, members, and invitations view.",
                    "icon": "fa-building",
                    "tone": "emerald",
                    "url": company_workspace_url,
                },
                {
                    "label": "Register company",
                    "description": "Start a new company registration or update an existing record.",
                    "icon": "fa-id-card",
                    "tone": "blue",
                    "url": safe_reverse("market:company_register"),
                },
                {
                    "label": "Company summary",
                    "description": "Review members, invites, and product readiness at a glance.",
                    "icon": "fa-chart-pie",
                    "tone": "slate",
                    "url": company_workspace_url,
                },
            ]
        )
    else:
        actions.extend(
            [
                {
                    "label": "Dashboard Home",
                    "description": "Stay inside the unified internal platform.",
                    "icon": "fa-gauge-high",
                    "tone": "emerald",
                    "url": safe_reverse("unified_dashboard"),
                },
                {
                    "label": "Notifications",
                    "description": "Review your latest operational updates.",
                    "icon": "fa-bell",
                    "tone": "blue",
                    "url": safe_reverse("contract_market_place:notifications_center"),
                },
                {
                    "label": "Marketplace",
                    "description": "Jump to the public marketplace when needed.",
                    "icon": "fa-store",
                    "tone": "slate",
                    "url": safe_reverse("market:home"),
                },
            ]
        )

    return [action for action in actions if action.get("url") and action["url"] != "#"]
