using JobsMedical.Web.Data;
using JobsMedical.Web.Models;
using JobsMedical.Web.Services;
using JobsMedical.Web.Services.Scraping;
using JobsMedical.Web.Services.Social;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace JobsMedical.Web.Pages.Admin;

[Authorize(Roles = "Admin")]
public class SocialModel : PageModel
{
    private readonly AppDbContext _db;
    private readonly SettingsService _settings;
    private readonly SocialPostService _social;

    public SocialModel(AppDbContext db, SettingsService settings, SocialPostService social)
    {
        _db = db; _settings = settings; _social = social;
    }

    [TempData] public string? Message { get; set; }
    [TempData] public string? Error { get; set; }

    public SocialDigest? Preview { get; private set; }

    [BindProperty] public bool SocialEnabled { get; set; }
    [BindProperty] public int SocialPostsPerDay { get; set; }
    [BindProperty] public string? SocialHeader { get; set; }
    [BindProperty] public string? SocialFooter { get; set; }
    [BindProperty] public bool SocialUseProxy { get; set; }
    [BindProperty] public bool SocialTelegramEnabled { get; set; }
    [BindProperty] public string? SocialTelegramBotToken { get; set; }
    [BindProperty] public string? SocialTelegramChatId { get; set; }
    [BindProperty] public bool SocialBaleEnabled { get; set; }
    [BindProperty] public string? SocialBaleBotToken { get; set; }
    [BindProperty] public string? SocialBaleChatId { get; set; }
    [BindProperty] public bool SocialInstagramEnabled { get; set; }
    [BindProperty] public string? InstagramHashtags { get; set; }

    public async Task OnGetAsync()
    {
        var s = await _settings.GetAsync();
        SocialEnabled = s.SocialEnabled;
        SocialPostsPerDay = s.SocialPostsPerDay;
        SocialHeader = s.SocialHeader;
        SocialFooter = s.SocialFooter;
        SocialUseProxy = s.SocialUseProxy;
        SocialTelegramEnabled = s.SocialTelegramEnabled;
        SocialTelegramBotToken = s.SocialTelegramBotToken;
        SocialTelegramChatId = s.SocialTelegramChatId;
        SocialBaleEnabled = s.SocialBaleEnabled;
        SocialBaleBotToken = s.SocialBaleBotToken;
        SocialBaleChatId = s.SocialBaleChatId;
        SocialInstagramEnabled = s.SocialInstagramEnabled;
        InstagramHashtags = s.InstagramHashtags;

        Preview = await _social.BuildDigestAsync(s);
    }

    public async Task<IActionResult> OnPostSaveAsync()
    {
        var s = await _settings.GetAsync();
        s.SocialEnabled = SocialEnabled;
        s.SocialPostsPerDay = Math.Clamp(SocialPostsPerDay, 1, 24);
        s.SocialHeader = SocialHeader?.Trim();
        s.SocialFooter = SocialFooter?.Trim();
        s.SocialUseProxy = SocialUseProxy;
        s.SocialTelegramEnabled = SocialTelegramEnabled;
        s.SocialTelegramBotToken = SocialTelegramBotToken?.Trim();
        s.SocialTelegramChatId = SocialTelegramChatId?.Trim();
        s.SocialBaleEnabled = SocialBaleEnabled;
        s.SocialBaleBotToken = SocialBaleBotToken?.Trim();
        s.SocialBaleChatId = SocialBaleChatId?.Trim();
        s.SocialInstagramEnabled = SocialInstagramEnabled;
        s.InstagramHashtags = InstagramHashtags?.Trim();
        s.UpdatedAt = DateTime.UtcNow;
        await _db.SaveChangesAsync();
        Message = "تنظیمات شبکه‌های اجتماعی ذخیره شد.";
        return RedirectToPage();
    }

    public async Task<IActionResult> OnPostSendNowAsync()
    {
        var r = await _social.PostAsync();
        if (r.Count == 0) Error = r.Error ?? "موردی برای انتشار نبود.";
        else
        {
            var parts = new List<string>();
            if (r.TelegramOk) parts.Add("تلگرام ✓");
            if (r.BaleOk) parts.Add("بله ✓");
            Message = parts.Count > 0
                ? $"ارسال شد ({string.Join("، ", parts)}) — {JalaliDate.ToPersianDigits(r.Count.ToString())} مورد."
                : "هیچ کانالی ارسال نشد؛ توکن/شناسه و فعال‌بودن را بررسی کن.";
            if (r.Error is not null && parts.Count == 0) Error = r.Error;
        }
        return RedirectToPage();
    }
}
