using System.IO;
using ClaudeDo.Ui.Localization;
using ClaudeDo.Ui.Services;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace ClaudeDo.Ui.ViewModels.Modals.Settings;

public sealed partial class WorktreesSettingsTabViewModel : ViewModelBase
{
    private readonly IWorkerClient _worker;

    [ObservableProperty] private string _worktreeStrategy = "sibling";
    [ObservableProperty] private string? _centralWorktreeRoot;
    [ObservableProperty] private bool _worktreeAutoCleanupEnabled;
    [ObservableProperty] private int _worktreeAutoCleanupDays = 7;

    [ObservableProperty] private string _statusMessage = "";
    [ObservableProperty] private bool _isBusy;

    public OperationStatus ResetStatus { get; } = new();

    /// <summary>Wired by <c>WindowDialogService.ShowSettingsAsync</c>. A missing hook (null)
    /// must not reset silently — <see cref="ConfirmResetAll"/> aborts instead.</summary>
    public Func<string, Task<bool>>? ConfirmAsync { get; set; }

    public IReadOnlyList<string> WorktreeStrategies { get; } = new[] { "sibling", "central" };

    public WorktreesSettingsTabViewModel(IWorkerClient worker) => _worker = worker;

    public string? Validate()
    {
        if (WorktreeAutoCleanupEnabled && (WorktreeAutoCleanupDays < 1 || WorktreeAutoCleanupDays > 365))
            return "Cleanup days must be between 1 and 365.";
        if (WorktreeStrategy == "central")
        {
            if (string.IsNullOrWhiteSpace(CentralWorktreeRoot))
                return "Central worktree root is required for Central strategy.";
            if (!Directory.Exists(CentralWorktreeRoot))
                return $"Directory not found: {CentralWorktreeRoot}";
        }
        return null;
    }

    [RelayCommand]
    private async Task CleanupWorktrees()
    {
        IsBusy = true; StatusMessage = "";
        try
        {
            var r = await _worker.CleanupFinishedWorktreesAsync();
            StatusMessage = r is null ? Loc.T("vm.worktreesTab.workerOffline") : Loc.T("vm.worktreesTab.removed", r.Removed);
        }
        catch (Exception ex) { StatusMessage = Loc.T("vm.worktreesTab.cleanupFailed", ex.Message); }
        finally { IsBusy = false; }
    }

    [RelayCommand]
    private async Task ConfirmResetAll()
    {
        if (ConfirmAsync is null) return;
        if (!await ConfirmAsync(Loc.T("settings.worktrees.confirmRemoveAll"))) return;

        StatusMessage = "";
        using var op = ResetStatus.Begin(Loc.T("ops.worktrees.resetting"));
        try
        {
            var r = await _worker.ResetAllWorktreesAsync();
            if (r is null) StatusMessage = Loc.T("vm.worktreesTab.workerOffline");
            else if (r.Blocked) StatusMessage = Loc.T("vm.worktreesTab.blocked", r.RunningTasks);
            else StatusMessage = Loc.T("vm.worktreesTab.removedFrom", r.Removed, r.TasksAffected);
        }
        catch (Exception ex) { StatusMessage = Loc.T("vm.worktreesTab.resetFailed", ex.Message); }
    }
}
