using ClaudeDo.Data;
using ClaudeDo.Ui.Services;
using ClaudeDo.Ui.ViewModels.Modals.Settings;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace ClaudeDo.Ui.ViewModels.Modals;

public sealed partial class SettingsModalViewModel : ViewModelBase
{
    private readonly WorkerClient _worker;

    public GeneralSettingsTabViewModel General { get; }
    public WorktreesSettingsTabViewModel Worktrees { get; }
    public FilesSettingsTabViewModel Files { get; }
    public PrimeClaudeTabViewModel Prime { get; }

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

    public Action? CloseAction { get; set; }

    public SettingsModalViewModel(WorkerClient worker, PrimeClaudeTabViewModel prime)
    {
        _worker = worker;
        General = new GeneralSettingsTabViewModel();
        Worktrees = new WorktreesSettingsTabViewModel(worker);
        Files = new FilesSettingsTabViewModel(worker);
        Prime = prime;
    }

    public async Task LoadAsync()
    {
        IsBusy = true;
        try
        {
            var dto = await _worker.GetAppSettingsAsync();
            if (dto is not null)
            {
                General.DefaultClaudeInstructions = dto.DefaultClaudeInstructions ?? "";
                General.DefaultModel = dto.DefaultModel ?? "sonnet";
                General.DefaultMaxTurns = dto.DefaultMaxTurns;
                General.DefaultPermissionMode = dto.DefaultPermissionMode ?? "auto";
                Worktrees.WorktreeStrategy = dto.WorktreeStrategy ?? "sibling";
                Worktrees.CentralWorktreeRoot = dto.CentralWorktreeRoot;
                Worktrees.WorktreeAutoCleanupEnabled = dto.WorktreeAutoCleanupEnabled;
                Worktrees.WorktreeAutoCleanupDays = dto.WorktreeAutoCleanupDays;
            }
            else StatusMessage = "Worker offline — settings read-only.";

            await Prime.LoadAsync();
        }
        finally { IsBusy = false; }
    }

    [RelayCommand]
    private async Task Save()
    {
        var err = General.Validate() ?? Worktrees.Validate() ?? Prime.Validate();
        if (err is not null) { ValidationError = err; return; }
        ValidationError = "";

        IsBusy = true;
        try
        {
            var dto = new AppSettingsDto(
                General.DefaultClaudeInstructions ?? "",
                General.DefaultModel ?? "sonnet",
                General.DefaultMaxTurns,
                General.DefaultPermissionMode ?? "auto",
                Worktrees.WorktreeStrategy ?? "sibling",
                string.IsNullOrWhiteSpace(Worktrees.CentralWorktreeRoot) ? null : Worktrees.CentralWorktreeRoot,
                Worktrees.WorktreeAutoCleanupEnabled,
                Worktrees.WorktreeAutoCleanupDays);
            await _worker.UpdateAppSettingsAsync(dto);
            await Prime.SaveAsync();
            CloseAction?.Invoke();
        }
        catch (Exception ex) { StatusMessage = $"Save failed: {ex.Message}"; }
        finally { IsBusy = false; }
    }

    [RelayCommand] private void Cancel() => CloseAction?.Invoke();
}
