from fastapi import APIRouter, Request, Form
from fastapi.responses import HTMLResponse, RedirectResponse

from app.core.auth import authenticate

router = APIRouter()


@router.get("/login", response_class=HTMLResponse)
def login_page():
    return """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TechSaathi Login</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f4f7fb;
            margin: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
        }
        .login-card {
            width: 360px;
            background: white;
            padding: 28px;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
        }
        h2 {
            margin: 0 0 8px;
            color: #173b67;
        }
        p {
            margin: 0 0 20px;
            color: #64748b;
        }
        input {
            width: 100%;
            padding: 12px 14px;
            margin-bottom: 14px;
            border: 1px solid #dbe2ea;
            border-radius: 10px;
            box-sizing: border-box;
        }
        button {
            width: 100%;
            padding: 12px 14px;
            border: none;
            border-radius: 10px;
            background: #2563eb;
            color: white;
            font-size: 15px;
            cursor: pointer;
        }
        button:hover {
            background: #1d4ed8;
        }
    </style>
</head>
<body>
    <div class="login-card">
        <h2>Admin Login</h2>
        <p>Login to access dashboard and admin panel.</p>
        <form method="post" action="/chatbot/login">
            <input name="username" placeholder="Username" required>
            <input name="password" type="password" placeholder="Password" required>
            <button type="submit">Login</button>
        </form>
    </div>
</body>
</html>
"""


@router.post("/login")
def login(request: Request, username: str = Form(...), password: str = Form(...)):
    if authenticate(username, password):
        request.session["user"] = username
        return RedirectResponse("/chatbot/admin", status_code=302)
    return RedirectResponse("/chatbot/login", status_code=302)


@router.get("/logout")
def logout(request: Request):
    request.session.clear()
    return RedirectResponse("/chatbot/login", status_code=302)