"""
Roteador Administrativo: Gestão Operacional da Barbearia (Multi-Tenancy SaaS)
Suporte à alternância entre barbearias e controle de permissões por plano (Básico, Intermediário e Profissional).
"""
from fastapi import APIRouter, Request, HTTPException
from fastapi.templating import Jinja2Templates
import os
from datetime import datetime, timedelta
from app.database import get_db
from app.plans import get_plan_info, SAAS_PLANS

TEMPLATES_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "templates")
templates = Jinja2Templates(directory=TEMPLATES_DIR)

router = APIRouter(prefix="/admin", tags=["Administração"])

def get_active_shop(request: Request, cursor):
    """
    Identifica a barbearia ativa com base no cookie barber_active_shop_id, parâmetro ?shop_id= ou primeiro registro ativo.
    Retorna (shop_dict, all_shops_list, plan_info_dict).
    """
    cursor.execute("SELECT id, name, slug, plan_tier FROM barbershops WHERE is_active = 1 ORDER BY id ASC")
    all_shops = [dict(r) for r in cursor.fetchall()]

    if not all_shops:
        raise HTTPException(status_code=404, detail="Nenhuma barbearia ativa cadastrada no sistema.")

    shop_id_param = request.query_params.get("shop_id")
    cookie_shop_id = request.cookies.get("barber_active_shop_id")
    target_id = None
    if shop_id_param:
        try:
            target_id = int(shop_id_param)
        except ValueError:
            pass
    elif cookie_shop_id:
        try:
            target_id = int(cookie_shop_id)
        except ValueError:
            pass

    if target_id:
        cursor.execute("SELECT * FROM barbershops WHERE id = ?", (target_id,))
        row = cursor.fetchone()
        shop = dict(row) if row else dict(all_shops[0])
    else:
        cursor.execute("SELECT * FROM barbershops WHERE id = ?", (all_shops[0]["id"],))
        shop = dict(cursor.fetchone())

    plan_info = get_plan_info(shop.get("plan_tier", "basico"))
    return shop, all_shops, plan_info


@router.get("")
@router.get("/")
def admin_dashboard(request: Request):
    with get_db() as conn:
        cursor = conn.cursor()
        shop, all_shops, plan_info = get_active_shop(request, cursor)
        today = datetime.now().strftime("%Y-%m-%d")

        # 1. Indicadores do Dia (Vendas e Comissões)
        cursor.execute("""
        SELECT 
            COALESCE(SUM(final_amount), 0.0) as total_sales,
            COALESCE(SUM(barber_commission_amount), 0.0) as total_comm,
            COALESCE(SUM(house_net_amount), 0.0) as house_net,
            COUNT(*) as orders_count
        FROM orders
        WHERE barbershop_id = ? AND date(created_at) = ?
        """, (shop["id"], today))
        sales_row = cursor.fetchone()

        # 2. Agendamentos de Hoje
        cursor.execute("""
        SELECT 
            COUNT(*) as total_appts,
            SUM(CASE WHEN status = 'concluido' THEN 1 ELSE 0 END) as completed_appts,
            SUM(CASE WHEN status NOT IN ('concluido', 'cancelado', 'falta') THEN 1 ELSE 0 END) as pending_appts
        FROM appointments
        WHERE barbershop_id = ? AND appointment_date = ?
        """, (shop["id"], today))
        appt_stats = cursor.fetchone()

        # 3. Clube de Assinatura
        cursor.execute("""
        SELECT 
            COUNT(*) as active_members,
            COALESCE(SUM(p.monthly_price), 0.0) as monthly_rev
        FROM client_subscriptions cs
        JOIN subscription_plans p ON cs.plan_id = p.id
        WHERE cs.barbershop_id = ? AND cs.status = 'ativo'
        """, (shop["id"],))
        club_stats = cursor.fetchone()

        # 4. Lista dos Agendamentos de Hoje
        cursor.execute("""
        SELECT a.*, s.name as service_name, b.name as barber_name, b.avatar_color as barber_color,
               c.name as client_name, c.phone as client_phone
        FROM appointments a
        JOIN services s ON a.service_id = s.id
        JOIN barbers b ON a.barber_id = b.id
        JOIN clients c ON a.client_id = c.id
        WHERE a.barbershop_id = ? AND a.appointment_date = ?
        ORDER BY a.start_time ASC
        """, (shop["id"], today))
        today_appts = []
        for r in cursor.fetchall():
            d = dict(r)
            d["zap_reminder_text"] = f"Fala {d['client_name']}! Lembrete do seu corte hoje às {d['start_time']}h na {shop['name']} com {d['barber_name']}. Responda 1 para confirmar."
            today_appts.append(d)

        # 5. Barbeiros
        cursor.execute("SELECT * FROM barbers WHERE barbershop_id = ? AND is_active = 1", (shop["id"],))
        barbers = [dict(r) for r in cursor.fetchall()]

        base_url = str(request.base_url).rstrip("/")
        now_dt = datetime.now()

        metrics = {
            "today_sales_total": sales_row["total_sales"],
            "today_commissions_total": sales_row["total_comm"],
            "today_house_net": sales_row["house_net"],
            "today_orders_count": sales_row["orders_count"],
            "today_appts_count": appt_stats["total_appts"] or 0,
            "today_appts_completed": appt_stats["completed_appts"] or 0,
            "today_appts_pending": appt_stats["pending_appts"] or 0,
            "club_monthly_revenue": club_stats["monthly_rev"] or 0.0,
            "club_active_members": club_stats["active_members"] or 0,
            "today_date_formatted": now_dt.strftime("%d/%m/%Y")
        }

        return templates.TemplateResponse(
            request=request,
            name="admin/dashboard.html",
            context={
                "shop": shop,
                "all_shops": all_shops,
                "plan_info": plan_info,
                "active_page": "dashboard",
                "metrics": metrics,
                "today_appointments": today_appts,
                "barbers": barbers,
                "base_url": base_url
            }
        )

@router.get("/agenda")
def admin_agenda(request: Request, date: str = None, barber_id: int = 0):
    with get_db() as conn:
        cursor = conn.cursor()
        shop, all_shops, plan_info = get_active_shop(request, cursor)

        today_str = datetime.now().strftime("%Y-%m-%d")
        if not date:
            date = today_str

        cur_dt = datetime.strptime(date, "%Y-%m-%d")
        prev_date = (cur_dt - timedelta(days=1)).strftime("%Y-%m-%d")
        next_date = (cur_dt + timedelta(days=1)).strftime("%Y-%m-%d")

        cursor.execute("SELECT * FROM barbers WHERE barbershop_id = ? AND is_active = 1 ORDER BY name ASC", (shop["id"],))
        barbers = [dict(r) for r in cursor.fetchall()]

        cursor.execute("SELECT * FROM services WHERE barbershop_id = ? AND is_active = 1 ORDER BY name ASC", (shop["id"],))
        services = [dict(r) for r in cursor.fetchall()]

        query = """
        SELECT a.*, s.name as service_name, s.duration_minutes, b.name as barber_name, b.avatar_color,
               c.name as client_name, c.phone as client_phone
        FROM appointments a
        JOIN services s ON a.service_id = s.id
        JOIN barbers b ON a.barber_id = b.id
        JOIN clients c ON a.client_id = c.id
        WHERE a.barbershop_id = ? AND a.appointment_date = ?
        """
        params = [shop["id"], date]

        if barber_id > 0:
            query += " AND a.barber_id = ?"
            params.append(barber_id)

        query += " ORDER BY a.start_time ASC"
        cursor.execute(query, params)

        appointments = []
        for r in cursor.fetchall():
            d = dict(r)
            d["zap_reminder_text"] = f"Fala {d['client_name']}! Lembrete do seu horário às {d['start_time']}h com {d['barber_name']} ({d['service_name']}) na {shop['name']}. Responda 1 para confirmar."
            appointments.append(d)

        # Estatísticas do dia
        stats = {
            "total": len(appointments),
            "confirmados": sum(1 for a in appointments if a["status"] == "confirmado"),
            "em_atendimento": sum(1 for a in appointments if a["status"] == "em_atendimento"),
            "concluidos": sum(1 for a in appointments if a["status"] == "concluido"),
            "agendados": sum(1 for a in appointments if a["status"] == "agendado"),
            "receita_prevista": sum(a["total_amount"] for a in appointments if a["status"] != "cancelado")
        }

        # Slots operacionais da barbearia (das 08:00 às 20:30 de 30 em 30 min)
        time_slots = [
            f"{h:02d}:{m:02d}"
            for h in range(8, 21)
            for m in (0, 30)
        ]

        def get_slot_key(time_str):
            try:
                parts = time_str.split(":")
                h = int(parts[0])
                m = int(parts[1]) if len(parts) > 1 else 0
                slot_m = "30" if m >= 30 else "00"
                return f"{h:02d}:{slot_m}"
            except Exception:
                return "09:00"

        # Organizar agendamentos na grade por slot e barbeiro
        grid_rows = []
        for slot in time_slots:
            slot_barbers = {}
            for b in barbers:
                b_appts = [a for a in appointments if a["barber_id"] == b["id"] and get_slot_key(a["start_time"]) == slot]
                slot_barbers[b["id"]] = b_appts
            grid_rows.append({
                "time": slot,
                "barbers": slot_barbers
            })

        base_url = str(request.base_url).rstrip("/")

        return templates.TemplateResponse(
            request=request,
            name="admin/agenda.html",
            context={
                "shop": shop,
                "all_shops": all_shops,
                "plan_info": plan_info,
                "active_page": "agenda",
                "current_date": date,
                "today_date": today_str,
                "prev_date": prev_date,
                "next_date": next_date,
                "selected_barber_id": barber_id,
                "barbers": barbers,
                "services": services,
                "appointments": appointments,
                "agenda_stats": stats,
                "time_slots": time_slots,
                "grid_rows": grid_rows,
                "base_url": base_url
            }
        )

@router.get("/caixa")
def admin_caixa(request: Request, appt_id: int = 0):
    with get_db() as conn:
        cursor = conn.cursor()
        shop, all_shops, plan_info = get_active_shop(request, cursor)
        today = datetime.now().strftime("%Y-%m-%d")

        cursor.execute("""
        SELECT o.*, b.name as barber_name,
               strftime('%H:%M', o.created_at) as created_time
        FROM orders o
        JOIN barbers b ON o.barber_id = b.id
        WHERE o.barbershop_id = ? AND date(o.created_at) = ?
        ORDER BY o.id DESC
        """, (shop["id"], today))
        orders = [dict(r) for r in cursor.fetchall()]

        cursor.execute("""
        SELECT 
            COALESCE(SUM(final_amount), 0.0) as total,
            COALESCE(SUM(house_net_amount), 0.0) as house_net,
            COALESCE(SUM(barber_commission_amount), 0.0) as commissions,
            COALESCE(SUM(total_products), 0.0) as total_products,
            COALESCE(SUM(total_services), 0.0) as total_services,
            COALESCE(SUM(CASE WHEN payment_method = 'pix' THEN final_amount ELSE 0 END), 0.0) as pix,
            COALESCE(SUM(CASE WHEN payment_method = 'cartao_credito' THEN final_amount ELSE 0 END), 0.0) as credit_card,
            COALESCE(SUM(CASE WHEN payment_method = 'cartao_debito' THEN final_amount ELSE 0 END), 0.0) as debit_card,
            COALESCE(SUM(CASE WHEN payment_method IN ('cartao_debito', 'cartao_credito') THEN final_amount ELSE 0 END), 0.0) as card,
            COALESCE(SUM(CASE WHEN payment_method = 'dinheiro' THEN final_amount ELSE 0 END), 0.0) as cash,
            COALESCE(SUM(CASE WHEN payment_method = 'fiado' THEN final_amount ELSE 0 END), 0.0) as fiado
        FROM orders
        WHERE barbershop_id = ? AND date(created_at) = ?
        """, (shop["id"], today))
        caixa_summary = dict(cursor.fetchone())

        orders_count = len(orders)
        tot = caixa_summary["total"]
        caixa_summary["orders_count"] = orders_count
        caixa_summary["ticket_medio"] = (tot / orders_count) if orders_count > 0 else 0.0
        caixa_summary["pix_pct"] = round((caixa_summary["pix"] / tot * 100), 1) if tot > 0 else 0.0
        caixa_summary["card_pct"] = round((caixa_summary["card"] / tot * 100), 1) if tot > 0 else 0.0
        caixa_summary["cash_pct"] = round((caixa_summary["cash"] / tot * 100), 1) if tot > 0 else 0.0
        caixa_summary["fiado_pct"] = round((caixa_summary["fiado"] / tot * 100), 1) if tot > 0 else 0.0

        # Vales do dia
        cursor.execute("""
        SELECT a.*, b.name as barber_name
        FROM barber_advances a
        JOIN barbers b ON a.barber_id = b.id
        WHERE a.barbershop_id = ? AND a.date = ?
        ORDER BY a.id DESC
        """, (shop["id"], today))
        today_advances = [dict(r) for r in cursor.fetchall()]
        caixa_summary["total_advances"] = sum(a["amount"] for a in today_advances)
        caixa_summary["saldo_liquido_gaveta"] = max(0.0, caixa_summary["cash"] - caixa_summary["total_advances"])

        cursor.execute("""
        SELECT a.*, s.name as service_name, b.name as barber_name, c.name as client_name
        FROM appointments a
        JOIN services s ON a.service_id = s.id
        JOIN barbers b ON a.barber_id = b.id
        JOIN clients c ON a.client_id = c.id
        WHERE a.barbershop_id = ? AND a.appointment_date = ? AND a.status NOT IN ('cancelado', 'falta')
        ORDER BY a.start_time ASC
        """, (shop["id"], today))
        pending_appts = [dict(r) for r in cursor.fetchall()]

        cursor.execute("SELECT * FROM barbers WHERE barbershop_id = ? AND is_active = 1", (shop["id"],))
        barbers = [dict(r) for r in cursor.fetchall()]

        cursor.execute("SELECT * FROM services WHERE barbershop_id = ? AND is_active = 1", (shop["id"],))
        services = [dict(r) for r in cursor.fetchall()]

        cursor.execute("SELECT * FROM products WHERE barbershop_id = ? AND is_active = 1", (shop["id"],))
        products = [dict(r) for r in cursor.fetchall()]

        initial_client = ""
        selected_barber_id = 0
        selected_service_id = 0
        if appt_id > 0:
            for p in pending_appts:
                if p["id"] == appt_id:
                    initial_client = p["client_name"]
                    selected_barber_id = p["barber_id"]
                    selected_service_id = p["service_id"]
                    break

        base_url = str(request.base_url).rstrip("/")

        return templates.TemplateResponse(
            request=request,
            name="admin/caixa.html",
            context={
                "shop": shop,
                "all_shops": all_shops,
                "plan_info": plan_info,
                "active_page": "caixa",
                "today_formatted": datetime.now().strftime("%d/%m/%Y"),
                "orders": orders,
                "caixa_summary": caixa_summary,
                "pending_appts": pending_appts,
                "barbers": barbers,
                "services": services,
                "products": products,
                "selected_appt_id": appt_id,
                "initial_client_name": initial_client,
                "selected_barber_id": selected_barber_id,
                "selected_service_id": selected_service_id,
                "today_advances": today_advances,
                "base_url": base_url
            }
        )

@router.get("/comissoes")
def admin_comissoes(request: Request):
    with get_db() as conn:
        cursor = conn.cursor()
        shop, all_shops, plan_info = get_active_shop(request, cursor)

        # Se o plano for Básico, recurso de comissões fica travado
        is_locked = not plan_info["has_commissions"]

        cursor.execute("SELECT * FROM barbers WHERE barbershop_id = ? AND is_active = 1 ORDER BY name ASC", (shop["id"],))
        barbers = [dict(r) for r in cursor.fetchall()]

        barber_commissions = []
        if not is_locked:
            for b in barbers:
                b_id = b["id"]
                cursor.execute("""
                SELECT 
                    COALESCE(SUM(total_services), 0.0) as total_prod,
                    COALESCE(SUM(barber_commission_amount), 0.0) as gross_comm
                FROM orders
                WHERE barbershop_id = ? AND barber_id = ?
                """, (shop["id"], b_id))
                prod_row = cursor.fetchone()

                cursor.execute("""
                SELECT * FROM barber_advances
                WHERE barbershop_id = ? AND barber_id = ?
                ORDER BY date DESC LIMIT 5
                """, (shop["id"], b_id))
                advances = [dict(r) for r in cursor.fetchall()]

                cursor.execute("""
                SELECT COALESCE(SUM(amount), 0.0) FROM barber_advances
                WHERE barbershop_id = ? AND barber_id = ? AND is_deducted = 0
                """, (shop["id"], b_id))
                total_adv = cursor.fetchone()[0] or 0.0

                gross_comm = prod_row["gross_comm"]
                net_to_pay = max(0.0, gross_comm - total_adv)

                barber_commissions.append({
                    "id": b_id,
                    "name": b["name"],
                    "avatar_color": b["avatar_color"],
                    "commission_rate": b["commission_rate"],
                    "total_produced": prod_row["total_prod"],
                    "gross_commission": gross_comm,
                    "total_advances": total_adv,
                    "net_to_pay": net_to_pay,
                    "advances": advances
                })

        base_url = str(request.base_url).rstrip("/")

        return templates.TemplateResponse(
            request=request,
            name="admin/comissoes.html",
            context={
                "shop": shop,
                "all_shops": all_shops,
                "plan_info": plan_info,
                "active_page": "comissoes",
                "is_locked": is_locked,
                "barber_commissions": barber_commissions,
                "base_url": base_url
            }
        )

@router.get("/clube")
def admin_clube(request: Request):
    with get_db() as conn:
        cursor = conn.cursor()
        shop, all_shops, plan_info = get_active_shop(request, cursor)

        # Se o plano não contemplar clube
        is_locked = not plan_info["has_club"]

        plans = []
        subscriptions = []
        clients = []
        total_rev = 0.0
        active_count = 0

        if not is_locked:
            cursor.execute("SELECT * FROM subscription_plans WHERE barbershop_id = ? AND is_active = 1", (shop["id"],))
            plans = [dict(r) for r in cursor.fetchall()]

            cursor.execute("""
            SELECT cs.*, c.name as client_name, c.phone as client_phone,
                   p.name as plan_name, p.cuts_included, p.monthly_price
            FROM client_subscriptions cs
            JOIN clients c ON cs.client_id = c.id
            JOIN subscription_plans p ON cs.plan_id = p.id
            WHERE cs.barbershop_id = ?
            ORDER BY cs.id DESC
            """, (shop["id"],))
            subscriptions = [dict(r) for r in cursor.fetchall()]

            cursor.execute("SELECT * FROM clients WHERE barbershop_id = ? ORDER BY name ASC", (shop["id"],))
            clients = [dict(r) for r in cursor.fetchall()]

            total_rev = sum(s["monthly_price"] for s in subscriptions if s["status"] == "ativo")
            active_count = sum(1 for s in subscriptions if s["status"] == "ativo")

        base_url = str(request.base_url).rstrip("/")

        return templates.TemplateResponse(
            request=request,
            name="admin/clube.html",
            context={
                "shop": shop,
                "all_shops": all_shops,
                "plan_info": plan_info,
                "active_page": "clube",
                "is_locked": is_locked,
                "plans": plans,
                "subscriptions": subscriptions,
                "clients": clients,
                "club_metrics": {
                    "total_revenue": total_rev,
                    "active_count": active_count
                },
                "base_url": base_url
            }
        )

@router.get("/clientes")
def admin_clientes(request: Request):
    with get_db() as conn:
        cursor = conn.cursor()
        shop, all_shops, plan_info = get_active_shop(request, cursor)

        cursor.execute("SELECT * FROM clients WHERE barbershop_id = ? ORDER BY last_visit_at DESC", (shop["id"],))
        clients = [dict(r) for r in cursor.fetchall()]

        # Reativação de clientes sumidos (Disponível no Plano Profissional)
        has_recovery = plan_info["has_recovery"]
        lost_clients = []
        today_dt = datetime.now()
        for c in clients:
            if c["last_visit_at"]:
                try:
                    visit_dt = datetime.strptime(c["last_visit_at"], "%Y-%m-%d")
                    days_diff = (today_dt - visit_dt).days
                    if days_diff >= 25:
                        lost_clients.append(c)
                except Exception:
                    pass

        base_url = str(request.base_url).rstrip("/")

        return templates.TemplateResponse(
            request=request,
            name="admin/clientes.html",
            context={
                "shop": shop,
                "all_shops": all_shops,
                "plan_info": plan_info,
                "active_page": "clientes",
                "has_recovery": has_recovery,
                "clients": clients,
                "lost_clients": lost_clients,
                "base_url": base_url
            }
        )

@router.get("/config")
def admin_config(request: Request):
    with get_db() as conn:
        cursor = conn.cursor()
        shop, all_shops, plan_info = get_active_shop(request, cursor)

        cursor.execute("SELECT * FROM services WHERE barbershop_id = ? ORDER BY price ASC", (shop["id"],))
        services = [dict(r) for r in cursor.fetchall()]

        cursor.execute("SELECT * FROM barbers WHERE barbershop_id = ? ORDER BY name ASC", (shop["id"],))
        barbers = [dict(r) for r in cursor.fetchall()]

        base_url = str(request.base_url).rstrip("/")

        return templates.TemplateResponse(
            request=request,
            name="admin/config.html",
            context={
                "shop": shop,
                "all_shops": all_shops,
                "plan_info": plan_info,
                "active_page": "config",
                "services": services,
                "barbers": barbers,
                "base_url": base_url
            }
        )
