from fastapi import APIRouter, Request, Depends, Form
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from starlette.responses import RedirectResponse
from starlette.status import HTTP_302_FOUND
from fastapi import HTTPException
from urllib.parse import urlencode
from app.auth import require_role, hash_password
from app.database import db

router = APIRouter()
templates = Jinja2Templates(directory="web")

@router.get("/panel-admin", response_class=HTMLResponse)
async def panel_admin(
    request: Request,
    user=Depends(require_role("admin")),
    crear_exito: str = None,
    password_exito: str = None,
    eliminar_exito: str = None
):
    usuarios = await db.users.find().to_list(length=None)
    return templates.TemplateResponse("panel-admin.html", {
        "request": request,
        "user": user,
        "usuarios": usuarios,
        "crear_exito": crear_exito,
        "password_exito": password_exito,
        "eliminar_exito": eliminar_exito,
    })


@router.post("/admin/usuarios/crear")
async def crear_usuario(
    request: Request,
    username: str = Form(...),
    password: str = Form(...),
    role: str = Form(...),
    user=Depends(require_role("admin"))
):
    if role not in ["admin", "medico"]:
        usuarios = await db.users.find().to_list(length=None)
        return templates.TemplateResponse("panel-admin.html", {
            "request": request,
            "user": user,
            "usuarios": usuarios,
            "crear_error": "Rol no válido. Solo se permite 'admin' o 'medico'."
        })

    existing = await db.users.find_one({"username": username})
    if existing:
        usuarios = await db.users.find().to_list(length=None)
        return templates.TemplateResponse("panel-admin.html", {
            "request": request,
            "user": user,
            "usuarios": usuarios,
            "crear_error": "El usuario ya existe."
        })

    await db.users.insert_one({
        "username": username,
        "password": hash_password(password),
        "role": role
    })

    params = urlencode({"crear_exito": f"Usuario '{username}' creado exitosamente."})
    return RedirectResponse(f"/panel-admin?{params}", status_code=HTTP_302_FOUND)



@router.post("/admin/usuarios/cambiar-password")
async def cambiar_password(
    request: Request,
    username: str = Form(...),
    new_password: str = Form(...),
    user=Depends(require_role("admin"))
):
    usuario = await db.users.find_one({"username": username})
    if not usuario:
        usuarios = await db.users.find().to_list(length=None)
        return templates.TemplateResponse("panel-admin.html", {
            "request": request,
            "user": user,
            "usuarios": usuarios,
            "password_error": "Usuario no encontrado."
        })

    await db.users.update_one(
        {"username": username},
        {"$set": {"password": hash_password(new_password)}}
    )

    params = urlencode({"password_exito": f"Contraseña de '{username}' actualizada."})
    return RedirectResponse(f"/panel-admin?{params}", status_code=HTTP_302_FOUND)


@router.post("/admin/usuarios/eliminar")
async def eliminar_usuario(
    request: Request,
    username: str = Form(...),
    user=Depends(require_role("admin"))
):
    usuario = await db.users.find_one({"username": username})
    if not usuario:
        usuarios = await db.users.find().to_list(length=None)
        return templates.TemplateResponse("panel-admin.html", {
            "request": request,
            "user": user,
            "usuarios": usuarios,
            "eliminar_error": "Usuario no encontrado."
        })

    if usuario["username"] == "admin":
        usuarios = await db.users.find().to_list(length=None)
        return templates.TemplateResponse("panel-admin.html", {
            "request": request,
            "user": user,
            "usuarios": usuarios,
            "eliminar_error": "No se puede eliminar el usuario admin principal."
        })

    await db.users.delete_one({"username": username})
    params = urlencode({"eliminar_exito": f"Usuario '{username}' eliminado correctamente."})
    return RedirectResponse(f"/panel-admin?{params}", status_code=HTTP_302_FOUND)
