@page "/admin/stores/create"
@layout AdminLayout
@inherits AdminBase
@using WebClientTpos.Client.Services
@using WebClientTpos.Shared.DTOs

@*
    EN: Create new store — wizard-like form connected to Merchant Service API.
    VI: Tạo cửa hàng mới — form dạng wizard kết nối API Merchant Service.
*@

<PageTitle>Tạo cửa hàng — aPOS Admin</PageTitle>

@* ═══ TOP BAR ═══ *@
<div class="admin-topbar">
    <div class="admin-topbar__left">
        <button class="admin-icon-btn" style="margin-right:8px;" @onclick="@(() => NavigateTo("stores"))">
            <i data-lucide="arrow-left"></i>
        </button>
        <div>
            <h1 class="admin-topbar__title">Tạo cửa hàng mới</h1>
            <p class="admin-topbar__subtitle">Thiết lập thông tin cơ bản để bắt đầu</p>
        </div>
    </div>
    <div class="admin-topbar__right">
        <span style="font-size:13px;color:var(--admin-text-tertiary);">Bước @_step / 3</span>
    </div>
</div>

@* ═══ CONTENT ═══ *@
<div class="admin-content" style="display:flex;flex-direction:column;gap:24px;max-width:720px;margin:0 auto;width:100%;">

    @* ── Success Message ── *@
    @if (_createSuccess)
    {
        <div style="text-align:center;padding:48px 24px;">
            <div style="width:80px;height:80px;border-radius:50%;background:rgba(34,197,94,0.15);display:flex;align-items:center;justify-content:center;margin:0 auto 24px;">
                <i data-lucide="check-circle" style="width:40px;height:40px;color:#22C55E;"></i>
            </div>
            <h2 style="font-size:24px;font-weight:700;color:var(--admin-text-primary);margin:0 0 8px;">Tạo cửa hàng thành công!</h2>
            <p style="font-size:15px;color:var(--admin-text-tertiary);margin:0 0 24px;">
                Cửa hàng <strong style="color:var(--admin-orange-primary);">@_storeName</strong> đã được tạo.
            </p>
            <button class="admin-btn-primary" @onclick="@(() => NavigateTo("stores"))">
                <i data-lucide="arrow-right"></i>
                <span>Xem danh sách cửa hàng</span>
            </button>
        </div>
    }
    else
    {
        @* ── Error Message ── *@
        @if (!string.IsNullOrEmpty(_errorMessage))
        {
            <div style="padding:12px 16px;border-radius:8px;background:rgba(239,68,68,0.12);color:#EF4444;font-size:14px;display:flex;align-items:center;gap:8px;">
                <i data-lucide="alert-circle" style="width:16px;height:16px;flex-shrink:0;"></i>
                <span>@_errorMessage</span>
            </div>
        }

        @* ── Step Indicator ── *@
        <div style="display:flex;gap:8px;align-items:center;">
            @for (int i = 1; i <= 3; i++)
            {
                var step = i;
                <div style="flex:1;height:4px;border-radius:4px;background-color:@(step <= _step ? "var(--admin-orange-primary)" : "var(--admin-bg-interactive)");transition:background 0.3s;"></div>
            }
        </div>

        @* ── Step 1: Business Info ── *@
        @if (_step == 1)
        {
            <div class="admin-panel">
                <div class="admin-panel__header">
                    <h3 class="admin-panel__title">
                        <i data-lucide="building-2" style="color:var(--admin-orange-primary);"></i>
                        Thông tin kinh doanh
                    </h3>
                </div>
                <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:20px;">
                    <div class="admin-form-group">
                        <label class="admin-form-label">Tên cửa hàng <span style="color:var(--admin-danger);">*</span></label>
                        <input class="admin-form-input" type="text" placeholder="VD: Coffee House Q1" @bind="_storeName" />
                    </div>

                    <div class="admin-form-group">
                        <label class="admin-form-label">Slug (URL) <span style="color:var(--admin-danger);">*</span></label>
                        <input class="admin-form-input" type="text" placeholder="coffee-house-q1" @bind="_slug" />
                        <small style="color:var(--admin-text-tertiary);font-size:12px;">Dùng cho đường dẫn cửa hàng. Chỉ dùng chữ thường, số và dấu gạch ngang.</small>
                    </div>

                    <div class="admin-form-group">
                        <label class="admin-form-label">Loại hình kinh doanh <span style="color:var(--admin-danger);">*</span></label>
                        <div style="display:grid;grid-template-columns:repeat(3, 1fr);gap:12px;">
                            @foreach (var type in _storeTypes)
                            {
                                var t = type;
                                <button class="admin-type-card @(_selectedType == t.Key ? "admin-type-card--active" : "")" @onclick="@(() => _selectedType = t.Key)">
                                    <i data-lucide="@t.Icon" style="width:24px;height:24px;color:@(t.Color);"></i>
                                    <span style="font-weight:600;font-size:14px;">@t.Label</span>
                                    <span style="font-size:12px;color:var(--admin-text-tertiary);">@t.Desc</span>
                                </button>
                            }
                        </div>
                    </div>

                    <div class="admin-form-group">
                        <label class="admin-form-label">Mô tả</label>
                        <textarea class="admin-form-input" rows="3" placeholder="Mô tả ngắn về cửa hàng..." @bind="_description"></textarea>
                    </div>
                </div>
            </div>
        }

        @* ── Step 2: Location ── *@
        @if (_step == 2)
        {
            <div class="admin-panel">
                <div class="admin-panel__header">
                    <h3 class="admin-panel__title">
                        <i data-lucide="map-pin" style="color:var(--admin-orange-primary);"></i>
                        Thông tin địa chỉ
                    </h3>
                </div>
                <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:20px;">
                    <div class="admin-form-group">
                        <label class="admin-form-label">Địa chỉ <span style="color:var(--admin-danger);">*</span></label>
                        <input class="admin-form-input" type="text" placeholder="Số nhà, đường" @bind="_address" />
                    </div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                        <div class="admin-form-group">
                            <label class="admin-form-label">Quận/Huyện</label>
                            <input class="admin-form-input" type="text" placeholder="VD: Quận 1" @bind="_district" />
                        </div>
                        <div class="admin-form-group">
                            <label class="admin-form-label">Tỉnh/Thành phố</label>
                            <input class="admin-form-input" type="text" placeholder="VD: TP.HCM" @bind="_city" />
                        </div>
                    </div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                        <div class="admin-form-group">
                            <label class="admin-form-label">Số điện thoại</label>
                            <input class="admin-form-input" type="tel" placeholder="0901 234 567" @bind="_phone" />
                        </div>
                        <div class="admin-form-group">
                            <label class="admin-form-label">Email</label>
                            <input class="admin-form-input" type="email" placeholder="store@example.com" @bind="_storeEmail" />
                        </div>
                    </div>
                </div>
            </div>
        }

        @* ── Step 3: Hours & Confirmation ── *@
        @if (_step == 3)
        {
            <div class="admin-panel">
                <div class="admin-panel__header">
                    <h3 class="admin-panel__title">
                        <i data-lucide="clock" style="color:var(--admin-orange-primary);"></i>
                        Giờ hoạt động
                    </h3>
                </div>
                <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:16px;">
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                        <div class="admin-form-group">
                            <label class="admin-form-label">Giờ mở cửa</label>
                            <input class="admin-form-input" type="time" @bind="_openTime" />
                        </div>
                        <div class="admin-form-group">
                            <label class="admin-form-label">Giờ đóng cửa</label>
                            <input class="admin-form-input" type="time" @bind="_closeTime" />
                        </div>
                    </div>
                    <div class="admin-form-group">
                        <label class="admin-form-label">Ngày hoạt động</label>
                        <div style="display:flex;gap:8px;">
                            @foreach (var day in new[] { "T2", "T3", "T4", "T5", "T6", "T7", "CN" })
                            {
                                var d = day;
                                <button class="admin-day-chip @(_activeDays.Contains(d) ? "admin-day-chip--active" : "")"
                                        @onclick="@(() => ToggleDay(d))">@d</button>
                            }
                        </div>
                    </div>
                </div>
            </div>

            @* Summary Card *@
            <div class="admin-panel" style="border:1px solid var(--admin-orange-primary);border-radius:16px;">
                <div class="admin-panel__header">
                    <h3 class="admin-panel__title">
                        <i data-lucide="check-circle" style="color:#22C55E;"></i>
                        Tóm tắt
                    </h3>
                </div>
                <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:10px;">
                    <div style="display:flex;justify-content:space-between;">
                        <span style="color:var(--admin-text-tertiary);">Tên cửa hàng</span>
                        <span style="font-weight:600;">@(string.IsNullOrEmpty(_storeName) ? "—" : _storeName)</span>
                    </div>
                    <div style="display:flex;justify-content:space-between;">
                        <span style="color:var(--admin-text-tertiary);">Slug</span>
                        <span style="font-weight:600;">@(string.IsNullOrEmpty(_slug) ? "—" : _slug)</span>
                    </div>
                    <div style="display:flex;justify-content:space-between;">
                        <span style="color:var(--admin-text-tertiary);">Loại hình</span>
                        <span style="font-weight:600;">@(_selectedType ?? "—")</span>
                    </div>
                    <div style="display:flex;justify-content:space-between;">
                        <span style="color:var(--admin-text-tertiary);">Địa chỉ</span>
                        <span style="font-weight:600;">@(string.IsNullOrEmpty(_address) ? "—" : $"{_address}, {_district}")</span>
                    </div>
                </div>
            </div>
        }

        @* ── Navigation Buttons ── *@
        <div style="display:flex;justify-content:space-between;padding-top:8px;">
            @if (_step > 1)
            {
                <button class="admin-btn-secondary" @onclick="PrevStep">
                    <i data-lucide="arrow-left"></i>
                    <span>Quay lại</span>
                </button>
            }
            else
            {
                <div></div>
            }

            @if (_step < 3)
            {
                <button class="admin-btn-primary" @onclick="NextStep">
                    <span>Tiếp theo</span>
                    <i data-lucide="arrow-right"></i>
                </button>
            }
            else
            {
                <button class="admin-btn-primary" @onclick="CreateStore" disabled="@_isCreating">
                    @if (_isCreating)
                    {
                        <span class="spinner-small" style="margin-right:8px;"></span>
                        <span>Đang tạo...</span>
                    }
                    else
                    {
                        <i data-lucide="check"></i>
                        <span>Tạo cửa hàng</span>
                    }
                </button>
            }
        </div>
    }
</div>

@code {
    [Inject] private MerchantApiService MerchantApi { get; set; } = default!;

    private int _step = 1;
    private string _storeName = "";
    private string _slug = "";
    private string _description = "";
    private string? _selectedType;
    private string _address = "";
    private string _district = "";
    private string _city = "";
    private string _phone = "";
    private string _storeEmail = "";
    private TimeOnly _openTime = new TimeOnly(7, 0);
    private TimeOnly _closeTime = new TimeOnly(22, 0);
    private HashSet<string> _activeDays = new() { "T2", "T3", "T4", "T5", "T6", "T7" };

    private bool _isCreating = false;
    private bool _createSuccess = false;
    private string? _errorMessage;

    private record StoreType(string Key, string Label, string Icon, string Color, string Desc);
    private readonly StoreType[] _storeTypes = new[]
    {
        new StoreType("cafe", "Café", "coffee", "#FF5C00", "Quán cà phê, trà sữa"),
        new StoreType("restaurant", "Nhà hàng / Bar", "utensils", "#3B82F6", "Nhà hàng, quán ăn, bar"),
        new StoreType("karaoke", "Karaoke", "mic", "#8B5CF6", "Karaoke, entertainment"),
        new StoreType("spa", "Spa", "sparkles", "#EC4899", "Spa, massage, wellness"),
        new StoreType("beauty", "Thẩm mỹ viện", "scissors", "#F472B6", "Salon, nail, thẩm mỹ"),
    };

    private void NextStep()
    {
        _errorMessage = null;
        if (_step == 1)
        {
            if (string.IsNullOrWhiteSpace(_storeName))
            {
                _errorMessage = "Vui lòng nhập tên cửa hàng";
                return;
            }
            if (string.IsNullOrWhiteSpace(_slug))
            {
                _errorMessage = "Vui lòng nhập slug cho cửa hàng";
                return;
            }
        }
        if (_step < 3) _step++;
    }

    private void PrevStep() { if (_step > 1) _step--; }

    private void ToggleDay(string day)
    {
        if (!_activeDays.Remove(day)) _activeDays.Add(day);
    }

    /// <summary>
    /// EN: Create shop via Merchant Service API — auto-registers merchant if needed.
    /// VI: Tạo shop qua API Merchant Service — tự đăng ký merchant nếu cần.
    /// </summary>
    private async Task CreateStore()
    {
        if (_isCreating) return;
        _errorMessage = null;
        _isCreating = true;
        StateHasChanged();

        // EN: Step 1 — Ensure merchant is registered (auto-register if not)
        // VI: Bước 1 — Đảm bảo đã đăng ký merchant (tự đăng ký nếu chưa)
        var merchantDto = new MerchantRegisterDto
        {
            BusinessName = _storeName,
            Type = "Individual"
        };
        var (merchantResult, merchantError) = await MerchantApi.RegisterMerchantAsync(merchantDto);
        
        // EN: 409 Conflict means already registered — that's OK, proceed
        // VI: 409 Conflict nghĩa là đã đăng ký rồi — OK, tiếp tục
        if (merchantResult == null && merchantError != null 
            && !merchantError.Contains("already has", StringComparison.OrdinalIgnoreCase))
        {
            _errorMessage = $"Đăng ký merchant thất bại: {merchantError}";
            _isCreating = false;
            StateHasChanged();
            return;
        }

        // EN: Step 2 — Create the shop
        // VI: Bước 2 — Tạo cửa hàng
        // EN: Use vertical-specific category values (not generic 'FoodBeverage')
        // VI: Dùng category riêng theo ngành hàng (không dùng 'FoodBeverage' chung)
        var category = _selectedType switch
        {
            "cafe" => "Cafe",
            "restaurant" => "Restaurant",
            "karaoke" => "Karaoke",
            "spa" => "Spa",
            "beauty" => "Beauty",
            _ => "Other"
        };

        var dto = new ShopCreateDto
        {
            Name = _storeName,
            Slug = _slug,
            Type = "Hybrid",
            Category = category,
            Description = _description,
            Phone = _phone,
            Email = _storeEmail
        };

        var (result, error) = await MerchantApi.CreateShopAsync(dto);

        if (result != null)
        {
            _createSuccess = true;
        }
        else
        {
            _errorMessage = error ?? "Không thể tạo cửa hàng";
        }

        _isCreating = false;
    }
}
