from flask import jsonify, request
from flask_jwt_extended import current_user
from marshmallow import ValidationError
from sqlalchemy import desc
from sqlalchemy.exc import IntegrityError

from ...permissions import can_see_cost, require_permission
from ...extensions import db
from ...models import (
    Brand,
    Category,
    ItemStatus,
    Product,
    ProductComboItem,
    ProductItem,
    ProductKind,
    StockMovement,
)
from ...schemas import ProductSchema
from ...utils import get_or_404, paginate, unique_slug
from . import admin_bp

_schema = ProductSchema()
_list_schema = ProductSchema(many=True)


@admin_bp.get("/products")
@require_permission("products.view")
def list_products():
    q = Product.query
    if search := request.args.get("q"):
        like = f"%{search}%"
        q = q.filter(
            (Product.name.ilike(like))
            | (Product.sku.ilike(like))
            | (Product.model.ilike(like))
        )
    if brand_id := request.args.get("brand_id"):
        q = q.filter(Product.brand_id == int(brand_id))
    if cat_id := request.args.get("category_id"):
        q = q.filter(Product.category_id == int(cat_id))
    if (active := request.args.get("is_active")) is not None and active != "":
        q = q.filter(Product.is_active == (active.lower() == "true"))
    if kind := request.args.get("kind"):
        q = q.filter(Product.kind == kind)
    if pmin := request.args.get("price_min"):
        try: q = q.filter(Product.price >= float(pmin))
        except (TypeError, ValueError): pass
    if pmax := request.args.get("price_max"):
        try: q = q.filter(Product.price <= float(pmax))
        except (TypeError, ValueError): pass
    q = q.order_by(Product.name)

    page = paginate(q)
    page["items"] = _list_schema.dump(page["items"])
    return jsonify(page)


def _set_combo_components(product: Product, raw_components):
    """Reemplaza los componentes del combo. raw_components = [{component_product_id, quantity}, ...]"""
    if raw_components is None:
        return
    # Limpiar previos
    for c in list(product.combo_components):
        db.session.delete(c)
    db.session.flush()

    seen = set()
    for c in raw_components:
        cid = int(c.get("component_product_id"))
        qty = int(c.get("quantity") or 1)
        if cid == product.id:
            raise ValueError("un combo no puede contener a sí mismo")
        if cid in seen:
            raise ValueError(f"componente duplicado: id {cid}")
        seen.add(cid)
        comp = Product.query.get(cid)
        if not comp:
            raise ValueError(f"componente {cid} no existe")
        if comp.kind == ProductKind.COMBO:
            raise ValueError(f"el componente '{comp.name}' es un combo y no puede anidar otros combos")
        if qty < 1:
            raise ValueError("la cantidad debe ser ≥ 1")
        db.session.add(ProductComboItem(
            combo_product_id=product.id,
            component_product_id=cid,
            quantity=qty,
        ))


@admin_bp.post("/products")
@require_permission("products.create")
def create_product():
    raw = request.get_json(silent=True) or {}
    combo_items = raw.pop("combo_items", None)
    try:
        data = _schema.load(raw)
    except ValidationError as err:
        return jsonify(errors=err.messages), 400

    get_or_404(Brand, data["brand_id"])
    get_or_404(Category, data["category_id"])

    kind_raw = (data.get("kind") or "simple").lower()
    kind_val = ProductKind.COMBO if kind_raw == "combo" else ProductKind.SIMPLE

    product = Product(
        sku=data["sku"].strip(),
        name=data["name"].strip(),
        slug=unique_slug(Product, data["name"]),
        model=(data.get("model") or "").strip() or None,
        description=data.get("description"),
        brand_id=data["brand_id"],
        category_id=data["category_id"],
        price=data["price"],
        image_url=data.get("image_url"),
        is_active=data.get("is_active", True),
        kind=kind_val,
    )
    db.session.add(product)
    try:
        db.session.flush()
        if kind_val == ProductKind.COMBO:
            if not combo_items:
                db.session.rollback()
                return jsonify(error="un combo requiere al menos un componente"), 400
            try:
                _set_combo_components(product, combo_items)
            except ValueError as e:
                db.session.rollback()
                return jsonify(error=str(e)), 400
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        return jsonify(error="SKU duplicado"), 409
    return _schema.dump(product), 201


@admin_bp.get("/products/<int:product_id>")
@require_permission("products.view")
def get_product(product_id):
    return _schema.dump(get_or_404(Product, product_id))


@admin_bp.put("/products/<int:product_id>")
@require_permission("products.edit")
def update_product(product_id):
    product = get_or_404(Product, product_id)
    raw = request.get_json(silent=True) or {}
    combo_items = raw.pop("combo_items", None)
    try:
        data = _schema.load(raw, partial=True)
    except ValidationError as err:
        return jsonify(errors=err.messages), 400

    if "brand_id" in data:
        get_or_404(Brand, data["brand_id"])
        product.brand_id = data["brand_id"]
    if "category_id" in data:
        get_or_404(Category, data["category_id"])
        product.category_id = data["category_id"]
    if "name" in data and data["name"] != product.name:
        product.name = data["name"].strip()
        product.slug = unique_slug(Product, data["name"])
    if "kind" in data and data["kind"]:
        new_kind = ProductKind.COMBO if str(data["kind"]).lower() == "combo" else ProductKind.SIMPLE
        # Si pasa de combo→simple, limpiar componentes
        if new_kind == ProductKind.SIMPLE and product.kind == ProductKind.COMBO:
            for c in list(product.combo_components):
                db.session.delete(c)
        # Si pasa de simple→combo y tiene unidades reales, advertir
        if new_kind == ProductKind.COMBO and product.items:
            return jsonify(error="no se puede convertir en combo: el producto ya tiene unidades en inventario"), 400
        product.kind = new_kind
    for fld in ("sku", "model", "description", "price", "image_url", "is_active"):
        if fld in data:
            value = data[fld]
            if isinstance(value, str):
                value = value.strip() or None
            setattr(product, fld, value)

    if combo_items is not None and product.kind == ProductKind.COMBO:
        try:
            _set_combo_components(product, combo_items)
        except ValueError as e:
            db.session.rollback()
            return jsonify(error=str(e)), 400

    try:
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        return jsonify(error="conflicto de unicidad"), 409
    return _schema.dump(product)


@admin_bp.delete("/products/<int:product_id>")
@require_permission("products.delete")
def delete_product(product_id):
    product = get_or_404(Product, product_id)
    if product.items:
        return jsonify(error="no se puede eliminar: tiene unidades en inventario"), 409
    db.session.delete(product)
    db.session.commit()
    return "", 204


# ============================================================
# Ficha del producto (detalle admin): items + stats + movements
# ============================================================

@admin_bp.get("/products/<int:product_id>/detail")
@require_permission("products.view")
def product_detail_admin(product_id):
    """Detalle ampliado: producto + breakdown de stock + unidades + ultimos movimientos."""
    product = get_or_404(Product, product_id)
    show_cost = can_see_cost(current_user)

    items = (
        ProductItem.query
        .filter_by(product_id=product_id)
        .order_by(ProductItem.store_id, ProductItem.status, ProductItem.serial)
        .all()
    )
    items_data = [{
        "id": it.id,
        "serial": it.serial,
        "barcode": it.barcode,
        "imei": it.imei,
        "status": it.status.value if hasattr(it.status, "value") else it.status,
        "store_id": it.store_id,
        "store_name": it.store.name if it.store else None,
        "store_code": it.store.code if it.store else None,
        "location": it.location,
        "cost": (str(it.cost) if it.cost else None) if show_cost else None,
        "created_at": it.created_at.isoformat(),
    } for it in items]

    # Stats por status
    stats = {s.value: 0 for s in ItemStatus}
    for it in items:
        key = it.status.value if hasattr(it.status, "value") else it.status
        stats[key] = stats.get(key, 0) + 1
    stats["total"] = len(items)

    # Stats por tienda
    by_store = {}
    for it in items:
        key = it.store_id or 0
        if key not in by_store:
            by_store[key] = {
                "store_id": it.store_id,
                "store_name": it.store.name if it.store else "— Sin sede —",
                "store_code": it.store.code if it.store else None,
                "total": 0, "available": 0, "sold": 0, "reserved": 0, "other": 0,
            }
        by_store[key]["total"] += 1
        st = it.status.value if hasattr(it.status, "value") else it.status
        if st == "available": by_store[key]["available"] += 1
        elif st == "sold": by_store[key]["sold"] += 1
        elif st == "reserved": by_store[key]["reserved"] += 1
        else: by_store[key]["other"] += 1

    return jsonify(
        product=_schema.dump(product),
        items=items_data,
        stats=stats,
        by_store=list(by_store.values()),
    )


@admin_bp.get("/products/<int:product_id>/movements")
@require_permission("products.view_movements")
def product_movements(product_id):
    """Movimientos de inventario de TODAS las unidades del producto, paginados.

    Acepta filtros opcionales: warehouse_id, store_id, type, date_from/date_to.
    """
    get_or_404(Product, product_id)

    # Filtrar items del producto (con posibles filtros de warehouse/store)
    item_filter = ProductItem.query.filter(ProductItem.product_id == product_id)
    if wh := request.args.get("warehouse_id"):
        item_filter = item_filter.filter(ProductItem.warehouse_id == int(wh))
    if st := request.args.get("store_id"):
        item_filter = item_filter.filter(ProductItem.store_id == int(st))

    item_ids_subq = item_filter.with_entities(ProductItem.id).subquery()

    q = (
        StockMovement.query
        .filter(StockMovement.product_item_id.in_(item_ids_subq))
    )
    if mtype := request.args.get("type"):
        q = q.filter(StockMovement.type == mtype)
    from datetime import datetime as _dt, timedelta as _td
    if df := request.args.get("date_from"):
        try: q = q.filter(StockMovement.created_at >= _dt.fromisoformat(df))
        except ValueError: pass
    if dt_ := request.args.get("date_to"):
        try:
            d = _dt.fromisoformat(dt_)
            q = q.filter(StockMovement.created_at < d + _td(days=1))
        except ValueError: pass

    q = q.order_by(desc(StockMovement.created_at))

    page = paginate(q, default_per_page=30)
    items = []
    for m in page["items"]:
        items.append({
            "id": m.id,
            "type": m.type.value if hasattr(m.type, "value") else m.type,
            "reference_type": m.reference_type,
            "reference_id": m.reference_id,
            "notes": m.notes,
            "created_at": m.created_at.isoformat(),
            "user": {"id": m.user.id, "full_name": m.user.full_name} if m.user else None,
            "item": {
                "id": m.item.id,
                "serial": m.item.serial,
                "barcode": m.item.barcode,
                "store_id": m.item.store_id,
                "store_name": m.item.store.name if m.item.store else None,
                "warehouse": {
                    "id": m.item.warehouse.id, "code": m.item.warehouse.code,
                } if m.item.warehouse else None,
            } if m.item else None,
        })
    page["items"] = items
    return jsonify(page)
