@using WebClientTpos.Client.Services
@using WebClientTpos.Client.Pages.Admin.Shop
@inject PosDataService DataService
@inject NavigationManager Nav

<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;gap:12px;">
    <div style="display:flex;gap:8px;flex:1;"><input type="text" @bind="_storageSearch" @bind:event="oninput" placeholder="Tìm kiếm tệp…" style="flex:1;max-width:320px;padding:8px 14px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:13px;" /><button class="admin-btn-primary" @onclick="SearchStorageFiles"><i data-lucide="search" style="width:14px;height:14px;"></i>Tìm</button></div>
    <div style="display:flex;gap:8px;"><button class="admin-btn-primary" @onclick="ToggleFolderForm"><i data-lucide="folder-plus" style="width:14px;height:14px;"></i>Thư mục mới</button><label class="admin-btn-primary" style="cursor:pointer;"><i data-lucide="upload" style="width:14px;height:14px;"></i>Upload<InputFile OnChange="HandleDriveUpload" style="display:none;" /></label></div>
</div>
@if (_showFolderForm)
{
    <div class="admin-panel" style="margin-bottom:16px;"><div class="admin-panel__body" style="display:flex;gap:8px;align-items:center;"><input type="text" @bind="_newFolderName" placeholder="Tên thư mục" style="flex:1;padding:8px 14px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:13px;" /><button class="admin-btn-primary" @onclick="CreateFolder">Tạo</button><button @onclick="HideFolderForm" style="padding:8px 14px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-secondary);cursor:pointer;font-size:13px;">Hủy</button></div></div>
}
@if (_currentFolderId.HasValue)
{
    <div style="margin-bottom:12px;"><button @onclick="NavigateToParentFolder" style="padding:6px 12px;border-radius:6px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);cursor:pointer;font-size:12px;"><i data-lucide="arrow-left" style="width:14px;height:14px;"></i> Quay lại</button></div>
}
@if (_storageFolders.Any())
{
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;margin-bottom:20px;">
    @foreach (var folder in _storageFolders)
    {
        <div @onclick="@(() => NavigateToFolder(folder.Id))" style="padding:16px;border-radius:12px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);cursor:pointer;display:flex;align-items:center;gap:10px;"><i data-lucide="folder" style="width:24px;height:24px;color:#F59E0B;"></i><div style="flex:1;min-width:0;"><div style="font-size:13px;font-weight:600;">@folder.Name</div><div style="font-size:11px;color:var(--admin-text-tertiary);">@folder.CreatedAt.ToString("dd/MM/yyyy")</div></div><button @onclick="@(() => DeleteFolder(folder.Id))" @onclick:stopPropagation style="padding:4px;border:none;background:transparent;color:var(--admin-text-tertiary);cursor:pointer;"><i data-lucide="trash-2" style="width:14px;height:14px;"></i></button></div>
    }
    </div>
}
<div class="admin-panel"><div class="admin-panel__header"><h3 class="admin-panel__title">Tệp (@_storageFiles.Count)</h3></div><div class="admin-panel__body" style="padding:0;">
@if (!_storageFiles.Any())
{
    <div style="padding:40px;text-align:center;color:var(--admin-text-tertiary);"><i data-lucide="file-x" style="width:40px;height:40px;margin-bottom:8px;opacity:0.3;"></i><div>Chưa có tệp nào.</div></div>
}
else
{
    <table class="admin-data-table"><thead><tr><th>Tên tệp</th><th>Loại</th><th>Kích thước</th><th>Ngày upload</th><th>Thao tác</th></tr></thead><tbody>
    @foreach (var f in _storageFiles)
    {
        <tr><td>@f.FileName</td><td style="font-size:12px;">@(f.ContentType ?? "—")</td><td style="font-size:12px;">@ShopHelpers.FormatFileSize(f.FileSizeBytes)</td><td style="font-size:12px;">@f.UploadedAt.ToString("dd/MM/yyyy HH:mm")</td><td><button @onclick="@(() => DownloadStorageFile(f.Id))" style="padding:4px 8px;border-radius:6px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);cursor:pointer;font-size:11px;"><i data-lucide="download" style="width:12px;height:12px;"></i></button><button @onclick="@(() => DeleteStorageFile(f.Id))" style="padding:4px 8px;border-radius:6px;border:none;background:rgba(239,68,68,0.1);color:#EF4444;cursor:pointer;font-size:11px;"><i data-lucide="trash-2" style="width:12px;height:12px;"></i></button></td></tr>
    }
    </tbody></table>
}
</div></div>

@code {
    [Parameter] public Guid ShopId { get; set; }

    private List<PosDataService.StorageFileInfo> _storageFiles = new();
    private List<PosDataService.StorageFolderInfo> _storageFolders = new();
    private Guid? _currentFolderId;
    private string _newFolderName = "";
    private bool _showFolderForm;
    private string _storageSearch = "";

    protected override async Task OnInitializedAsync()
    {
        _storageFolders = await DataService.GetFoldersAsync(_currentFolderId);
        _storageFiles = await DataService.GetStorageFilesAsync(search: _storageSearch);
    }

    private void ToggleFolderForm() => _showFolderForm = !_showFolderForm;
    private void HideFolderForm() => _showFolderForm = false;

    private async Task SearchStorageFiles() => _storageFiles = await DataService.GetStorageFilesAsync(search: _storageSearch);

    private async Task NavigateToFolder(Guid id)
    {
        _currentFolderId = id;
        _storageFolders = await DataService.GetFoldersAsync(id);
        _storageFiles = await DataService.GetStorageFilesAsync(search: _storageSearch);
    }

    private async Task NavigateToParentFolder()
    {
        _currentFolderId = null;
        _storageFolders = await DataService.GetFoldersAsync(null);
        _storageFiles = await DataService.GetStorageFilesAsync(search: _storageSearch);
    }

    private async Task CreateFolder()
    {
        if (string.IsNullOrWhiteSpace(_newFolderName)) return;
        await DataService.CreateFolderAsync(new PosDataService.CreateFolderRequest(_newFolderName.Trim(), _currentFolderId));
        _newFolderName = "";
        _showFolderForm = false;
        _storageFolders = await DataService.GetFoldersAsync(_currentFolderId);
    }

    private async Task DeleteFolder(Guid id)
    {
        await DataService.DeleteFolderAsync(id);
        _storageFolders = await DataService.GetFoldersAsync(_currentFolderId);
    }

    private async Task DeleteStorageFile(Guid id)
    {
        await DataService.DeleteStorageFileAsync(id);
        _storageFiles = await DataService.GetStorageFilesAsync(search: _storageSearch);
    }

    private async Task DownloadStorageFile(Guid id)
    {
        var url = await DataService.GetDownloadUrlAsync(id);
        if (url != null) Nav.NavigateTo(url, forceLoad: true);
    }

    private async Task HandleDriveUpload(InputFileChangeEventArgs e)
    {
        foreach (var f in e.GetMultipleFiles(20))
        {
            using var s = f.OpenReadStream(10_485_760);
            await DataService.UploadImageAsync(s, f.Name, f.ContentType);
        }
        _storageFiles = await DataService.GetStorageFilesAsync(search: _storageSearch);
    }
}
