using System.Windows.Controls;
using ClaudeDo.Installer.Core;
using ClaudeDo.Installer.Localization;
using CommunityToolkit.Mvvm.ComponentModel;

namespace ClaudeDo.Installer.Pages.PathsPage;

public partial class PathsPageViewModel : ObservableObject, IInstallerPage
{
    private readonly InstallContext _context;
    private PathsPageView? _view;

    public string Title => TrExtension.Localizer?["installer.paths.title"] ?? "Paths";
    public string Icon => "\uE8B7";
    public int Order => 2;
    public bool ShowInWizard => true;
    public bool ShowInSettings => true;
    public UserControl View => _view ??= new PathsPageView { DataContext = this };

    [ObservableProperty] private string _dbPath = "~/.claudeDo/todo.db";
    [ObservableProperty] private string _logRoot = "~/.claudeDo/logs";
    [ObservableProperty] private string _sandboxRoot = "~/.claudeDo/sandbox";
    [ObservableProperty] private string _worktreeRootStrategy = "sibling";
    [ObservableProperty] private string _centralWorktreeRoot = "~/.claudeDo/worktrees";
    [ObservableProperty] private string? _validationError;

    public bool IsCentralVisible => WorktreeRootStrategy == "central";

    public PathsPageViewModel(InstallContext context) => _context = context;

    partial void OnWorktreeRootStrategyChanged(string value) =>
        OnPropertyChanged(nameof(IsCentralVisible));

    public Task LoadAsync()
    {
        var cfg = InstallerWorkerConfig.Load();
        DbPath = cfg.DbPath;
        LogRoot = cfg.LogRoot;
        SandboxRoot = cfg.SandboxRoot;
        WorktreeRootStrategy = cfg.WorktreeRootStrategy;
        CentralWorktreeRoot = cfg.CentralWorktreeRoot;
        return Task.CompletedTask;
    }

    public Task ApplyAsync()
    {
        _context.DbPath = DbPath;
        _context.UiDbPath = DbPath;
        _context.LogRoot = LogRoot;
        _context.SandboxRoot = SandboxRoot;
        _context.WorktreeRootStrategy = WorktreeRootStrategy;
        _context.CentralWorktreeRoot = CentralWorktreeRoot;
        return Task.CompletedTask;
    }

    public bool Validate()
    {
        if (string.IsNullOrWhiteSpace(DbPath) ||
            string.IsNullOrWhiteSpace(LogRoot) ||
            string.IsNullOrWhiteSpace(SandboxRoot))
        {
            ValidationError = "All path fields are required.";
            return false;
        }

        if (WorktreeRootStrategy == "central" && string.IsNullOrWhiteSpace(CentralWorktreeRoot))
        {
            ValidationError = "Central worktree root is required when using central strategy.";
            return false;
        }

        ValidationError = null;
        return true;
    }
}
