// Placeholder for chat.css
// Placeholder for AIChatSessionView.razor
@page "/AIChatSessionView/{Id:guid}"
@using cetho.Module.BusinessObjects
@inject IObjectSpaceFactory ObjectSpaceFactory
@inject cetho.Module.BusinessObjects.OpenAIService AIService
@using System.Linq

<PageTitle > AI Chat Session</PageTitle >

<div class="max-w-3xl mx-auto p-6 bg-white shadow-lg rounded-2xl mt-6" >
<h2 class="text-2xl font-bold mb-4 text-blue-700" > @Session?.Title</h2 >

<div class="chat-box overflow-y-auto h-[400px] bg-gray-50 p-4 rounded-xl" >
@if (Session != null) {
    @foreach (var msg in Session.Messages.OrderBy(x => x.SentAt)) {
        <div class="mb-3"> <div class="font-semibold text-gray-700">@msg.Sender:</div> <div class="@((msg.Sender == "AI") ? "bg-blue-100" : "bg-green-100") p-3 rounded-xl inline-block max-w-[80%]"> @msg.Message </div> </div>
    }
}

</div >

<div class="mt-4 flex" >
<input @bind="UserInput" placeholder="Type message..."
class="flex-grow p-3 rounded-xl border border-gray-300 focus:ring focus:ring-blue-300 outline-none" / >
<button class="ml-3 px-5 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-xl" @onclick="SendMessage" > Send</button >
</div >
</div >

@code {
    [Parameter] public Guid Id

{
    get;
    set;
}

private AIChatSession Session;
private string UserInput = "";

protected override void OnInitialized() {
    using var os = ObjectSpaceFactory.CreateObjectSpace(typeof(AIChatSession));
    Session = os.GetObjectByKey<AIChatSession>(Id);
}

private async Task SendMessage() {
    if (string.IsNullOrWhiteSpace(UserInput)) return;
    using var os = ObjectSpaceFactory.CreateObjectSpace(typeof(AIChatMessage));
    var msg = os.CreateObject<AIChatMessage>();
    msg .Sender = "You";
    msg .Message = UserInput;
    msg .SentAt = DateTime.Now;
    msg .SessionChat = Session;
    os .CommitChanges();
    UserInput = "";
    StateHasChanged();
    var aiResponse = await AIService.AskAsync(msg.Message);
    var aiMsg = os.CreateObject<AIChatMessage>();
    aiMsg .Sender = "AI";
    aiMsg .Message = aiResponse;
    aiMsg .SentAt = DateTime.Now;
    aiMsg .SessionChat = Session;
    os .CommitChanges();
    // Refresh Session.Messages.Reload();
    StateHasChanged();
}
}
