import io

import barcode
from barcode.writer import ImageWriter
from flask import abort, jsonify, request, send_file
from flask_jwt_extended import current_user
from marshmallow import ValidationError
from sqlalchemy.exc import IntegrityError

from ...permissions import (
    can_manage_inventory_in,
    can_see_cost,
    require_permission,
    scrub_cost,
)
from ...extensions import db
from ...models import (
    ItemStatus,
    MovementType,
    Product,
    ProductItem,
    ServiceStatus,
    StockMovement,
    TechnicalService,
    Warehouse,
    WarehouseLocation,
    is_locked_for_disposition,
)
from ...schemas import MoveItemSchema, ProductItemSchema
from ...utils import get_or_404, paginate
from . import admin_bp

_schema = ProductItemSchema()
_list_schema = ProductItemSchema(many=True)


def _generate_barcode(item_id: int) -> str:
    return f"NES{item_id:08d}"


def _normalize_barcode(value):
    """Acepta str/None y devuelve un barcode utilizable o None.
    El backend lo trata como 'autogenerar' cuando es None/vacío.
    """
    if value is None:
        return None
    v = str(value).strip()
    return v or None


def _is_barcode_taken(barcode: str, exclude_item_id: int | None = None) -> bool:
    """¿Ya hay otra unidad con ese barcode?"""
    q = ProductItem.query.filter(ProductItem.barcode == barcode)
    if exclude_item_id is not None:
        q = q.filter(ProductItem.id != exclude_item_id)
    return q.first() is not None


@admin_bp.get("/items")
@require_permission("items.view")
def list_items():
    q = ProductItem.query
    if search := request.args.get("q"):
        like = f"%{search}%"
        q = q.filter(
            (ProductItem.serial.ilike(like))
            | (ProductItem.barcode.ilike(like))
            | (ProductItem.imei.ilike(like))
        )
    if pid := request.args.get("product_id"):
        q = q.filter(ProductItem.product_id == int(pid))
    if status := request.args.get("status"):
        q = q.filter(ProductItem.status == status)
    if store_id := request.args.get("store_id"):
        q = q.filter(ProductItem.store_id == int(store_id))
    if wh_id := request.args.get("warehouse_id"):
        q = q.filter(ProductItem.warehouse_id == int(wh_id))
    if loc_id := request.args.get("location_id"):
        q = q.filter(ProductItem.location_id == int(loc_id))
    if location := request.args.get("location"):
        q = q.filter(ProductItem.location.ilike(f"%{location}%"))
    q = q.order_by(ProductItem.created_at.desc())

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


@admin_bp.get("/items/lookup")
@require_permission("items.lookup")
def lookup_item():
    """Match exacto por serial, codigo de barras o IMEI. Para POS y recepcion."""
    code = (request.args.get("code") or "").strip()
    if not code:
        return jsonify(error="parametro 'code' requerido"), 400
    item = ProductItem.query.filter(
        (ProductItem.serial == code)
        | (ProductItem.barcode == code)
        | (ProductItem.imei == code)
    ).first()
    if not item:
        return jsonify(error="no encontrado"), 404
    return scrub_cost(_schema.dump(item), current_user)


@admin_bp.post("/items")
@require_permission("items.create")
def create_item():
    """Crea una unidad manualmente (alta sin compra). Para casos de ajuste o pruebas."""
    try:
        data = _schema.load(request.get_json(silent=True) or {})
    except ValidationError as err:
        return jsonify(errors=err.messages), 400

    get_or_404(Product, data["product_id"])

    # Validar warehouse + location si se proveen
    wh = None
    if data.get("warehouse_id"):
        wh = get_or_404(Warehouse, data["warehouse_id"])
    loc = None
    if data.get("location_id"):
        loc = get_or_404(WarehouseLocation, data["location_id"])
        if wh and loc.warehouse_id != wh.id:
            return jsonify(error="la ubicación no pertenece al almacén indicado"), 400
        if not wh:
            wh = loc.warehouse

    # Barcode opcional: si viene custom, validar unicidad antes de insertar
    custom_barcode = _normalize_barcode(data.get("barcode"))
    if custom_barcode is not None and _is_barcode_taken(custom_barcode):
        return jsonify(error=f"el código de barras '{custom_barcode}' ya está en uso"), 409

    item = ProductItem(
        product_id=data["product_id"],
        serial=data["serial"].strip(),
        imei=(data.get("imei") or "").strip() or None,
        barcode="PENDING",
        cost=data.get("cost"),
        location=data.get("location"),
        store_id=data.get("store_id") or (wh.store_id if wh else None),
        warehouse_id=wh.id if wh else None,
        location_id=loc.id if loc else None,
        notes=data.get("notes"),
    )
    db.session.add(item)
    try:
        db.session.flush()
        item.barcode = custom_barcode if custom_barcode else _generate_barcode(item.id)
        movement = StockMovement(
            product_item_id=item.id,
            type=MovementType.ADJUST_IN,
            reference_type="manual",
            user_id=current_user.id if current_user else None,
            notes="Alta manual",
        )
        db.session.add(movement)
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        return jsonify(error="serial o IMEI duplicado"), 409
    return scrub_cost(_schema.dump(item), current_user), 201


@admin_bp.get("/items/<int:item_id>")
@require_permission("items.view")
def get_item(item_id):
    return scrub_cost(_schema.dump(get_or_404(ProductItem, item_id)), current_user)


@admin_bp.put("/items/<int:item_id>")
@require_permission("items.edit")
def update_item(item_id):
    item = get_or_404(ProductItem, item_id)
    try:
        data = _schema.load(request.get_json(silent=True) or {}, partial=True)
    except ValidationError as err:
        return jsonify(errors=err.messages), 400

    for fld in ("serial", "imei", "cost", "location", "notes"):
        if fld in data:
            value = data[fld]
            if isinstance(value, str):
                value = value.strip() or None
            setattr(item, fld, value)

    # Cambio de barcode (manual / por reemplazo de etiqueta dañada).
    # Si viene vacío y la unidad tenía uno custom, lo reseteamos a autogenerado.
    if "barcode" in data:
        new_bc = _normalize_barcode(data["barcode"])
        if new_bc is None:
            new_bc = _generate_barcode(item.id)
        if new_bc != item.barcode:
            if _is_barcode_taken(new_bc, exclude_item_id=item.id):
                return jsonify(error=f"el código de barras '{new_bc}' ya está en uso"), 409
            item.barcode = new_bc

    try:
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        return jsonify(error="serial / IMEI / barcode duplicado"), 409
    return scrub_cost(_schema.dump(item), current_user)


_move_schema = MoveItemSchema()


@admin_bp.post("/items/<int:item_id>/move")
@require_permission("items.move")
def move_item(item_id):
    """Mueve la unidad a otro almacén (misma sede o cross-sede). Movimiento simple."""
    item = get_or_404(ProductItem, item_id)
    try:
        data = _move_schema.load(request.get_json(silent=True) or {})
    except ValidationError as err:
        return jsonify(errors=err.messages), 400

    target_wh = get_or_404(Warehouse, data["warehouse_id"])
    if not target_wh.is_active:
        return jsonify(error="el almacén destino está inactivo"), 400

    # Vendedor/inventario: necesita can_manage_inventory en AMBAS sedes
    if not can_manage_inventory_in(current_user, item.store_id):
        return jsonify(error="no tenés permiso para mover unidades de la sede origen"), 403
    if not can_manage_inventory_in(current_user, target_wh.store_id):
        return jsonify(error="no tenés permiso para mover unidades a la sede destino"), 403

    target_loc = None
    if data.get("location_id"):
        target_loc = get_or_404(WarehouseLocation, data["location_id"])
        if target_loc.warehouse_id != target_wh.id:
            return jsonify(error="la ubicación no pertenece al almacén destino"), 400

    same_wh = item.warehouse_id == target_wh.id
    same_loc = item.location_id == (target_loc.id if target_loc else None)
    if same_wh and same_loc:
        return jsonify(error="la unidad ya está en ese almacén/ubicación"), 400

    notes = (data.get("notes") or "").strip() or None
    parts = []
    if not same_wh:
        from_label = item.warehouse.code if item.warehouse else "—"
        parts.append(f"{from_label} → {target_wh.code}")
    if not same_loc:
        from_l = (item.location_ref.code if item.location_ref else "—")
        to_l = (target_loc.code if target_loc else "—")
        parts.append(f"loc {from_l} → {to_l}")
    summary = " · ".join(parts)
    final_notes = f"Movimiento interno: {summary}"
    if notes:
        final_notes += f" | {notes}"

    item.warehouse_id = target_wh.id
    item.store_id = target_wh.store_id  # mantener sede coherente
    item.location_id = target_loc.id if target_loc else None

    db.session.add(StockMovement(
        product_item_id=item.id,
        type=MovementType.INTERNAL_MOVE,
        reference_type="warehouse_move",
        reference_id=target_wh.id,
        user_id=current_user.id if current_user else None,
        notes=final_notes,
    ))
    db.session.commit()
    return scrub_cost(_schema.dump(item), current_user)


@admin_bp.post("/items/<int:item_id>/status")
@require_permission("items.change_status")
def change_status(item_id):
    """Cambia el estado de una unidad y registra el movimiento.

    Transiciones que pasan por flujos dedicados (NO usar este endpoint):
      - IN_SERVICE: usar `POST /admin/technical-services/...` (servicio técnico)
      - IN_WARRANTY: usar el flujo de garantías
      - LOST: usar `POST /admin/items/<id>/declare-loss`
      - SOLD: usar POS / sales
    """
    item = get_or_404(ProductItem, item_id)
    if not can_manage_inventory_in(current_user, item.store_id):
        return jsonify(error="no tenés permiso para cambiar el estado de unidades en esa sede"), 403
    body = request.get_json(silent=True) or {}
    new_status = body.get("status")
    if new_status not in {s.value for s in ItemStatus}:
        return jsonify(error="status invalido"), 400

    if item.status == ItemStatus.IN_SERVICE:
        return jsonify(error="la unidad está en servicio técnico; usá los endpoints de /technical-services"), 409

    movement_type_map = {
        ItemStatus.AVAILABLE.value: MovementType.RELEASE,
        ItemStatus.RESERVED.value: MovementType.RESERVE,
        ItemStatus.SOLD.value: MovementType.OUT,
        ItemStatus.DAMAGED.value: MovementType.DAMAGE,
        ItemStatus.RETURNED.value: MovementType.ADJUST_IN,
    }
    if new_status not in movement_type_map:
        return jsonify(error=f"transición a '{new_status}' no permitida por este endpoint"), 400
    movement_type = movement_type_map[new_status]

    item.status = ItemStatus(new_status)
    db.session.add(StockMovement(
        product_item_id=item.id,
        type=movement_type,
        reference_type="manual",
        user_id=current_user.id if current_user else None,
        notes=body.get("notes"),
    ))
    db.session.commit()
    return scrub_cost(_schema.dump(item), current_user)


@admin_bp.get("/items/<int:item_id>/timeline")
@require_permission("items.timeline")
def item_timeline(item_id):
    """Linea de tiempo de la unidad: movimientos, ventas, devoluciones."""
    item = get_or_404(ProductItem, item_id)
    show_cost = can_see_cost(current_user)
    events = []
    for m in sorted(item.movements, key=lambda x: x.created_at):
        events.append({
            "id": f"mv-{m.id}",
            "kind": "movement",
            "type": m.type.value if hasattr(m.type, "value") else m.type,
            "reference_type": m.reference_type,
            "reference_id": m.reference_id,
            "user": {"id": m.user.id, "name": m.user.full_name} if m.user else None,
            "notes": m.notes,
            "created_at": m.created_at.isoformat(),
        })

    # Servicios técnicos sobre esta unidad (historial + costo acumulado).
    # `service_cost_total` solo cuenta los completados; cancelados quedan en 0.
    services = TechnicalService.query.filter_by(product_item_id=item.id).order_by(
        TechnicalService.created_at.desc()
    ).all()
    from decimal import Decimal as _D
    services_dump = []
    cost_total = _D("0")
    for s in services:
        services_dump.append({
            "id": s.id,
            "number": s.number,
            "status": s.status.value if hasattr(s.status, "value") else s.status,
            "fee": str(s.fee) if show_cost else None,
            "currency": s.currency,
            "fee_overridden": s.fee_overridden,
            "description": s.description,
            "technician": {
                "id": s.technician.id,
                "full_name": s.technician.full_name,
            } if s.technician else None,
            "started_at": s.started_at.isoformat() if s.started_at else None,
            "completed_at": s.completed_at.isoformat() if s.completed_at else None,
            "is_paid": s.is_paid,
        })
        if s.status == ServiceStatus.COMPLETED:
            cost_total += s.fee
    return jsonify(
        item={
            "id": item.id,
            "serial": item.serial,
            "barcode": item.barcode,
            "imei": item.imei,
            "status": item.status.value if hasattr(item.status, "value") else item.status,
            "cost": (str(item.cost) if item.cost else None) if show_cost else None,
            "location": item.location,
            "store_id": item.store_id,
            "store_name": item.store.name if item.store else None,
            "store_code": item.store.code if item.store else None,
            "warehouse_id": item.warehouse_id,
            "warehouse": {
                "id": item.warehouse.id,
                "code": item.warehouse.code,
                "name": item.warehouse.name,
                "store_id": item.warehouse.store_id,
            } if item.warehouse else None,
            "location_id": item.location_id,
            "location_ref": {
                "id": item.location_ref.id,
                "code": item.location_ref.code,
                "name": item.location_ref.name,
            } if item.location_ref else None,
            "product": {
                "id": item.product.id,
                "name": item.product.name,
                "sku": item.product.sku,
                "image_url": item.product.image_url,
                "price": str(item.product.price),
            } if item.product else None,
            "created_at": item.created_at.isoformat(),
            "service_cost_total": str(cost_total) if show_cost else None,
            "service_count": len(services),
        },
        events=events,
        services=services_dump,
    )


@admin_bp.get("/items/<int:item_id>/barcode.png")
@require_permission("items.barcode_png")
def item_barcode(item_id):
    item = get_or_404(ProductItem, item_id)
    code = barcode.get("code128", item.barcode, writer=ImageWriter())
    buf = io.BytesIO()
    code.write(buf, options={"module_height": 10.0, "font_size": 8, "text_distance": 3.0, "quiet_zone": 4.0})
    buf.seek(0)
    return send_file(buf, mimetype="image/png", download_name=f"{item.barcode}.png")


@admin_bp.get("/items/<int:item_id>/label.pdf")
@require_permission("items.barcode_png")
def item_label_pdf(item_id):
    """Etiqueta imprimible 80×50mm con producto + serial + barcode + precio."""
    from ...pdf.label import build_item_label_pdf
    item = get_or_404(ProductItem, item_id)
    buf = build_item_label_pdf(item)
    # `as_attachment=False` para que el browser lo abra en visor y permita
    # imprimir directo desde ahí.
    return send_file(
        buf,
        mimetype="application/pdf",
        download_name=f"label_{item.barcode}.pdf",
        as_attachment=False,
    )


@admin_bp.post("/items/labels.pdf")
@require_permission("items.barcode_png")
def items_labels_sheet_pdf():
    """Lote: PDF con N etiquetas en hojas A4 (grilla 2×5).

    Body: `{"item_ids": [1, 2, 3, ...]}` (máx 200 para no romper el browser).
    Preserva el orden recibido. Items inexistentes se descartan silenciosamente
    (devuelven el conteo de etiquetas dibujadas en el header).
    """
    from ...pdf.label import build_items_labels_sheet_pdf

    body = request.get_json(silent=True) or {}
    raw_ids = body.get("item_ids") or []
    if not isinstance(raw_ids, list) or not raw_ids:
        return jsonify(error="item_ids debe ser una lista no vacía"), 400
    if len(raw_ids) > 200:
        return jsonify(error="máximo 200 etiquetas por lote"), 400
    try:
        ids = [int(x) for x in raw_ids]
    except (TypeError, ValueError):
        return jsonify(error="item_ids debe contener solo enteros"), 400

    found = {it.id: it for it in ProductItem.query.filter(ProductItem.id.in_(ids)).all()}
    ordered = [found[i] for i in ids if i in found]
    if not ordered:
        return jsonify(error="ninguna unidad encontrada"), 404

    buf = build_items_labels_sheet_pdf(ordered)
    resp = send_file(
        buf,
        mimetype="application/pdf",
        download_name=f"etiquetas_{len(ordered)}u.pdf",
        as_attachment=False,
    )
    resp.headers["X-Labels-Count"] = str(len(ordered))
    return resp


@admin_bp.delete("/items/<int:item_id>")
@require_permission("items.delete")
def delete_item(item_id):
    item = get_or_404(ProductItem, item_id)
    if is_locked_for_disposition(item):
        return jsonify(
            error=f"no se puede eliminar una unidad en estado '{item.status.value}' "
                  "(vendida / en servicio / en garantía / perdida)"
        ), 409
    db.session.delete(item)
    db.session.commit()
    return "", 204
