using ClaudeDo.Data.Models;
using ClaudeDo.Ui.Services;
using ClaudeDo.Ui.ViewModels.Modals;
using Xunit;
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;

namespace ClaudeDo.Ui.Tests.ViewModels;

// The overview's 4s reconcile tick goes through LoadAsync, which rebuilds every row instance and
// resets SelectedCount/ConflictRows/BatchProgress. Left bare, that wipes the user's batch-merge
// ticks and the highlighted row every four seconds — assembling a multi-worktree selection would
// be impossible. The tick has to carry that state across the reload.
public class WorktreesOverviewReconcileTickTests
{
    private sealed class FakeWorker : StubWorkerClient
    {
        public List<WorktreeOverviewDto> Worktrees { get; set; } = new();
        public override Task<List<WorktreeOverviewDto>> GetWorktreesOverviewAsync(string? listId)
            => Task.FromResult(Worktrees.ToList());
        public override Task<MergeTargetsDto?> GetMergeTargetsAsync(string taskId)
            => Task.FromResult<MergeTargetsDto?>(new MergeTargetsDto("main", new[] { "main" }, "chore(list): merge t"));
    }

    private static WorktreeOverviewDto Wt(string taskId, WorktreeState state = WorktreeState.Active) =>
        new(taskId, $"Task {taskId}", TaskStatus.WaitingForReview, "L1", "Work",
            $@"C:\wt\{taskId}", $"claudedo/{taskId}", "base0", state, "+1 -0",
            DateTime.UtcNow, PathExistsOnDisk: true);

    private static async Task<(WorktreesOverviewModalViewModel Vm, FakeWorker Worker)> BuildLoadedAsync()
    {
        var worker = new FakeWorker { Worktrees = { Wt("a"), Wt("b"), Wt("c") } };
        var vm = new WorktreesOverviewModalViewModel(
            worker, () => throw new InvalidOperationException("no diff vm in this test"),
            new ClaudeDo.Ui.Services.MergeCoordinator());
        vm.Configure("L1", "Work");
        await vm.LoadAsync();
        return (vm, worker);
    }

    [Fact]
    public async Task Tick_keeps_the_batch_merge_ticks()
    {
        var (vm, _) = await BuildLoadedAsync();

        vm.Rows.Single(r => r.TaskId == "a").IsChecked = true;
        vm.Rows.Single(r => r.TaskId == "c").IsChecked = true;
        Assert.Equal(2, vm.SelectedCount);

        await vm.ReconcileTickAsync();

        Assert.True(vm.Rows.Single(r => r.TaskId == "a").IsChecked);
        Assert.False(vm.Rows.Single(r => r.TaskId == "b").IsChecked);
        Assert.True(vm.Rows.Single(r => r.TaskId == "c").IsChecked);
        Assert.Equal(2, vm.SelectedCount);
    }

    [Fact]
    public async Task Tick_re_points_the_selected_row_at_the_fresh_instance()
    {
        var (vm, _) = await BuildLoadedAsync();

        vm.SelectRow(vm.Rows.Single(r => r.TaskId == "b"));

        await vm.ReconcileTickAsync();

        Assert.NotNull(vm.SelectedRow);
        Assert.Equal("b", vm.SelectedRow!.TaskId);
        // Not the stale pre-reload instance: it must be the row actually in the collection.
        Assert.Contains(vm.Rows, r => ReferenceEquals(r, vm.SelectedRow));
        Assert.True(vm.SelectedRow.IsSelected);
    }

    [Fact]
    public async Task Tick_clears_the_selection_when_that_worktree_is_gone()
    {
        var (vm, worker) = await BuildLoadedAsync();

        vm.SelectRow(vm.Rows.Single(r => r.TaskId == "b"));
        worker.Worktrees.RemoveAll(w => w.TaskId == "b");

        await vm.ReconcileTickAsync();

        Assert.Null(vm.SelectedRow);
    }

    [Fact]
    public async Task Tick_keeps_a_finished_batch_outcome_and_its_conflict_row()
    {
        var (vm, _) = await BuildLoadedAsync();

        vm.Rows.Single(r => r.TaskId == "a").MergeOutcome = BatchMergeOutcome.Merged;
        vm.Rows.Single(r => r.TaskId == "b").MergeOutcome = BatchMergeOutcome.Conflict;

        await vm.ReconcileTickAsync();

        Assert.Equal(BatchMergeOutcome.Merged, vm.Rows.Single(r => r.TaskId == "a").MergeOutcome);
        Assert.Equal(BatchMergeOutcome.Conflict, vm.Rows.Single(r => r.TaskId == "b").MergeOutcome);
        Assert.Single(vm.ConflictRows);
        Assert.Equal("b", vm.ConflictRows[0].TaskId);
    }

    [Fact]
    public async Task Tick_leaves_a_newly_appeared_worktree_unticked()
    {
        var (vm, worker) = await BuildLoadedAsync();

        vm.Rows.Single(r => r.TaskId == "a").IsChecked = true;
        worker.Worktrees.Add(Wt("d"));

        await vm.ReconcileTickAsync();

        Assert.True(vm.Rows.Single(r => r.TaskId == "a").IsChecked);
        Assert.False(vm.Rows.Single(r => r.TaskId == "d").IsChecked);
        Assert.Equal(1, vm.SelectedCount);
    }

    [Theory]
    [InlineData("refresh")]
    [InlineData("cleanup")]
    [InlineData("forceRemove")]
    [InlineData("batchMerge")]
    public async Task Tick_skips_the_reload_while_any_action_status_is_running(string which)
    {
        var (vm, worker) = await BuildLoadedAsync();
        var status = which switch
        {
            "refresh" => vm.RefreshStatus,
            "cleanup" => vm.CleanupStatus,
            "forceRemove" => vm.ForceRemoveStatus,
            "batchMerge" => vm.BatchMergeStatus,
            _ => throw new ArgumentOutOfRangeException(nameof(which)),
        };

        using var op = status.Begin("running");
        worker.Worktrees.Add(Wt("d"));

        await vm.ReconcileTickAsync();

        Assert.DoesNotContain(vm.Rows, r => r.TaskId == "d");
    }
}
