from flask import Flask, render_template_string, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

html = """
<!DOCTYPE html>
<html>
<head>
    <title>Skin Clinic Chatbot</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f2f2f2;
            margin: 0;
            padding: 0;
        }
        .chat-container {
            max-width: 600px;
            margin: 50px auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .chat-box {
            height: 400px;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
        }
        .user, .bot {
            max-width: 80%;
            padding: 10px 15px;
            border-radius: 20px;
            margin: 10px 0;
        }
        .user {
            background: #dcf8c6;
            align-self: flex-end;
        }
        .bot {
            background: #eee;
            align-self: flex-start;
        }
        .input-box {
            display: flex;
            padding: 10px;
            border-top: 1px solid #ddd;
        }
        .input-box input {
            flex: 1;
            padding: 10px;
            border: none;
            border-radius: 20px;
            font-size: 16px;
        }
        .input-box button {
            margin-left: 10px;
            padding: 10px 15px;
            border: none;
            background: #4CAF50;
            color: white;
            border-radius: 20px;
            cursor: pointer;
        }
        .option-button {
            margin: 5px;
            padding: 8px 12px;
            border: none;
            background-color: #f0f0f0;
            border-radius: 15px;
            cursor: pointer;
            display: inline-block;
        }
        .option-button:hover {
            background-color: #ddd;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-box" id="chatBox">
            <div class="bot">Hi! Welcome to our Skin Clinic. How can I help you today?</div>
        </div>
        <div class="input-box">
            <input type="text" id="userInput" placeholder="Type a message..." onkeydown="if(event.key==='Enter'){sendMessage()}">
            <button onclick="sendMessage()">Send</button>
        </div>
    </div>

    <script>
        function sendMessage(text=null) {
            let userInput = document.getElementById("userInput");
            let message = text || userInput.value.trim();
            if (!message) return;

            addMessage(message, 'user');
            userInput.value = '';

            fetch('/chat', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({message: message})
            })
            .then(response => response.json())
            .then(data => {
                addMessage(data.reply, 'bot');
                if (data.options) {
                    addOptions(data.options);
                }
            });
        }

        function addMessage(msg, sender) {
            const chatBox = document.getElementById("chatBox");
            const div = document.createElement("div");
            div.className = sender;
            div.innerText = msg;
            chatBox.appendChild(div);
            chatBox.scrollTop = chatBox.scrollHeight;
        }

        function addOptions(options) {
            const chatBox = document.getElementById("chatBox");
            const wrapper = document.createElement("div");
            wrapper.className = "bot";

            options.forEach(opt => {
                const btn = document.createElement("button");
                btn.className = "option-button";
                btn.innerText = opt;
                btn.onclick = () => {
                    sendMessage(opt);
                };
                wrapper.appendChild(btn);
            });

            chatBox.appendChild(wrapper);
            chatBox.scrollTop = chatBox.scrollHeight;
        }
    </script>
</body>
</html>
"""

# Basic flow control state
user_state = {}

@app.route("/")
def index():
    return render_template_string(html)

@app.route("/chat", methods=["POST"])
def chat():
    data = request.json
    user_msg = data.get("message", "").strip().lower()

    if user_msg in ["hi", "hello", "hey"]:
        return jsonify(reply="Hello! Please choose your concern:", options=["Acne", "Hair Loss", "Skin Allergy", "Anti-Aging", "Skin Pigmentation"])

    elif user_msg in ["acne", "hair loss", "skin allergy", "anti-aging", "skin pigmentation"]:
        concern = user_msg
        user_state["concern"] = concern
        if concern == "acne":
            return jsonify(reply="How often do you experience breakouts?", options=["Daily", "Weekly", "Occasionally"])
        elif concern == "hair loss":
            return jsonify(reply="Is your hair falling in patches or overall thinning?", options=["Patches", "Overall thinning"])
        elif concern == "skin allergy":
            return jsonify(reply="Do you experience itching or rashes?", options=["Itching", "Rashes", "Both"])
        elif concern == "anti-aging":
            return jsonify(reply="Are you looking for wrinkle treatment or skin tightening?", options=["Wrinkle treatment", "Skin tightening"])
        elif concern == "skin pigmentation":
            return jsonify(reply="Are the spots dark, red or white?", options=["Dark", "Red", "White"])

    elif user_msg in ["daily", "weekly", "occasionally", "patches", "overall thinning", "itching", "rashes", "both", "wrinkle treatment", "skin tightening", "dark", "red", "white"]:
        return jsonify(reply="Thanks for the information. One of our specialists will get in touch with you shortly!")

    return jsonify(reply="No problem! Feel free to ask any skin-related question anytime.")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5007)
