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

namespace JobsMedical.Web.Pages.Shifts;

public class IndexModel : PageModel
{
    private readonly AppDbContext _db;
    public IndexModel(AppDbContext db) => _db = db;

    [BindProperty(SupportsGet = true)] public int? CityId { get; set; }
    [BindProperty(SupportsGet = true)] public int? DistrictId { get; set; }
    [BindProperty(SupportsGet = true)] public int? RoleId { get; set; }
    [BindProperty(SupportsGet = true)] public int? FacilityId { get; set; }
    [BindProperty(SupportsGet = true)] public ShiftType? ShiftType { get; set; }
    [BindProperty(SupportsGet = true)] public bool PaidOnly { get; set; }
    [BindProperty(SupportsGet = true)] public bool ShareOnly { get; set; }   // فقط شیفت‌های سهم درآمد
    [BindProperty(SupportsGet = true)] public Gender? GenderFilter { get; set; }

    // "Near me": the browser sends the visitor's coordinates and we sort by distance.
    [BindProperty(SupportsGet = true)] public double? Lat { get; set; }
    [BindProperty(SupportsGet = true)] public double? Lng { get; set; }

    // Pretty-URL segments (/شیفت/{roleSlug}/{citySlug?}); resolved to RoleId/CityId below.
    [BindProperty(SupportsGet = true)] public string? RoleSlug { get; set; }
    [BindProperty(SupportsGet = true)] public string? CitySlug { get; set; }

    // NB: must NOT be named "Page" — "page" is a reserved Razor Pages route value, so a bound
    // property called Page never picks up ?page=N (it stayed 1, breaking pagination). Bind from "p".
    [BindProperty(SupportsGet = true, Name = "p")] public int PageNumber { get; set; } = 1;
    private const int PageSize = 24;
    public int TotalCount { get; private set; }
    public int TotalPages { get; private set; }
    public int CurrentPage { get; private set; }

    public bool NearMeActive => Lat is not null && Lng is not null;

    public List<Shift> Results { get; private set; } = new();
    public List<City> Cities { get; private set; } = new();
    public List<District> Districts { get; private set; } = new();
    public List<Role> Roles { get; private set; } = new();
    public List<Facility> Facilities { get; private set; } = new();

    /// <summary>Dynamic page heading/H1 + title, set from the active role/city for SEO.</summary>
    public string PageHeading { get; private set; } = "شیفت‌های خالی";

    /// <summary>A short unique intro shown on role/city landing pages (avoids thin-content).</summary>
    public string? PageIntro { get; private set; }

    /// <summary>Breadcrumb trail (also emitted as BreadcrumbList JSON-LD).</summary>
    public IReadOnlyList<Crumb> Breadcrumbs { get; private set; } = Array.Empty<Crumb>();

    public async Task<IActionResult> OnGetAsync()
    {
        var today = DateOnly.FromDateTime(DateTime.UtcNow);

        Cities = await _db.Cities.Where(c => c.IsActive).OrderBy(c => c.Name).ToListAsync();
        Roles = await _db.Roles.Where(r => r.IsActive).OrderBy(r => r.SortOrder).ToListAsync();

        // Pretty-URL landing: resolve slugs → filters (404 on a slug that matches nothing).
        if (!string.IsNullOrWhiteSpace(RoleSlug))
        {
            var role = Roles.FirstOrDefault(r => SeoSlug.Matches(r.Name, RoleSlug));
            if (role is null) return NotFound();
            RoleId = role.Id;
        }
        if (!string.IsNullOrWhiteSpace(CitySlug))
        {
            var city = Cities.FirstOrDefault(c => SeoSlug.Matches(c.Name, CitySlug));
            if (city is null) return NotFound();
            CityId = city.Id;
        }

        Districts = await _db.Districts
            .Where(d => d.IsActive && (CityId == null || d.CityId == CityId))
            .OrderBy(d => d.Name).ToListAsync();
        Facilities = await _db.Facilities
            .Where(f => CityId == null || f.CityId == CityId)
            .OrderBy(f => f.Name).ToListAsync();

        var q = _db.Shifts
            .Include(s => s.Facility).ThenInclude(f => f.City)
            .Include(s => s.Facility).ThenInclude(f => f.District)
            .Include(s => s.Role)
            .Where(s => s.Status == ShiftStatus.Open && s.Date >= today);

        if (CityId is not null) q = q.Where(s => s.Facility.CityId == CityId);
        if (DistrictId is not null) q = q.Where(s => s.Facility.DistrictId == DistrictId);
        if (RoleId is not null) q = q.Where(s => s.RoleId == RoleId);
        if (FacilityId is not null) q = q.Where(s => s.FacilityId == FacilityId);
        if (ShiftType is not null) q = q.Where(s => s.ShiftType == ShiftType);
        if (PaidOnly) q = q.Where(s => s.PayAmount != null);
        if (ShareOnly) q = q.Where(s => s.SharePercent != null);
        // A given gender sees listings open to them (their gender or "فرقی نمی‌کند").
        if (GenderFilter is Gender g && g != Gender.Any)
            q = q.Where(s => s.GenderRequirement == Gender.Any || s.GenderRequirement == g);

        TotalCount = await q.CountAsync();
        TotalPages = Math.Max(1, (int)Math.Ceiling(TotalCount / (double)PageSize));
        CurrentPage = Math.Clamp(PageNumber, 1, TotalPages);
        var skip = (CurrentPage - 1) * PageSize;

        if (NearMeActive)
        {
            // Distance sort needs all rows in memory; paginate after sorting (shifts without coords last).
            var all = await q.ToListAsync();
            foreach (var s in all)
                if (s.Facility.Lat is double flat && s.Facility.Lng is double flng)
                    s.DistanceKm = Geo.DistanceKm(Lat!.Value, Lng!.Value, flat, flng);
            Results = all
                .OrderBy(s => s.DistanceKm ?? double.MaxValue)
                .ThenBy(s => s.Date).ThenBy(s => s.StartTime)
                .Skip(skip).Take(PageSize).ToList();
        }
        else
        {
            Results = await q.OrderBy(s => s.Date).ThenBy(s => s.StartTime)
                             .Skip(skip).Take(PageSize).ToListAsync();
        }

        SetSeo(Roles.FirstOrDefault(r => r.Id == RoleId)?.Name, Cities.FirstOrDefault(c => c.Id == CityId)?.Name);
        return Page();
    }

    /// <summary>Title/H1/meta from the active role+city so the page targets «شیفت [نقش] [شهر]».</summary>
    private void SetSeo(string? role, string? city)
    {
        PageHeading =
            role is not null && city is not null ? $"شیفت {role} در {city}"
            : role is not null ? $"شیفت {role}"
            : city is not null ? $"شیفت کادر درمان در {city}"
            : "شیفت‌های خالی";
        ViewData["Title"] = PageHeading;
        ViewData["Description"] = role is not null || city is not null
            ? $"جدیدترین {PageHeading} در همکادر؛ مشاهده شیفت‌ها و تماس مستقیم با مراکز درمانی."
            : "شیفت‌های خالی کادر درمان (پزشک، پرستار، ماما، تکنسین) در بیمارستان‌ها و کلینیک‌های تهران — همکادر.";
        if (role is not null || city is not null)
            PageIntro = $"در این صفحه جدیدترین {PageHeading}، گردآوری‌شده از منابع معتبر، را می‌بینید. "
                + "روی هر شیفت بزنید تا تاریخ، ساعت، پرداخت و راهِ تماسِ مستقیم با مرکز درمانی نمایش داده شود. "
                + "برای موارد مرتبط، نقش یا شهر دیگری را از لینک‌های بالا انتخاب کنید.";

        var crumbs = new List<Crumb> { new("خانه", "/"), new("شیفت‌ها", "/Shifts") };
        if (role is not null) crumbs.Add(new(role, "/شیفت/" + SeoSlug.Of(role)));
        if (city is not null) crumbs.Add(new(city, null));
        Breadcrumbs = crumbs;
    }
}
