from flask import Flask, request, jsonify, Response

app = Flask(__name__)

@app.route('/')
def index():
    html = r"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>Skin Clinic Chatbot</title>
        <style>
            body { font-family: Arial; background: #f4f4f4; padding: 20px; }
            #chatbox { max-width: 600px; margin: auto; background: #fff; padding: 20px; border-radius: 10px; }
            .message { margin: 10px 0; }
            .user { text-align: right; color: #007bff; }
            .bot { text-align: left; color: #333; }
            .option-btn { margin: 5px; padding: 8px 12px; border: none; border-radius: 5px; background: #007bff; color: #fff; cursor: pointer; }
        </style>
    </head>
    <body>
        <div id="chatbox">
            <h2>Skin Clinic Chatbot 💬</h2>
            <div id="messages"></div>
            <input id="user-input" placeholder="Type your message..." style="width:100%;padding:10px;" autofocus />
        </div>

        <script>
            const messages = document.getElementById('messages');
            const input = document.getElementById('user-input');

            function appendMessage(sender, text) {
                messages.innerHTML += `<div class="message ${sender}"><b>${sender === 'user' ? 'You' : 'Bot'}:</b> ${text}</div>`;
                messages.scrollTop = messages.scrollHeight;
            }

            function sendMessage(msg) {
                appendMessage('user', msg);
                fetch('/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message: msg })
                })
                .then(res => res.json())
                .then(data => {
                    appendMessage('bot', data.reply);
                    if (data.options) {
                        data.options.forEach(opt => {
                            messages.innerHTML += `<button class='option-btn' onclick="sendMessage('${opt}')">${opt}</button>`;
                        });
                    }
                });
            }

            input.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && input.value.trim()) {
                    sendMessage(input.value.trim());
                    input.value = '';
                }
            });

            window.onload = () => {
                sendMessage("Hi");
            };
        </script>
    </body>
    </html>
    """
    return Response(html, mimetype='text/html')


# Simple in-memory session state
user_state = {}

@app.route('/chat', methods=['POST'])
def chat():
    user_input = request.json.get("message", "").strip().lower()
    user_id = "default_user"

    state = user_state.get(user_id, {"step": "greet"})
    reply = ""
    options = []

    if state["step"] == "greet":
        if any(greet in user_input for greet in ["hi", "hello", "hey", "how are you"]):
            reply = "Hello! I’m your skin care assistant. What would you like help with today?"
            options = ["Acne", "Pigmentation", "Hair Fall"]
            state["step"] = "choose_topic"
        else:
            reply = "Hi there! You can say 'hi' or ask for help with a skin issue."
    elif state["step"] == "choose_topic":
        state["topic"] = user_input
        if user_input == "acne":
            reply = "Are you experiencing whiteheads, blackheads, or cystic acne?"
            options = ["Whiteheads", "Blackheads", "Cystic"]
        elif user_input == "pigmentation":
            reply = "Is the pigmentation light brown, dark, or patchy?"
            options = ["Light Brown", "Dark", "Patchy"]
        elif user_input == "hair fall":
            reply = "Is the hair fall sudden or gradual?"
            options = ["Sudden", "Gradual"]
        else:
            reply = "Sorry, I didn’t understand. Please select from the options."
            options = ["Acne", "Pigmentation", "Hair Fall"]
        state["step"] = "detail_question"
    elif state["step"] == "detail_question":
        reply = f"Thanks for sharing! We recommend you consult our dermatologist for the best treatment for {state.get('topic')}. Would you like to book an appointment?"
        options = ["Yes", "No"]
        state["step"] = "end"
    elif state["step"] == "end":
        if user_input == "yes":
            reply = "Great! Please call us at 9876543210 or visit our clinic. Have a healthy skin day! 🌟"
        else:
            reply = "No problem! Feel free to ask any skin-related question anytime."

    user_state[user_id] = state
    return jsonify({"reply": reply, "options": options})

if __name__ == "__main__":
    app.run(port=8080, debug=True)
