"""Contacts list, detail view, and inline-edit endpoints."""

from markupsafe import escape
from flask import (
    Blueprint, render_template, request, g, jsonify,
)

from webapp.auth import login_required, role_required
from webapp.dates import resolve_date_range, PERIOD_PRESETS, DEFAULT_PERIOD
from icp_db import (
    list_contacts,
    get_contact_by_id,
    get_contact_interactions,
    update_contact_notes,
    update_contact_company,
    update_contact_status_by_id,
    SourceProfile,
)

contacts_bp = Blueprint("contacts", __name__)


@contacts_bp.route("/contacts")
@login_required
def index():
    db = g.db
    profiles = db.query(SourceProfile).order_by(SourceProfile.code).all()

    # Default filter: ICP for all roles
    from flask import session as flask_session
    role = flask_session.get("role", "viewer")
    default_status = "ICP"

    return render_template(
        "contacts.html",
        profiles=profiles,
        default_status=default_status,
        role=role,
        period_presets=PERIOD_PRESETS,
        default_period=DEFAULT_PERIOD,
    )


@contacts_bp.route("/contacts/table")
@login_required
def table():
    """htmx partial: filtered, paginated, sorted contacts table."""
    db = g.db

    from flask import session as flask_session
    role = flask_session.get("role", "viewer")

    status = request.args.get("status", "")
    # Enforce viewer restriction
    if role == "viewer" and not status:
        status = "ICP"

    # Date range
    date_from, date_to, active_period = resolve_date_range(
        request.args.get("period"),
        request.args.get("date_from"),
        request.args.get("date_to"),
    )

    result = list_contacts(
        db,
        status=status or None,
        source_profile=request.args.get("source_profile") or None,
        company=request.args.get("company") or None,
        search=request.args.get("search") or None,
        sort_by=request.args.get("sort_by", "latest_interaction"),
        sort_dir=request.args.get("sort_dir", "desc"),
        page=int(request.args.get("page", 1)),
        per_page=50,
        date_from=date_from,
        date_to=date_to,
    )

    has_date_filter = active_period != "all"

    return render_template(
        "partials/contacts_table.html",
        contacts=result["items"],
        total=result["total"],
        page=result["page"],
        pages=result["pages"],
        sort_by=request.args.get("sort_by", "latest_interaction"),
        sort_dir=request.args.get("sort_dir", "desc"),
        has_date_filter=has_date_filter,
        # Pass current filters so pagination links can preserve them
        current_filters={
            "status": status,
            "source_profile": request.args.get("source_profile", ""),
            "company": request.args.get("company", ""),
            "search": request.args.get("search", ""),
            "period": active_period,
            "date_from": date_from.isoformat() if date_from else "",
            "date_to": date_to.isoformat() if date_to else "",
        },
    )


@contacts_bp.route("/contacts/<int:contact_id>")
@login_required
def detail(contact_id):
    db = g.db
    contact = get_contact_by_id(db, contact_id)
    if not contact:
        return render_template("base.html", error="Contact not found."), 404

    interactions = get_contact_interactions(db, contact_id)

    from flask import session as flask_session
    role = flask_session.get("role", "viewer")

    return render_template(
        "contact_detail.html",
        contact=contact,
        interactions=interactions,
        role=role,
    )


@contacts_bp.route("/contacts/<int:contact_id>/notes", methods=["PATCH"])
@role_required("editor")
def update_notes(contact_id):
    """htmx inline notes update."""
    db = g.db
    notes = request.form.get("notes", "")
    ok = update_contact_notes(db, contact_id, notes)
    if not ok:
        return "Contact not found", 404
    return f'<span class="saved-indicator">Saved</span>'


@contacts_bp.route("/contacts/<int:contact_id>/company", methods=["PATCH"])
@role_required("editor")
def update_company(contact_id):
    """htmx inline company update."""
    db = g.db
    company = request.form.get("company", "").strip()
    ok = update_contact_company(db, contact_id, company)
    if not ok:
        return "Contact not found", 404

    # Learn from company correction
    if company:
        contact = get_contact_by_id(db, contact_id)
        if contact and contact["status"] in ("ICP", "POI", "Not ICP"):
            from icp_process import learn_from_classification
            learn_from_classification(
                contact["name"],
                contact["title"],
                company,
                contact["status"],
            )

    display = escape(company) if company else "—"
    return f'{display} <span class="saved-indicator">Saved</span>'


@contacts_bp.route("/contacts/<int:contact_id>/status", methods=["PATCH"])
@role_required("editor")
def update_status(contact_id):
    """htmx inline status change."""
    db = g.db
    new_status = request.form.get("status", "")
    if new_status not in ("ICP", "POI", "Not ICP", "Review"):
        return "Invalid status", 400
    ok = update_contact_status_by_id(db, contact_id, new_status)
    if not ok:
        return "Contact not found", 404

    # Learn from this classification
    if new_status in ("ICP", "POI", "Not ICP"):
        contact = get_contact_by_id(db, contact_id)
        if contact:
            from icp_process import learn_from_classification
            learn_from_classification(
                contact["name"],
                contact["title"],
                contact["company"],
                new_status,
            )

    # Auto-sync to Zoho CRM when classified as ICP
    if new_status == "ICP":
        from webapp.zoho_helpers import trigger_zoho_sync
        trigger_zoho_sync(contact_id)

    return f'<span class="status-badge status-{new_status.lower().replace(" ", "")}">{new_status}</span> <span class="saved-indicator">Saved</span>'
