# app/leads/routes.py
# This module implements the lead management features, including:

from flask import Blueprint, render_template, request, redirect, url_for, flash, abort, jsonify, current_app
from flask_login import login_required, current_user
from sqlalchemy import or_, func, cast, String
from datetime import datetime, timedelta
from decimal import Decimal
from ..audit import log_audit
from .. import db
from ..utils import require_perm

from ..models import (
    Lead, LeadStatus, LeadSource, User,
    LeadActivity, ActivityType,
    Client, ClientBranch, EmployeeProfile, Industry, LeadService,
    CountryMaster, StateMaster, Opportunity,
    LeadAssignmentHistory, BranchContact, Project, Quote,
    ProformaInvoice, Invoice, OperationsJobcard, QuoteStatus,
    ExternalLeadSync, LeadLocationAssignmentRule
)
from ..whatsapp_utils import send_lead_assignment_whatsapp
from werkzeug.utils import secure_filename


leads_bp = Blueprint("leads", __name__, template_folder="../templates")


# -------------------------
# Access helpers
# -------------------------
def _team_user_ids(manager_user_id: int):
    """Return direct + nested reportees user_ids (recursive)."""
    seen = set()
    stack = [manager_user_id]

    while stack:
        mid = stack.pop()
        rows = (
            EmployeeProfile.query
            .filter(EmployeeProfile.reporting_manager_user_id == mid)
            .with_entities(EmployeeProfile.user_id)
            .all()
        )
        child_ids = [r[0] for r in rows if r[0] is not None and r[0] not in seen]
        for cid in child_ids:
            seen.add(cid)
            stack.append(cid)

    return list(seen)

def _clean(v):
    return (v or "").strip()

def _allowed_lead_owner_ids():
    """
    Who's leads can the current user see?
    - If user has leads.view_all => everyone
    - Else => self + reportees
    """
    if current_user.has_perm("leads.view_all"):
        return None

    team_ids = _team_user_ids(current_user.id)
    return [current_user.id] + team_ids


def _owner_options_for_current_user():
    """Users to show in Owner dropdowns (list & assign)."""
    allowed = _allowed_lead_owner_ids()
    if allowed is None:
        return User.query.filter_by(is_active=True).order_by(User.name.asc()).all()
    return User.query.filter(User.id.in_(allowed)).order_by(User.name.asc()).all()


def _enforce_lead_access(lead: Lead):
    allowed = _allowed_lead_owner_ids()
    if allowed is None:
        return True
    if lead.owner_id in allowed:
        return True
    abort(403)


# -------------------------
# Helpers
# -------------------------
def _lead_code_next():
    last = db.session.query(Lead).order_by(Lead.id.desc()).first()
    nxt = (last.id + 1) if last else 1
    return f"LD-{nxt:06d}"


def _parse_date(v):
    if not v:
        return None
    return datetime.strptime(v, "%Y-%m-%d").date()


def _lead_has_opportunity(lead_id: int) -> bool:
    if not lead_id:
        return False
    return Opportunity.query.filter_by(lead_id=lead_id).first() is not None


def _enforce_lead_not_converted(lead: Lead):
    if _lead_has_opportunity(lead.id):
        flash("This lead is already converted to an opportunity and can no longer be edited.", "warning")
        return False
    return True


def _branch_display_payload(branch):
    if not branch:
        return {
            "company_name": "",
            "branch_location": "",
            "city": "",
            "state": "",
            "country": "",
            "gst": "",
            "full_location": "",
            "contact_name": "",
            "contact_email": "",
            "contact_phone": "",
        }

    state_name = ""
    if getattr(branch, "state_master", None):
        state_name = branch.state_master.name or ""
    else:
        state_name = branch.state or ""

    country_name = ""
    if getattr(branch, "country_master", None):
        country_name = branch.country_master.name or ""
    else:
        country_name = branch.country or ""

    city = branch.city or ""
    branch_location = branch.branch_location or ""
    gst = branch.gst or ""

    location_parts = [x for x in [branch_location, city, state_name, country_name] if x]
    full_location = ", ".join(location_parts)

    primary_contact = (
        branch.contacts
        .filter_by(is_primary=True)
        .order_by(BranchContact.id.asc())
        .first()
    )

    if not primary_contact:
        primary_contact = branch.contacts.order_by(BranchContact.id.asc()).first()

    return {
        "company_name": branch.client.company_name if getattr(branch, "client", None) else "",
        "branch_location": branch_location,
        "city": city,
        "state": state_name,
        "country": country_name,
        "gst": gst,
        "full_location": full_location,
        "contact_name": primary_contact.name if primary_contact and primary_contact.name else "",
        "contact_email": primary_contact.email if primary_contact and primary_contact.email else "",
        "contact_phone": primary_contact.phone if primary_contact and primary_contact.phone else "",
    }

def _load_form_masters():
    """Keep masters in one place so we don't forget industries on error renders."""
    statuses = LeadStatus.query.filter_by(is_active=True).order_by(LeadStatus.sort_order.asc()).all()
    sources = LeadSource.query.filter_by(is_active=True).order_by(LeadSource.sort_order.asc()).all()
    clients = Client.query.filter_by(is_active=True).order_by(Client.company_name.asc()).all()
    industries = Industry.query.filter_by(is_active=True).order_by(Industry.sort_order.asc(), Industry.name.asc()).all()
    services = LeadService.query.filter_by(is_active=True).order_by(LeadService.sort_order.asc(), LeadService.name.asc()).all()
    return statuses, sources, clients, industries, services


# -------------------------
# Routes
# -------------------------
@leads_bp.route("/")
@login_required
@require_perm("leads.view")
def list_leads():
    q = (request.args.get("q") or "").strip()
    status_id = request.args.get("status_id") or ""
    source_id = request.args.get("source_id") or ""
    owner = request.args.get("owner") or ""
    service_id = request.args.get("service_id") or ""
    created_month = (request.args.get("created_month") or "").strip()
    lead_type = (request.args.get("lead_type") or "").strip()

    page = int(request.args.get("page", 1))
    per_page = 10

    query = Lead.query

    allowed_owner_ids = _allowed_lead_owner_ids()
    if allowed_owner_ids is not None:
        query = query.filter(Lead.owner_id.in_(allowed_owner_ids))

    if q:
        like = f"%{q}%"
        query = query.filter(or_(
            Lead.name.ilike(like),
            Lead.company.ilike(like),
            Lead.email.ilike(like),
            Lead.phone.ilike(like),
            Lead.lead_code.ilike(like),
        ))

    if status_id.isdigit():
        query = query.filter(Lead.status_id == int(status_id))

    if source_id.isdigit():
        query = query.filter(Lead.source_id == int(source_id))

    if service_id.isdigit():
        query = query.filter(Lead.service_id == int(service_id))

    if lead_type in ("Corporate", "Individual"):
        query = query.filter(Lead.lead_type == lead_type)

    if created_month:
        try:
            month_start = datetime.strptime(created_month, "%Y-%m")
            if month_start.month == 12:
                next_month = datetime(month_start.year + 1, 1, 1)
            else:
                next_month = datetime(month_start.year, month_start.month + 1, 1)

            query = query.filter(Lead.created_at >= month_start)
            query = query.filter(Lead.created_at < next_month)
        except ValueError:
            flash("Invalid month filter.", "warning")

    if owner == "me":
        query = query.filter(Lead.owner_id == current_user.id)
    elif owner.isdigit():
        oid = int(owner)
        if allowed_owner_ids is None or oid in allowed_owner_ids:
            query = query.filter(Lead.owner_id == oid)
        else:
            query = query.filter(Lead.owner_id == current_user.id)

    query = query.order_by(Lead.created_at.desc())

    pagination = query.paginate(page=page, per_page=per_page, error_out=False)
    services = LeadService.query.filter_by(is_active=True).order_by(LeadService.sort_order.asc(), LeadService.name.asc()).all()
    statuses = LeadStatus.query.filter_by(is_active=True).order_by(LeadStatus.sort_order.asc()).all()
    sources = LeadSource.query.filter_by(is_active=True).order_by(LeadSource.sort_order.asc()).all()
    owner_options = _owner_options_for_current_user()

    return render_template(
        "leads/list.html",
        pagination=pagination,
        q=q,
        status_id=status_id,
        source_id=source_id,
        service_id=service_id,
        owner=owner,
        created_month=created_month,
        lead_type=lead_type,
        statuses=statuses,
        sources=sources,
        services=services,
        owner_options=owner_options,
        allowed_owner_ids=allowed_owner_ids,
    )

@leads_bp.route("/new", methods=["GET", "POST"])
@login_required
@require_perm("leads.create")
def create_lead():
    statuses, sources, clients, industries, services = _load_form_masters()

    if request.method == "POST":
        client_id_raw = (request.form.get("client_id") or "").strip()
        branch_id_raw = (request.form.get("branch_id") or "").strip()
        client_id = int(client_id_raw) if client_id_raw.isdigit() else None
        branch_id = int(branch_id_raw) if branch_id_raw.isdigit() else None

        if branch_id and not client_id:
            flash("Please select Client first before selecting Branch.", "danger")
            return render_template(
                "leads/form.html",
                mode="create", lead=None,
                statuses=statuses, sources=sources, clients=clients, industries=industries, services=services
            )

        # Existing-customer leads must always be tied to a specific client branch.
        # This prevents ambiguous leads that have client_id populated while
        # branch_id is NULL. New/prospect leads can still be created without
        # selecting either an existing client or a branch.
        if client_id and not branch_id:
            flash("Please select a Client Branch for the selected existing client.", "danger")
            return render_template(
                "leads/form.html",
                mode="create", lead=None,
                statuses=statuses, sources=sources, clients=clients, industries=industries, services=services
            )

        selected_branch = None
        if client_id and branch_id:
            selected_branch = ClientBranch.query.get(branch_id)
            if not selected_branch or selected_branch.client_id != client_id:
                flash("Selected branch does not belong to selected client.", "danger")
                return render_template(
                    "leads/form.html",
                    mode="create", lead=None,
                    statuses=statuses, sources=sources, clients=clients, industries=industries, services=services
                )

        branch_payload = _branch_display_payload(selected_branch) if selected_branch else None
        lead_type = (request.form.get("lead_type") or "Corporate").strip()
        if lead_type not in ("Corporate", "Individual"):
            lead_type = "Corporate"
            
        lead = Lead(
            lead_code=_lead_code_next(),
            name=(
                branch_payload["contact_name"]
                if selected_branch and branch_payload and branch_payload["contact_name"]
                else (request.form.get("name") or "").strip()
            ),
            company=(
                selected_branch.client.company_name
                if selected_branch and getattr(selected_branch, "client", None)
                else (request.form.get("company") or "").strip()
            ),
            location=(
                branch_payload["full_location"]
                if selected_branch and branch_payload
                else (request.form.get("location") or "").strip()
            ),
            email=(
                (branch_payload["contact_email"] or "").strip().lower()
                if selected_branch and branch_payload and branch_payload["contact_email"]
                else (request.form.get("email") or "").strip().lower()
            ),
            phone_country=(request.form.get("phone_country") or "+91").strip(),
            phone=(
                (branch_payload["contact_phone"] or "").strip()
                if selected_branch and branch_payload and branch_payload["contact_phone"]
                else (request.form.get("phone") or "").strip()
            ),
            industry_id=int(request.form.get("industry_id")) if (request.form.get("industry_id") or "").isdigit() else None,
            website=(request.form.get("website") or "").strip(),
            notes=(request.form.get("notes") or "").strip(),
            owner_id=current_user.id,
            status_id=int(request.form.get("status_id")) if (request.form.get("status_id") or "").isdigit() else None,
            source_id=int(request.form.get("source_id")) if (request.form.get("source_id") or "").isdigit() else None,
            service_id=int(request.form.get("service_id")) if (request.form.get("service_id") or "").isdigit() else None,
            client_id=client_id,
            branch_id=branch_id,
            estimated_closure_date=_parse_date(request.form.get("estimated_closure_date")),
            lead_type=lead_type,
        )

        if not lead.name:
            flash("Lead name is required.", "danger")
            return render_template(
                "leads/form.html",
                mode="create", lead=lead,
                statuses=statuses, sources=sources, clients=clients, industries=industries, services=services
            )

        db.session.add(lead)
        db.session.commit()

        log_audit("Lead", lead.id, "CREATE")
        flash("Lead created successfully ✅", "success")
        return redirect(url_for("leads.list_leads"))

    return render_template(
        "leads/form.html",
        mode="create", lead=None,
        statuses=statuses, sources=sources, clients=clients, industries=industries, services=services
    )


@leads_bp.route("/<int:lead_id>/edit", methods=["GET", "POST"])
@login_required
@require_perm("leads.edit")
def edit_lead(lead_id):
    lead = Lead.query.get_or_404(lead_id)
    _enforce_lead_access(lead)

    if not _enforce_lead_not_converted(lead):
        return redirect(url_for("leads.view_lead", lead_id=lead.id))

    statuses, sources, clients, industries, services = _load_form_masters()

    if request.method == "POST":
        old_name = lead.name

        client_id_raw = (request.form.get("client_id") or "").strip()
        branch_id_raw = (request.form.get("branch_id") or "").strip()
        client_id = int(client_id_raw) if client_id_raw.isdigit() else None
        branch_id = int(branch_id_raw) if branch_id_raw.isdigit() else None
        
            
        if branch_id and not client_id:
            flash("Please select Client first before selecting Branch.", "danger")
            return render_template(
                "leads/form.html",
                mode="edit", lead=lead,
                statuses=statuses, sources=sources, clients=clients, industries=industries, services=services
            )

        # Keep the same invariant while editing: if an existing client is
        # selected, a branch belonging to that client is mandatory.
        if client_id and not branch_id:
            flash("Please select a Client Branch for the selected existing client.", "danger")
            return render_template(
                "leads/form.html",
                mode="edit", lead=lead,
                statuses=statuses, sources=sources, clients=clients, industries=industries, services=services
            )

        selected_branch = None
        if client_id and branch_id:
            selected_branch = ClientBranch.query.get(branch_id)
            if not selected_branch or selected_branch.client_id != client_id:
                flash("Selected branch does not belong to selected client.", "danger")
                return render_template(
                    "leads/form.html",
                    mode="edit", lead=lead,
                    statuses=statuses, sources=sources, clients=clients, industries=industries, services=services
                )

        branch_payload = _branch_display_payload(selected_branch) if selected_branch else None
        lead_type = (request.form.get("lead_type") or "Corporate").strip()
        if lead_type not in ("Corporate", "Individual"):
            lead_type = "Corporate"

        lead.name = (
            branch_payload["contact_name"]
            if selected_branch and branch_payload and branch_payload["contact_name"]
            else (request.form.get("name") or "").strip()
        )
        lead.company = (
            selected_branch.client.company_name
            if selected_branch and getattr(selected_branch, "client", None)
            else (request.form.get("company") or "").strip()
        )
        lead.location = (
            branch_payload["full_location"]
            if selected_branch and branch_payload
            else (request.form.get("location") or "").strip()
        )
        lead.email = (
            (branch_payload["contact_email"] or "").strip().lower()
            if selected_branch and branch_payload and branch_payload["contact_email"]
            else (request.form.get("email") or "").strip().lower()
        )
        lead.phone_country = (request.form.get("phone_country") or "+91").strip()
        lead.phone = (
            (branch_payload["contact_phone"] or "").strip()
            if selected_branch and branch_payload and branch_payload["contact_phone"]
            else (request.form.get("phone") or "").strip()
        )
        lead.industry_id = int(request.form.get("industry_id")) if (request.form.get("industry_id") or "").isdigit() else None
        lead.website = (request.form.get("website") or "").strip()
        lead.notes = (request.form.get("notes") or "").strip()
        lead.service_id = int(request.form.get("service_id")) if (request.form.get("service_id") or "").isdigit() else None
        lead.status_id = int(request.form.get("status_id")) if (request.form.get("status_id") or "").isdigit() else None
        lead.source_id = int(request.form.get("source_id")) if (request.form.get("source_id") or "").isdigit() else None
        lead.client_id = client_id
        lead.branch_id = branch_id
        lead.estimated_closure_date = _parse_date(request.form.get("estimated_closure_date"))
        lead.lead_type = lead_type

        if not lead.name:
            flash("Lead name is required.", "danger")
            return render_template(
                "leads/form.html",
                mode="edit", lead=lead,
                statuses=statuses, sources=sources, clients=clients, industries=industries, services=services
            )

        db.session.commit()

        if old_name != lead.name:
            log_audit("Lead", lead.id, "UPDATE", "name", old_name, lead.name)

        flash("Lead updated ✅", "success")
        return redirect(url_for("leads.view_lead", lead_id=lead.id))

    return render_template(
        "leads/form.html",
        mode="edit", lead=lead,
        statuses=statuses, sources=sources, clients=clients, industries=industries, services=services
    )


@leads_bp.route("/<int:lead_id>")
@login_required
@require_perm("leads.view")
def view_lead(lead_id):
    lead = Lead.query.get_or_404(lead_id)
    _enforce_lead_access(lead)

    activity_types = ActivityType.query.filter_by(is_active=True).order_by(ActivityType.sort_order.asc()).all()
    activities = (
        LeadActivity.query
        .filter_by(lead_id=lead.id)
        .order_by(LeadActivity.activity_at.desc(), LeadActivity.id.desc())
        .limit(50)
        .all()
    )
    owner_options = _owner_options_for_current_user()
    has_opportunity = _lead_has_opportunity(lead.id)

    return render_template(
        "leads/view.html",
        lead=lead,
        activity_types=activity_types,
        activities=activities,
        owner_options=owner_options,
        has_opportunity=has_opportunity
    )


@leads_bp.route("/<int:lead_id>/activities/new", methods=["POST"])
@login_required
@require_perm("activities.create")
def add_activity(lead_id):
    lead = Lead.query.get_or_404(lead_id)
    _enforce_lead_access(lead)

    activity_type_id = request.form.get("activity_type_id")
    subject = (request.form.get("subject") or "").strip()
    outcome = (request.form.get("outcome") or "").strip()
    notes = (request.form.get("notes") or "").strip()

    activity_at_raw = request.form.get("activity_at")
    next_follow_raw = request.form.get("next_follow_up_at")

    def parse_dt(v):
        if not v:
            return None
        return datetime.strptime(v, "%Y-%m-%dT%H:%M")

    activity_at = parse_dt(activity_at_raw) or datetime.utcnow()
    next_follow = parse_dt(next_follow_raw)

    act = LeadActivity(
        lead_id=lead.id,
        activity_type_id=int(activity_type_id) if (activity_type_id or "").isdigit() else None,
        subject=subject,
        outcome=outcome,
        notes=notes,
        activity_at=activity_at,
        next_follow_up_at=next_follow,
        created_by_id=current_user.id
    )
    db.session.add(act)

    new_status_id = request.form.get("new_status_id")
    if (new_status_id or "").isdigit():
        lead.status_id = int(new_status_id)

    db.session.commit()
    flash("Activity added ✅", "success")
    return redirect(url_for("leads.view_lead", lead_id=lead.id))


@leads_bp.route("/follow-ups")
@login_required
@require_perm("activities.view")
def followups():
    now = datetime.now()

    try:
        days = int(request.args.get("days", 7))
    except (TypeError, ValueError):
        days = 7
    days = max(1, min(days, 90))

    owner = (request.args.get("owner") or "me").strip()
    activity_type_id = (request.args.get("activity_type_id") or "").strip()
    q = (request.args.get("q") or "").strip()
    timing = (request.args.get("timing") or "upcoming").strip().lower()

    today_start = datetime.combine(now.date(), datetime.min.time())
    tomorrow_start = today_start + timedelta(days=1)
    end = now + timedelta(days=days)

    allowed_owner_ids = _allowed_lead_owner_ids()

    query = (
        LeadActivity.query
        .join(Lead, LeadActivity.lead_id == Lead.id)
        .filter(LeadActivity.next_follow_up_at.isnot(None))
    )

    if allowed_owner_ids is not None:
        query = query.filter(Lead.owner_id.in_(allowed_owner_ids))

    if owner == "me":
        query = query.filter(Lead.owner_id == current_user.id)
    elif owner == "all":
        if allowed_owner_ids is not None:
            query = query.filter(Lead.owner_id.in_(allowed_owner_ids))
    elif owner.isdigit():
        owner_id = int(owner)
        if allowed_owner_ids is None or owner_id in allowed_owner_ids:
            query = query.filter(Lead.owner_id == owner_id)
        else:
            owner = "me"
            query = query.filter(Lead.owner_id == current_user.id)
    else:
        owner = "me"
        query = query.filter(Lead.owner_id == current_user.id)

    if timing == "overdue":
        query = query.filter(LeadActivity.next_follow_up_at < now)
    elif timing == "today":
        query = query.filter(
            LeadActivity.next_follow_up_at >= today_start,
            LeadActivity.next_follow_up_at < tomorrow_start,
        )
    else:
        timing = "upcoming"
        query = query.filter(
            LeadActivity.next_follow_up_at >= now,
            LeadActivity.next_follow_up_at <= end,
        )

    if activity_type_id.isdigit():
        query = query.filter(LeadActivity.activity_type_id == int(activity_type_id))

    if q:
        like = f"%{q}%"
        query = query.filter(or_(
            Lead.name.ilike(like),
            Lead.company.ilike(like),
            Lead.lead_code.ilike(like),
            Lead.email.ilike(like),
            Lead.phone.ilike(like),
            LeadActivity.subject.ilike(like),
            LeadActivity.outcome.ilike(like),
            LeadActivity.notes.ilike(like),
        ))

    items = (
        query
        .order_by(LeadActivity.next_follow_up_at.asc(), LeadActivity.id.asc())
        .limit(500)
        .all()
    )

    return render_template(
        "leads/followups.html",
        items=items,
        days=days,
        owner=owner,
        timing=timing,
        q=q,
        activity_type_id=activity_type_id,
        owner_options=_owner_options_for_current_user(),
        activity_types=ActivityType.query.filter_by(is_active=True).order_by(
            ActivityType.sort_order.asc(), ActivityType.name.asc()
        ).all(),
        now=now,
    )


@leads_bp.route("/<int:lead_id>/assign", methods=["POST"])
@login_required
@require_perm("leads.assign")
def assign_lead(lead_id):
    lead = Lead.query.get_or_404(lead_id)
    _enforce_lead_access(lead)

    new_owner_id = request.form.get("owner_id")
    if not new_owner_id or not new_owner_id.isdigit():
        flash("Invalid user selected.", "danger")
        return redirect(url_for("leads.view_lead", lead_id=lead.id))

    new_owner_id = int(new_owner_id)
    allowed = _allowed_lead_owner_ids()

    if allowed is not None and new_owner_id not in allowed:
        flash("You can only assign leads within your team.", "danger")
        return redirect(url_for("leads.view_lead", lead_id=lead.id))

    old_owner_id = lead.owner_id
    old_owner = lead.owner.name if lead.owner else None

    if old_owner_id == new_owner_id:
        flash("Lead is already assigned to this user.", "warning")
        return redirect(url_for("leads.view_lead", lead_id=lead.id))

    lead.owner_id = new_owner_id

    history = LeadAssignmentHistory(
        lead_id=lead.id,
        assigned_by_id=current_user.id,
        old_owner_id=old_owner_id,
        new_owner_id=new_owner_id
    )
    db.session.add(history)
    db.session.commit()

    new_owner = User.query.get(new_owner_id)

    log_audit(
        "Lead",
        lead.id,
        "ASSIGN",
        "owner",
        old_owner,
        new_owner.name if new_owner else str(new_owner_id)
    )

    # Send assignment email, but do not block assignment if mail fails
    #email_sent = False
    #email_error = None

    #if new_owner and new_owner.email:
    #    result = send_lead_assignment_email(
    #        lead=lead,
    #        assigned_user=new_owner,
    #        assigned_by=current_user
    #    )

        # Supports both old return style: (sent, error)
        # and new return style: (sent, error, mail_log_id)
    #    if isinstance(result, tuple):
    #        email_sent = result[0] if len(result) > 0 else False
    #        email_error = result[1] if len(result) > 1 else None
    #    else:
    #        email_sent = bool(result)
    #        email_error = None if email_sent else "Email sending failed."
    #else:
    #    email_error = "New owner email not found."

    # Send WhatsApp assignment notification, but do not block assignment if it fails
    wa_sent = False
    wa_error = None

    if new_owner:
        wa_sent, wa_error = send_lead_assignment_whatsapp(
            lead=lead,
            assigned_user=new_owner,
            assigned_by=current_user
        )
    else:
        wa_error = "New owner not found."
    
    if wa_sent:
        flash("Lead reassigned successfully ✅ WhatsApp sent.", "success")
    else:
        flash(
            f"Lead reassigned successfully, but WhatsApp could not be sent: {wa_error}",
            "warning"
        )

    return redirect(url_for("leads.view_lead", lead_id=lead.id))

@leads_bp.route("/assignment-history")
@login_required
@require_perm("leads.view")
def lead_assignment_history():
    q = (request.args.get("q") or "").strip()
    assigned_by = request.args.get("assigned_by") or ""
    new_owner = request.args.get("new_owner") or ""
    company = (request.args.get("company") or "").strip()
    created_month = (request.args.get("created_month") or datetime.utcnow().strftime("%Y-%m")).strip()
    lead_type = (request.args.get("lead_type") or "").strip()
    service_id = request.args.get("service_id") or ""

    page = int(request.args.get("page", 1))
    per_page = 20

    query = LeadAssignmentHistory.query.join(Lead, LeadAssignmentHistory.lead_id == Lead.id)

    allowed_owner_ids = _allowed_lead_owner_ids()
    if allowed_owner_ids is not None:
        query = query.filter(
            or_(
                LeadAssignmentHistory.assigned_by_id == current_user.id,
                Lead.owner_id.in_(allowed_owner_ids),
                LeadAssignmentHistory.old_owner_id.in_(allowed_owner_ids),
                LeadAssignmentHistory.new_owner_id.in_(allowed_owner_ids),
            )
        )

    if q:
        like = f"%{q}%"
        query = query.filter(or_(
            Lead.name.ilike(like),
            Lead.company.ilike(like),
            Lead.lead_code.ilike(like),
        ))

    if company:
        query = query.filter(Lead.company.ilike(f"%{company}%"))
    
    if lead_type in ("Corporate", "Individual"):
        query = query.filter(Lead.lead_type == lead_type)

    if service_id.isdigit():
        query = query.filter(Lead.service_id == int(service_id))

    if created_month:
        try:
            month_start = datetime.strptime(created_month, "%Y-%m")
            if month_start.month == 12:
                next_month = datetime(month_start.year + 1, 1, 1)
            else:
                next_month = datetime(month_start.year, month_start.month + 1, 1)

            query = query.filter(LeadAssignmentHistory.assigned_at >= month_start)
            query = query.filter(LeadAssignmentHistory.assigned_at < next_month)
        except ValueError:
            flash("Invalid month filter.", "warning")

    if assigned_by.isdigit():
        query = query.filter(LeadAssignmentHistory.assigned_by_id == int(assigned_by))

    if new_owner.isdigit():
        query = query.filter(LeadAssignmentHistory.new_owner_id == int(new_owner))

    all_rows = (
        query
        .order_by(
            LeadAssignmentHistory.lead_id.asc(),
            LeadAssignmentHistory.assigned_at.asc(),
            LeadAssignmentHistory.id.asc()
        )
        .all()
    )

    lead_summary_map = {}

    for row in all_rows:
        lead_id = row.lead_id

        if lead_id not in lead_summary_map:
            lead_summary_map[lead_id] = {
                "lead": row.lead,
                "first_from_user": row.old_owner,
                "latest_to_user": row.new_owner,
                "latest_assigned_by": row.assigned_by,
                "latest_assigned_at": row.assigned_at,
                "history_count": 1,
                "latest_history_id": row.id,
            }
        else:
            lead_summary_map[lead_id]["latest_to_user"] = row.new_owner
            lead_summary_map[lead_id]["latest_assigned_by"] = row.assigned_by
            lead_summary_map[lead_id]["latest_assigned_at"] = row.assigned_at
            lead_summary_map[lead_id]["latest_history_id"] = row.id
            lead_summary_map[lead_id]["history_count"] += 1

    summary_rows = sorted(
        lead_summary_map.values(),
        key=lambda x: x["latest_assigned_at"] or datetime.min,
        reverse=True
    )

    total_items = len(summary_rows)
    start = (page - 1) * per_page
    end = start + per_page
    paginated_rows = summary_rows[start:end]

    class SimplePagination:
        def __init__(self, items, page, per_page, total):
            self.items = items
            self.page = page
            self.per_page = per_page
            self.total = total
            self.pages = (total + per_page - 1) // per_page

        @property
        def has_prev(self):
            return self.page > 1

        @property
        def has_next(self):
            return self.page < self.pages

        @property
        def prev_num(self):
            return self.page - 1

        @property
        def next_num(self):
            return self.page + 1

        def iter_pages(self, left_edge=2, left_current=2, right_current=3, right_edge=2):
            last = 0
            for num in range(1, self.pages + 1):
                if (
                    num <= left_edge
                    or (num > self.page - left_current - 1 and num < self.page + right_current)
                    or num > self.pages - right_edge
                ):
                    if last + 1 != num:
                        yield None
                    yield num
                    last = num

    pagination = SimplePagination(paginated_rows, page, per_page, total_items)
    current_month = datetime.utcnow().strftime("%Y-%m")
    users = _owner_options_for_current_user()

    services = LeadService.query.filter_by(is_active=True).order_by(
        LeadService.sort_order.asc(),
        LeadService.name.asc()
    ).all()
    
    return render_template(
        "leads/assignment_history.html",
        pagination=pagination,
        q=q,
        assigned_by=assigned_by,
        current_month=current_month,
        new_owner=new_owner,
        company=company,
        created_month=created_month,
        lead_type=lead_type,
        users=users,
        service_id=service_id,
        services=services,
    )

@leads_bp.route("/<int:lead_id>/assignment-history")
@login_required
@require_perm("leads.view")
def lead_assignment_history_detail(lead_id):
    lead = Lead.query.get_or_404(lead_id)
    _enforce_lead_access(lead)

    rows = (
        LeadAssignmentHistory.query
        .filter_by(lead_id=lead.id)
        .order_by(LeadAssignmentHistory.assigned_at.desc(), LeadAssignmentHistory.id.desc())
        .all()
    )

    return render_template(
        "leads/assignment_history_detail.html",
        lead=lead,
        rows=rows
    )
# -------- API: Branch dropdown for a client --------
@leads_bp.route("/api/client/<int:client_id>/branches")
@login_required
@require_perm("leads.view")
def api_client_branches(client_id):
    branches = (
        ClientBranch.query
        .filter_by(client_id=client_id, is_active=True)
        .order_by(ClientBranch.branch_location.asc())
        .all()
    )

    out = []
    for b in branches:
        payload = _branch_display_payload(b)
        out.append({
            "id": b.id,
            "name": b.branch_location,
            "company_name": payload["company_name"],
            "branch_location": payload["branch_location"],
            "city": payload["city"],
            "state": payload["state"],
            "country": payload["country"],
            "gst": payload["gst"],
            "full_location": payload["full_location"],
            "contact_name": payload["contact_name"],
            "contact_email": payload["contact_email"],
            "contact_phone": payload["contact_phone"],
        })
    return jsonify(out)

@leads_bp.route("/import", methods=["GET", "POST"])
@login_required
@require_perm("leads.create")
def import_leads():
    from openpyxl import load_workbook

    if request.method == "POST":
        f = request.files.get("file")
        if not f or not f.filename:
            flash("Please select an Excel file.", "danger")
            return redirect(url_for("leads.import_leads"))

        filename = secure_filename(f.filename)
        if not filename.lower().endswith((".xlsx", ".xlsm")):
            flash("Only .xlsx/.xlsm supported.", "danger")
            return redirect(url_for("leads.import_leads"))

        wb = load_workbook(f, data_only=True)
        ws = wb.active

        headers = {}
        for c in range(1, ws.max_column + 1):
            v = (ws.cell(row=1, column=c).value or "")
            key = str(v).strip().lower()
            if key:
                headers[key] = c

        def col(key):
            return headers.get(key)

        required = ["name"]
        missing = [k for k in required if col(k) is None]
        if missing:
            flash(f"Missing required columns: {', '.join(missing)}", "danger")
            return redirect(url_for("leads.import_leads"))

        status_map = {s.name.strip().lower(): s.id for s in LeadStatus.query.filter_by(is_active=True).all()}
        source_map = {s.name.strip().lower(): s.id for s in LeadSource.query.filter_by(is_active=True).all()}
        industry_map = {i.name.strip().lower(): i.id for i in Industry.query.filter_by(is_active=True).all()}
        service_map = {s.name.strip().lower(): s.id for s in LeadService.query.filter_by(is_active=True).all()}

        created = 0
        skipped = 0
        errors = []

        next_id = (db.session.query(func.coalesce(func.max(Lead.id), 0)).scalar() or 0) + 1

        for r in range(2, ws.max_row + 1):
            try:
                name = (ws.cell(r, col("name")).value or "").strip() if col("name") else ""
                if not name:
                    skipped += 1
                    continue

                company = ws.cell(r, col("company")).value if col("company") else ""
                email = ws.cell(r, col("email")).value if col("email") else ""
                phone_country = ws.cell(r, col("phone_country")).value if col("phone_country") else "+91"
                phone = ws.cell(r, col("phone")).value if col("phone") else ""
                location = ws.cell(r, col("location")).value if col("location") else ""
                website = ws.cell(r, col("website")).value if col("website") else ""
                notes = ws.cell(r, col("notes")).value if col("notes") else ""

                service_name = (ws.cell(r, col("service")).value or "").strip() if col("service") else ""
                service_id = None
                if service_name:
                    key = service_name.lower()
                    service_id = service_map.get(key)
                    if not service_id:
                        new_s = LeadService(name=service_name, is_active=True, sort_order=0)
                        db.session.add(new_s)
                        db.session.flush()
                        service_id = new_s.id
                        service_map[key] = service_id

                industry_name = (ws.cell(r, col("industry")).value or "").strip() if col("industry") else ""
                industry_id = None
                if industry_name:
                    key = industry_name.lower()
                    industry_id = industry_map.get(key)
                    if not industry_id:
                        new_i = Industry(name=industry_name, is_active=True, sort_order=0)
                        db.session.add(new_i)
                        db.session.flush()
                        industry_id = new_i.id
                        industry_map[key] = industry_id

                status_name = (ws.cell(r, col("status")).value or "")
                source_name = (ws.cell(r, col("source")).value or "")
                status_key = str(status_name).strip().lower() if status_name else ""
                source_key = str(source_name).strip().lower() if source_name else ""

                lead_code = f"LD-{next_id:06d}"
                next_id += 1

                lead = Lead(
                    lead_code=lead_code,
                    name=str(name).strip(),
                    company=str(company or "").strip(),
                    email=str(email or "").strip().lower(),
                    phone_country=str(phone_country or "+91").strip(),
                    phone=str(phone or "").strip(),
                    location=str(location or "").strip(),
                    industry_id=industry_id,
                    website=str(website or "").strip(),
                    notes=str(notes or "").strip(),
                    owner_id=current_user.id,
                    status_id=status_map.get(status_key) if status_key else None,
                    source_id=source_map.get(source_key) if source_key else None,
                    service_id=service_id,
                )
                db.session.add(lead)
                created += 1

            except Exception as e:
                errors.append(f"Row {r}: {str(e)}")

        db.session.commit()

        msg = f"Imported: {created}, Skipped: {skipped}"
        if errors:
            msg += f" (Errors: {len(errors)})"
        flash(msg, "success" if created else "warning")

        return render_template("leads/import.html", errors=errors)

    return render_template("leads/import.html", errors=None)

@leads_bp.route("/today-followups")
@login_required
@require_perm("activities.view")
def today_followups_dashboard():
    # Use application/server local time so the dashboard follows the business day.
    now = datetime.now()
    today = now.date()
    start_dt = datetime.combine(today, datetime.min.time())
    end_dt = start_dt + timedelta(days=1)

    allowed_owner_ids = _allowed_lead_owner_ids()

    selected_owner = (request.args.get("owner") or "me").strip()
    activity_type_id = (request.args.get("activity_type_id") or "").strip()
    time_slot = (request.args.get("time_slot") or "all").strip().lower()
    q = (request.args.get("q") or "").strip()

    base_query = (
        LeadActivity.query
        .join(Lead, LeadActivity.lead_id == Lead.id)
        .filter(LeadActivity.next_follow_up_at.isnot(None))
        .filter(LeadActivity.next_follow_up_at >= start_dt)
        .filter(LeadActivity.next_follow_up_at < end_dt)
    )

    if allowed_owner_ids is not None:
        base_query = base_query.filter(Lead.owner_id.in_(allowed_owner_ids))

    # Calculate dashboard totals before applying the selected-owner filter.
    visible_count = base_query.count()
    my_count = base_query.filter(Lead.owner_id == current_user.id).count()
    overdue_today_count = base_query.filter(LeadActivity.next_follow_up_at < now).count()
    remaining_today_count = base_query.filter(LeadActivity.next_follow_up_at >= now).count()

    query = base_query

    if selected_owner == "me":
        query = query.filter(Lead.owner_id == current_user.id)
    elif selected_owner == "all":
        pass
    elif selected_owner.isdigit():
        owner_id = int(selected_owner)
        if allowed_owner_ids is None or owner_id in allowed_owner_ids:
            query = query.filter(Lead.owner_id == owner_id)
        else:
            selected_owner = "me"
            query = query.filter(Lead.owner_id == current_user.id)
    else:
        selected_owner = "me"
        query = query.filter(Lead.owner_id == current_user.id)

    if activity_type_id.isdigit():
        query = query.filter(LeadActivity.activity_type_id == int(activity_type_id))

    if time_slot == "overdue":
        query = query.filter(LeadActivity.next_follow_up_at < now)
    elif time_slot == "remaining":
        query = query.filter(LeadActivity.next_follow_up_at >= now)
    elif time_slot == "morning":
        query = query.filter(
            func.hour(LeadActivity.next_follow_up_at) >= 0,
            func.hour(LeadActivity.next_follow_up_at) < 12,
        )
    elif time_slot == "afternoon":
        query = query.filter(
            func.hour(LeadActivity.next_follow_up_at) >= 12,
            func.hour(LeadActivity.next_follow_up_at) < 17,
        )
    elif time_slot == "evening":
        query = query.filter(func.hour(LeadActivity.next_follow_up_at) >= 17)
    else:
        time_slot = "all"

    if q:
        like = f"%{q}%"
        query = query.filter(or_(
            Lead.name.ilike(like),
            Lead.company.ilike(like),
            Lead.lead_code.ilike(like),
            Lead.email.ilike(like),
            Lead.phone.ilike(like),
            LeadActivity.subject.ilike(like),
            LeadActivity.outcome.ilike(like),
            LeadActivity.notes.ilike(like),
        ))

    items = (
        query
        .order_by(LeadActivity.next_follow_up_at.asc(), LeadActivity.id.asc())
        .all()
    )

    return render_template(
        "leads/today_followups_dashboard.html",
        items=items,
        today=today,
        now=now,
        owner_options=_owner_options_for_current_user(),
        activity_types=ActivityType.query.filter_by(is_active=True).order_by(
            ActivityType.sort_order.asc(), ActivityType.name.asc()
        ).all(),
        selected_owner=selected_owner,
        activity_type_id=activity_type_id,
        time_slot=time_slot,
        q=q,
        my_count=my_count,
        visible_count=visible_count,
        overdue_today_count=overdue_today_count,
        remaining_today_count=remaining_today_count,
    )


@leads_bp.route("/billing-report")
@login_required
@require_perm("leads.view")
def lead_billing_report():
    month = request.args.get("month", type=int)
    year = request.args.get("year", type=int)
    user_id = request.args.get("user_id", type=int)
    billing_status = _clean(request.args.get("billing_status") or "all")

    today = datetime.utcnow().date()
    if not month:
        month = today.month
    if not year:
        year = today.year

    allowed_user_ids = _allowed_lead_owner_ids()
    users = _owner_options_for_current_user()

    selected_user_id = user_id
    if selected_user_id and allowed_user_ids is not None and selected_user_id not in allowed_user_ids:
        selected_user_id = current_user.id

    lead_query = Lead.query.filter(
        func.month(Lead.created_at) == month,
        func.year(Lead.created_at) == year
    )

    leads = lead_query.order_by(Lead.created_at.desc(), Lead.id.desc()).all()

    rows = []
    summary = {
        "total_leads": 0,
        "billed": 0,
        "unbilled": 0,
        "jobcard_generated": 0,
        "jobcard_not_generated": 0,
        "total_amount": Decimal("0"),
    }

    for lead in leads:
        first_history = (
            LeadAssignmentHistory.query
            .filter_by(lead_id=lead.id)
            .order_by(
                LeadAssignmentHistory.assigned_at.asc(),
                LeadAssignmentHistory.id.asc()
            )
            .first()
        )

        # Original creator/owner:
        # If reassigned, first old_owner is the original owner.
        # If never reassigned, current owner is still the original owner.
        lead_created_by = (
            first_history.old_owner
            if first_history and first_history.old_owner
            else lead.owner
        )

        if selected_user_id:
            if not lead_created_by or lead_created_by.id != selected_user_id:
                continue
        elif allowed_user_ids is not None:
            if not lead_created_by or lead_created_by.id not in allowed_user_ids:
                continue

        opportunities = Opportunity.query.filter_by(lead_id=lead.id).all()

        lead_projects = []
        has_billed = False
        has_jobcard = False
        lead_amount = Decimal("0")

        for opp in opportunities:
            quotes = Quote.query.filter_by(opportunity_id=opp.id).all()

            for quote in quotes:
                project = Project.query.filter_by(quote_id=quote.id).first()

                if project:
                    project_amount = Decimal(str(project.contract_value or 0))
                    project_status = (project.jobcard_status or "").strip().lower()

                    is_billed = (
                        project_status == "billed"
                        or bool(project.pms_bill_no)
                        or bool(project.pms_bill_date)
                    )

                    if project.jobcard_no:
                        has_jobcard = True

                    if is_billed:
                        has_billed = True
                else:
                    project_amount = Decimal(str((quote.subtotal or 0) - (quote.discount or 0)))
                    project_status = ""
                    is_billed = False

                lead_amount += project_amount

                lead_projects.append({
                    "opportunity": opp,
                    "quote": quote,
                    "project": project,
                    "amount": project_amount,
                    "is_billed": is_billed,
                    "project_status": project_status,
                })

        lead_billing_status = "Billed" if has_billed else "Unbilled"

        if billing_status == "billed" and not has_billed:
            continue

        if billing_status == "unbilled" and has_billed:
            continue

        summary["total_leads"] += 1

        if has_billed:
            summary["billed"] += 1
        else:
            summary["unbilled"] += 1

        if has_jobcard:
            summary["jobcard_generated"] += 1
        else:
            summary["jobcard_not_generated"] += 1

        summary["total_amount"] += lead_amount

        rows.append({
            "lead": lead,
            "created_by": lead_created_by,
            "amount": lead_amount,
            "lead_projects": lead_projects,
            "billing_status": lead_billing_status,
            "has_jobcard": has_jobcard,
        })

    months = [
        (1, "January"), (2, "February"), (3, "March"), (4, "April"),
        (5, "May"), (6, "June"), (7, "July"), (8, "August"),
        (9, "September"), (10, "October"), (11, "November"), (12, "December")
    ]

    years = list(range(today.year - 3, today.year + 2))

    return render_template(
        "leads/lead_billing_report.html",
        rows=rows,
        summary=summary,
        users=users,
        months=months,
        years=years,
        selected_month=month,
        selected_year=year,
        selected_user_id=selected_user_id,
        billing_status=billing_status,
    )
    
@leads_bp.route("/sales-dashboard")
@login_required
@require_perm("leads.view")
def sales_dashboard():
    today = datetime.utcnow().date()
    now = datetime.utcnow()

    month_start = datetime(today.year, today.month, 1)

    if today.month == 12:
        next_month = datetime(today.year + 1, 1, 1)
    else:
        next_month = datetime(today.year, today.month + 1, 1)

    allowed_owner_ids = _allowed_lead_owner_ids()

    # -------------------------
    # Base Lead Query
    # -------------------------
    lead_query = Lead.query

    if allowed_owner_ids is not None:
        lead_query = lead_query.filter(Lead.owner_id.in_(allowed_owner_ids))

    total_leads = lead_query.count()

    my_leads = lead_query.filter(Lead.owner_id == current_user.id).count()

    month_leads = (
        lead_query
        .filter(Lead.created_at >= month_start)
        .filter(Lead.created_at < next_month)
        .count()
    )

    corporate_leads = lead_query.filter(Lead.lead_type == "Corporate").count()
    individual_leads = lead_query.filter(Lead.lead_type == "Individual").count()

    # -------------------------
    # Converted Leads / Opportunities
    # -------------------------
    opportunity_query = Opportunity.query

    if allowed_owner_ids is not None:
        opportunity_query = opportunity_query.filter(Opportunity.owner_id.in_(allowed_owner_ids))

    total_opportunities = opportunity_query.count()

    converted_lead_ids = [
        row[0] for row in
        db.session.query(Opportunity.lead_id)
        .filter(Opportunity.lead_id.isnot(None))
        .distinct()
        .all()
    ]

    if allowed_owner_ids is not None:
        converted_count = (
            Lead.query
            .filter(Lead.id.in_(converted_lead_ids))
            .filter(Lead.owner_id.in_(allowed_owner_ids))
            .count()
            if converted_lead_ids else 0
        )
    else:
        converted_count = len(converted_lead_ids)

    open_leads = max(total_leads - converted_count, 0)

    # -------------------------
    # Follow-ups
    # -------------------------
    today_start = datetime.combine(today, datetime.min.time())
    tomorrow_start = datetime.combine(today + timedelta(days=1), datetime.min.time())

    followup_query = (
        LeadActivity.query
        .join(Lead, LeadActivity.lead_id == Lead.id)
        .filter(LeadActivity.next_follow_up_at.isnot(None))
    )

    if allowed_owner_ids is not None:
        followup_query = followup_query.filter(Lead.owner_id.in_(allowed_owner_ids))

    today_followups_count = (
        followup_query
        .filter(LeadActivity.next_follow_up_at >= today_start)
        .filter(LeadActivity.next_follow_up_at < tomorrow_start)
        .count()
    )

    overdue_followups_count = (
        followup_query
        .filter(LeadActivity.next_follow_up_at < today_start)
        .count()
    )

    upcoming_followups_count = (
        followup_query
        .filter(LeadActivity.next_follow_up_at >= today_start)
        .filter(LeadActivity.next_follow_up_at < today_start + timedelta(days=7))
        .count()
    )

    today_followups = (
        followup_query
        .filter(LeadActivity.next_follow_up_at >= today_start)
        .filter(LeadActivity.next_follow_up_at < tomorrow_start)
        .order_by(LeadActivity.next_follow_up_at.asc(), LeadActivity.id.asc())
        .limit(8)
        .all()
    )

    overdue_followups = (
        followup_query
        .filter(LeadActivity.next_follow_up_at < today_start)
        .order_by(LeadActivity.next_follow_up_at.asc(), LeadActivity.id.asc())
        .limit(8)
        .all()
    )

    # -------------------------
    # Quotes Summary
    # -------------------------
    quote_query = Quote.query.join(Opportunity, Quote.opportunity_id == Opportunity.id)

    # Use quote access style:
    # If user has quotes.view_all => all
    # Else current user + reportees based on lead allowed owners
    if not current_user.has_perm("quotes.view_all"):
        quote_allowed_ids = allowed_owner_ids or [current_user.id]
        quote_query = quote_query.filter(or_(
            Quote.created_by_id == current_user.id,
            Opportunity.owner_id.in_(quote_allowed_ids)
        ))

    total_quotes = quote_query.count()

    month_quotes = (
        quote_query
        .filter(Quote.created_at >= month_start)
        .filter(Quote.created_at < next_month)
        .count()
    )

    quote_status_rows = (
        db.session.query(QuoteStatus.name, func.count(Quote.id))
        .join(Quote, Quote.status_id == QuoteStatus.id)
        .join(Opportunity, Quote.opportunity_id == Opportunity.id)
    )

    if not current_user.has_perm("quotes.view_all"):
        quote_allowed_ids = allowed_owner_ids or [current_user.id]
        quote_status_rows = quote_status_rows.filter(or_(
            Quote.created_by_id == current_user.id,
            Opportunity.owner_id.in_(quote_allowed_ids)
        ))

    quote_status_rows = (
        quote_status_rows
        .group_by(QuoteStatus.name)
        .all()
    )

    quote_status_counts = {
        status_name or "No Status": count
        for status_name, count in quote_status_rows
    }

    draft_quotes = quote_status_counts.get("Draft", 0)
    pending_approval_quotes = quote_status_counts.get("Pending Approval", 0)
    approved_quotes = quote_status_counts.get("Approved", 0)
    selected_quotes = quote_status_counts.get("Selected", 0)
    sent_quotes = quote_status_counts.get("Sent", 0)
    rejected_quotes = quote_status_counts.get("Rejected", 0)

    # -------------------------
    # Quote Value Summary
    # -------------------------
    quote_value_rows = quote_query.all()

    total_quote_value = Decimal("0")
    month_quote_value = Decimal("0")
    sent_quote_value = Decimal("0")
    selected_quote_value = Decimal("0")

    for q in quote_value_rows:
        amount = Decimal(str(q.total_amount or q.total or 0))
        total_quote_value += amount

        if q.created_at and month_start <= q.created_at < next_month:
            month_quote_value += amount

        status_name = q.status.name if q.status else ""

        if status_name == "Sent":
            sent_quote_value += amount

        if status_name == "Selected":
            selected_quote_value += amount

    # -------------------------
    # Sent Proposals / Ops / Billing
    # -------------------------
    sent_quote_rows = [
        q for q in quote_value_rows
        if q.status and q.status.name == "Sent"
    ]

    confirmed_proposals = sum(
        1 for q in sent_quote_rows
        if getattr(q, "proposal_confirmed_at", None)
    )

    pending_confirmation = max(len(sent_quote_rows) - confirmed_proposals, 0)

    quote_ids = [q.id for q in quote_value_rows]

    jobcard_quote_ids = set()
    pi_quote_ids = set()
    invoice_quote_ids = set()

    if quote_ids:
        jobcard_quote_ids = set(
            row[0] for row in
            db.session.query(OperationsJobcard.quote_id)
            .filter(OperationsJobcard.quote_id.in_(quote_ids))
            .distinct()
            .all()
        )

        pi_quote_ids = set(
            row[0] for row in
            db.session.query(ProformaInvoice.quote_id)
            .filter(ProformaInvoice.quote_id.in_(quote_ids))
            .filter(ProformaInvoice.status != "Cancelled")
            .distinct()
            .all()
        )

        invoice_quote_ids = set(
            row[0] for row in
            db.session.query(Invoice.quote_id)
            .filter(Invoice.quote_id.in_(quote_ids))
            .filter(Invoice.status != "Cancelled")
            .distinct()
            .all()
        )

    jobcards_created = len(jobcard_quote_ids)
    pi_generated = len(pi_quote_ids)
    invoices_generated = len(invoice_quote_ids)

    pi_pending_requests = quote_query.filter(Quote.pi_request_status == "Pending").count()
    invoice_pending_requests = quote_query.filter(Quote.invoice_request_status == "Pending").count()

    # -------------------------
    # Latest Leads
    # -------------------------
    latest_leads = (
        lead_query
        .order_by(Lead.created_at.desc(), Lead.id.desc())
        .limit(8)
        .all()
    )

    # -------------------------
    # Latest Quotes
    # -------------------------
    latest_quotes = (
        quote_query
        .order_by(Quote.updated_at.desc(), Quote.id.desc())
        .limit(8)
        .all()
    )

    # -------------------------
    # Team Performance
    # -------------------------
    owner_ids_for_team = allowed_owner_ids

    if owner_ids_for_team is None:
        users_for_team = (
            User.query
            .filter_by(is_active=True)
            .order_by(User.name.asc())
            .all()
        )
    else:
        users_for_team = (
            User.query
            .filter(User.id.in_(owner_ids_for_team))
            .filter_by(is_active=True)
            .order_by(User.name.asc())
            .all()
        )

    team_rows = []

    for user in users_for_team:
        user_lead_count = Lead.query.filter(Lead.owner_id == user.id).count()

        user_month_lead_count = (
            Lead.query
            .filter(Lead.owner_id == user.id)
            .filter(Lead.created_at >= month_start)
            .filter(Lead.created_at < next_month)
            .count()
        )

        user_opp_count = Opportunity.query.filter(Opportunity.owner_id == user.id).count()

        user_quote_rows = (
            Quote.query
            .join(Opportunity, Quote.opportunity_id == Opportunity.id)
            .filter(or_(
                Quote.created_by_id == user.id,
                Opportunity.owner_id == user.id
            ))
            .all()
        )

        user_quote_count = len(user_quote_rows)
        user_quote_value = sum(
            Decimal(str(q.total_amount or q.total or 0))
            for q in user_quote_rows
        )

        user_sent_count = sum(
            1 for q in user_quote_rows
            if q.status and q.status.name == "Sent"
        )

        user_selected_count = sum(
            1 for q in user_quote_rows
            if q.status and q.status.name == "Selected"
        )

        team_rows.append({
            "user": user,
            "lead_count": user_lead_count,
            "month_lead_count": user_month_lead_count,
            "opportunity_count": user_opp_count,
            "quote_count": user_quote_count,
            "quote_value": user_quote_value,
            "sent_count": user_sent_count,
            "selected_count": user_selected_count,
        })

    team_rows = sorted(
        team_rows,
        key=lambda x: (x["month_lead_count"], x["quote_value"]),
        reverse=True
    )[:10]

    # -------------------------
    # Quick Actions based on access
    # -------------------------
    quick_actions = []

    if current_user.has_perm("leads.create"):
        quick_actions.append({
            "label": "Create Lead",
            "icon": "bi-plus-circle",
            "url": url_for("leads.create_lead"),
            "class": "primary",
        })

    if current_user.has_perm("leads.view"):
        quick_actions.append({
            "label": "View Leads",
            "icon": "bi-people",
            "url": url_for("leads.list_leads"),
            "class": "info",
        })

    if current_user.has_perm("activities.view"):
        quick_actions.append({
            "label": "Today Follow-ups",
            "icon": "bi-calendar-check",
            "url": url_for("leads.today_followups_dashboard"),
            "class": "warning",
        })

    if current_user.has_perm("quotes.view"):
        quick_actions.append({
            "label": "View Quotes",
            "icon": "bi-file-earmark-text",
            "url": url_for("quotes.list_quotes"),
            "class": "success",
        })

    if current_user.has_perm("quotes.approve"):
        quick_actions.append({
            "label": "Quote Approvals",
            "icon": "bi-check2-square",
            "url": url_for("quotes.approvals_inbox"),
            "class": "danger",
        })

    if current_user.has_perm("quotes.proposals_sent.view"):
        quick_actions.append({
            "label": "Sent Proposals",
            "icon": "bi-send",
            "url": url_for("quotes.sent_proposals"),
            "class": "secondary",
        })

    if current_user.has_perm("leads.view"):
        quick_actions.append({
            "label": "Billing Report",
            "icon": "bi-receipt",
            "url": url_for("leads.lead_billing_report"),
            "class": "dark",
        })

    summary = {
        "total_leads": total_leads,
        "my_leads": my_leads,
        "month_leads": month_leads,
        "corporate_leads": corporate_leads,
        "individual_leads": individual_leads,
        "converted_count": converted_count,
        "open_leads": open_leads,
        "total_opportunities": total_opportunities,

        "today_followups_count": today_followups_count,
        "overdue_followups_count": overdue_followups_count,
        "upcoming_followups_count": upcoming_followups_count,

        "total_quotes": total_quotes,
        "month_quotes": month_quotes,
        "draft_quotes": draft_quotes,
        "pending_approval_quotes": pending_approval_quotes,
        "approved_quotes": approved_quotes,
        "selected_quotes": selected_quotes,
        "sent_quotes": sent_quotes,
        "rejected_quotes": rejected_quotes,

        "total_quote_value": total_quote_value,
        "month_quote_value": month_quote_value,
        "sent_quote_value": sent_quote_value,
        "selected_quote_value": selected_quote_value,

        "confirmed_proposals": confirmed_proposals,
        "pending_confirmation": pending_confirmation,
        "jobcards_created": jobcards_created,
        "pi_generated": pi_generated,
        "invoices_generated": invoices_generated,
        "pi_pending_requests": pi_pending_requests,
        "invoice_pending_requests": invoice_pending_requests,
    }

    return render_template(
        "leads/sales_dashboard.html",
        summary=summary,
        quick_actions=quick_actions,
        latest_leads=latest_leads,
        latest_quotes=latest_quotes,
        today_followups=today_followups,
        overdue_followups=overdue_followups,
        team_rows=team_rows,
        today=today,
    )


# =========================================================
# External LMSCom website leads
# =========================================================
@leads_bp.route("/external")
@login_required
@require_perm("external_leads.view")
def external_leads_inbox():
    from .external_leads_service import (
        INDIA_REGIONS,
        CITY_TO_STATE,
        get_region_for_location,
        sync_external_leads,
    )

    sync_error = None
    if current_user.has_perm("external_leads.sync"):
        try:
            sync_external_leads(limit=200)
        except Exception as exc:
            sync_error = str(exc)

    q = (request.args.get("q") or "").strip()
    location = (request.args.get("location") or "").strip()
    region = (request.args.get("region") or "").strip()
    assignment = (request.args.get("assignment") or "").strip()
    mode = (request.args.get("mode") or "").strip()
    owner_id = (request.args.get("owner_id") or "").strip()
    date_from = (request.args.get("date_from") or "").strip()
    date_to = (request.args.get("date_to") or "").strip()
    page = request.args.get("page", 1, type=int)

    base_query = ExternalLeadSync.query

    allowed_owner_ids = _allowed_lead_owner_ids()
    if allowed_owner_ids is not None:
        base_query = base_query.filter(or_(
            ExternalLeadSync.assigned_user_id.in_(allowed_owner_ids),
            ExternalLeadSync.assigned_user_id.is_(None),
        ))

    total_imported = base_query.count()
    total_assigned = base_query.filter(
        ExternalLeadSync.assigned_user_id.isnot(None)
    ).count()
    total_unassigned = base_query.filter(
        ExternalLeadSync.assigned_user_id.is_(None)
    ).count()

    query = base_query

    if q:
        like = f"%{q}%"
        query = query.filter(or_(
            ExternalLeadSync.company_name.ilike(like),
            ExternalLeadSync.contact_person.ilike(like),
            ExternalLeadSync.email.ilike(like),
            ExternalLeadSync.phone.ilike(like),
            ExternalLeadSync.lead_description.ilike(like),
            cast(ExternalLeadSync.external_lead_id, String).ilike(like),
        ))

    if location:
        query = query.filter(ExternalLeadSync.normalized_location == location)

    if region:
        region_locations = set(INDIA_REGIONS.get(region, set()))
        region_locations.update(
            city for city, state in CITY_TO_STATE.items()
            if state in INDIA_REGIONS.get(region, set())
        )
        if region_locations:
            query = query.filter(
                ExternalLeadSync.normalized_location.in_(sorted(region_locations))
            )

    if assignment == "assigned":
        query = query.filter(ExternalLeadSync.assigned_user_id.isnot(None))
    elif assignment in {"unassigned", "waiting_rule"}:
        query = query.filter(ExternalLeadSync.assigned_user_id.is_(None))

    if mode in {"AUTO", "MANUAL", "UNASSIGNED"}:
        query = query.filter(ExternalLeadSync.assignment_mode == mode)

    if owner_id.isdigit():
        oid = int(owner_id)
        if allowed_owner_ids is None or oid in allowed_owner_ids:
            query = query.filter(ExternalLeadSync.assigned_user_id == oid)

    if date_from:
        try:
            start_date = datetime.strptime(date_from, "%Y-%m-%d")
            query = query.filter(
                ExternalLeadSync.external_created_at >= start_date
            )
        except ValueError:
            pass

    if date_to:
        try:
            end_date = datetime.strptime(date_to, "%Y-%m-%d") + timedelta(days=1)
            query = query.filter(
                ExternalLeadSync.external_created_at < end_date
            )
        except ValueError:
            pass

    pagination = query.order_by(
        ExternalLeadSync.external_created_at.desc(),
        ExternalLeadSync.external_lead_id.desc(),
    ).paginate(page=page, per_page=20, error_out=False)

    locations = [
        row[0] for row in db.session.query(ExternalLeadSync.normalized_location)
        .filter(ExternalLeadSync.normalized_location.isnot(None))
        .filter(ExternalLeadSync.normalized_location != "")
        .distinct()
        .order_by(ExternalLeadSync.normalized_location.asc())
        .all()
    ]

    region_options = [
        ("north", "North"),
        ("south", "South"),
        ("east", "East"),
        ("west", "West"),
        ("central", "Central"),
        ("north_east", "North East"),
    ]

    return render_template(
        "leads/external_inbox.html",
        pagination=pagination,
        q=q,
        location=location,
        region=region,
        assignment=assignment,
        mode=mode,
        owner_id=owner_id,
        date_from=date_from,
        date_to=date_to,
        owner_options=_owner_options_for_current_user(),
        locations=locations,
        region_options=region_options,
        total_imported=total_imported,
        total_assigned=total_assigned,
        total_unassigned=total_unassigned,
        sync_error=sync_error,
        refresh_seconds=current_app.config.get("LMSCOM_BROWSER_SYNC_SECONDS", 30),
        get_region_for_location=get_region_for_location,
    )


@leads_bp.route("/external/sync", methods=["POST"])
@login_required
@require_perm("external_leads.sync")
def sync_external_leads_now():
    from .external_leads_service import sync_external_leads

    try:
        result = sync_external_leads()
        return jsonify({"ok": True, **result})
    except Exception as exc:
        return jsonify({"ok": False, "error": str(exc)}), 500


@leads_bp.route("/external/re-run-assignment", methods=["POST"])
@login_required
@require_perm("external_leads.assign")
def rerun_external_lead_assignment():
    from .external_leads_service import auto_assign_unassigned_leads

    try:
        result = auto_assign_unassigned_leads(
            assigned_by_id=current_user.id,
        )
        return jsonify({"ok": True, **result})
    except Exception as exc:
        db.session.rollback()
        return jsonify({"ok": False, "error": str(exc)}), 500


@leads_bp.route("/external/<int:sync_id>/assign", methods=["POST"])
@login_required
@require_perm("external_leads.assign")
def assign_external_lead(sync_id):
    sync_row = ExternalLeadSync.query.get_or_404(sync_id)
    user_id = (request.form.get("user_id") or "").strip()

    if not user_id.isdigit():
        flash("Please select a valid user.", "danger")
        return redirect(url_for("leads.external_leads_inbox"))

    target_user = User.query.filter_by(id=int(user_id), is_active=True).first_or_404()
    allowed = _allowed_lead_owner_ids()
    if allowed is not None and target_user.id not in allowed:
        abort(403)

    old_owner_id = sync_row.assigned_user_id
    sync_row.assigned_user_id = target_user.id
    sync_row.assignment_mode = "MANUAL"

    if sync_row.local_lead:
        sync_row.local_lead.owner_id = target_user.id
        db.session.add(LeadAssignmentHistory(
            lead_id=sync_row.local_lead_id,
            assigned_by_id=current_user.id,
            old_owner_id=old_owner_id,
            new_owner_id=target_user.id,
        ))

    db.session.commit()
    flash(f"Lead assigned to {target_user.name}.", "success")
    return redirect(request.referrer or url_for("leads.external_leads_inbox"))


@leads_bp.route("/external/location-rules", methods=["GET", "POST"])
@login_required
@require_perm("external_leads.manage_rules")
def external_location_rules():
    from .external_leads_service import (
        INDIA_STATE_OPTIONS,
        REGION_OPTIONS,
        normalize_location,
    )

    if request.method == "POST":
        rule_type = (request.form.get("rule_type") or "").strip()
        region_name = (request.form.get("region_name") or "").strip()
        state_name = (request.form.get("state_name") or "").strip()
        user_id = (request.form.get("user_id") or "").strip()
        priority = request.form.get("priority", 1, type=int) or 1

        valid_regions = {value for value, _label in REGION_OPTIONS}
        valid_states = {value for value, _label in INDIA_STATE_OPTIONS}
        state_labels = dict(INDIA_STATE_OPTIONS)
        region_labels = dict(REGION_OPTIONS)

        if not user_id.isdigit():
            flash("Please select a valid user.", "danger")
            return redirect(url_for("leads.external_location_rules"))

        if rule_type == "region":
            if region_name not in valid_regions:
                flash("Please select a valid region.", "danger")
                return redirect(url_for("leads.external_location_rules"))

            location_name = f"{region_labels[region_name]} Region"
            normalized = f"region:{region_name}"

        elif rule_type == "state":
            normalized = normalize_location(state_name)
            if normalized not in valid_states:
                flash("Please select a valid state or union territory.", "danger")
                return redirect(url_for("leads.external_location_rules"))

            location_name = state_labels[normalized]

        elif rule_type == "unknown":
            location_name = "Unknown Location"
            normalized = "special:unknown"

        elif rule_type == "fallback":
            location_name = "Default Fallback"
            normalized = "*"

        else:
            flash("Please select a valid rule type.", "danger")
            return redirect(url_for("leads.external_location_rules"))

        user = User.query.filter_by(id=int(user_id), is_active=True).first()
        if not user:
            flash("Selected user was not found.", "danger")
            return redirect(url_for("leads.external_location_rules"))

        exists = LeadLocationAssignmentRule.query.filter_by(
            normalized_location=normalized,
            user_id=user.id,
        ).first()
        if exists:
            flash(
                "This user is already mapped to the selected assignment rule.",
                "warning",
            )
            return redirect(url_for("leads.external_location_rules"))

        db.session.add(
            LeadLocationAssignmentRule(
                location_name=location_name,
                normalized_location=normalized,
                user_id=user.id,
                priority=max(1, priority),
                is_active=True,
                created_by_id=current_user.id,
            )
        )
        db.session.commit()

        from .external_leads_service import auto_assign_unassigned_leads
        assignment_result = auto_assign_unassigned_leads(
            normalized_location=normalized,
            assigned_by_id=current_user.id,
        )

        if assignment_result["assigned"]:
            flash(
                f"Location assignment rule added. "
                f"{assignment_result['assigned']} existing unassigned lead(s) "
                f"were assigned automatically.",
                "success",
            )
        else:
            flash(
                "Location assignment rule added. No existing unassigned leads "
                "matched this rule.",
                "success",
            )

        if assignment_result["failed"]:
            flash(
                f"{assignment_result['failed']} lead(s) could not be processed. "
                "Use Re-run Auto Assignment after checking the application log.",
                "warning",
            )

        return redirect(url_for("leads.external_location_rules"))

    rules = LeadLocationAssignmentRule.query.order_by(
        LeadLocationAssignmentRule.normalized_location.asc(),
        LeadLocationAssignmentRule.priority.asc(),
        LeadLocationAssignmentRule.id.asc(),
    ).all()

    return render_template(
        "leads/location_rules.html",
        rules=rules,
        users=User.query.filter_by(is_active=True).order_by(User.name.asc()).all(),
        region_options=REGION_OPTIONS,
        state_options=INDIA_STATE_OPTIONS,
    )


@leads_bp.route("/external/location-rules/<int:rule_id>/toggle", methods=["POST"])
@login_required
@require_perm("external_leads.manage_rules")
def toggle_external_location_rule(rule_id):
    rule = LeadLocationAssignmentRule.query.get_or_404(rule_id)
    rule.is_active = not rule.is_active
    db.session.commit()
    flash("Rule status updated.", "success")
    return redirect(url_for("leads.external_location_rules"))


@leads_bp.route("/external/location-rules/<int:rule_id>/delete", methods=["POST"])
@login_required
@require_perm("external_leads.manage_rules")
def delete_external_location_rule(rule_id):
    rule = LeadLocationAssignmentRule.query.get_or_404(rule_id)
    if rule.assignment_count:
        rule.is_active = False
        db.session.commit()
        flash("Rule has assignment history, so it was disabled instead of deleted.", "warning")
    else:
        db.session.delete(rule)
        db.session.commit()
        flash("Rule deleted.", "success")
    return redirect(url_for("leads.external_location_rules"))
