@page "/prompt"
@using Common.Dtos.Prompt
@using HushianWebApp.Service
@inject PromptService promptService

<div class="row" style="height: fit-content; padding: 1rem;">
	<div class="col-md-12">
		<TextAreaInput dir="rtl" style="text-align:right;margin-bottom:10px" @bind-value="@newPrompt.Test" class="form-control" placeholder="متن پرامپت"></TextAreaInput>
	</div>
	<div class="col-md-12" style="margin-bottom:10px;">
		<Button Color="ButtonColor.Success" @onclick="AddPrompt">ثبت</Button>
	</div>

	<div class="col-md-12">
		@if (loading)
		{
			<p>در حال بارگذاری...</p>
		}
		else if (prompts == null || prompts.Count == 0)
		{
			<p>موردی یافت نشد</p>
		}
		else
		{
			<table class="table table-striped">
				<thead>
					<tr>
						<th>متن</th>
						<th style="width:110px">عملیات</th>
					</tr>
				</thead>
				<tbody>
					@foreach (var p in prompts)
					{
						<tr>
							<td>
								<TextAreaInput class="form-control" @bind-value="p.Test"></TextAreaInput>
							</td>
							<td>
								<Button Color="ButtonColor.Warning" class="me-1" @onclick="(()=>UpdatePrompt(p))"><Icon Name="IconName.CloudLightning" /></Button>
								<Button Color="ButtonColor.Danger" @onclick="(()=>DeletePrompt(p.ID))"><Icon Name="IconName.Trash" /></Button>
							</td>
						</tr>
					}
				</tbody>
			</table>
		}
	</div>
</div>

@code {
	private List<ReadANDUpdate_PromptDto> prompts = new();
	private ADD_PromptDto newPrompt = new();
	private bool loading = false;
}
@functions {
	protected override async Task OnInitializedAsync()
	{
		await LoadPrompts();
	}
	private async Task LoadPrompts()
	{
		loading = true;
		prompts = await promptService.GetPrompts();
		loading = false;
	}
	private async Task AddPrompt()
	{
		if (!string.IsNullOrWhiteSpace(newPrompt.Test))
		{
			if (await promptService.AddPrompt(newPrompt))
			{
				newPrompt = new();
				await LoadPrompts();
			}
		}
	}
	private async Task UpdatePrompt(ReadANDUpdate_PromptDto model)
	{
		if (!string.IsNullOrWhiteSpace(model.Test))
		{
			if (await promptService.UpdatePrompt(model))
			{
				await LoadPrompts();
			}
		}
	}
	private async Task DeletePrompt(int id)
	{
		if (await promptService.DeletePrompt(id))
		{
			await LoadPrompts();
		}
	}
}




