using System;
using Avalonia.Controls;
using Avalonia.Interactivity;

namespace MarkdownEditor.Views;

/// <summary>
/// Dialog for inputting and validating URLs.
/// </summary>
public partial class UrlInputDialog : Window
{
    public string Url { get; set; } = string.Empty;
    public bool IsConfirmed { get; private set; }

    public UrlInputDialog()
    {
        InitializeComponent();
    }

    public UrlInputDialog(string title, string prompt) : this()
    {
        Title = title;
        if (PromptText != null)
        {
            PromptText.Text = prompt;
        }
    }

    private void OnOk(object? sender, RoutedEventArgs e)
    {
        var urlText = UrlTextBox?.Text?.Trim() ?? string.Empty;

        if (string.IsNullOrWhiteSpace(urlText))
        {
            ShowError();
            return;
        }

        // Basic URL validation
        if (!IsValidUrl(urlText))
        {
            ShowError();
            return;
        }

        Url = urlText;
        IsConfirmed = true;
        Close();
    }

    private void OnCancel(object? sender, RoutedEventArgs e)
    {
        IsConfirmed = false;
        Close();
    }

    private void ShowError()
    {
        if (ErrorMessage != null)
        {
            ErrorMessage.IsVisible = true;
        }
    }

    private bool IsValidUrl(string url)
    {
        // Allow relative URLs (starting with /)
        if (url.StartsWith("/"))
            return true;

        // Allow URLs with common protocols
        if (url.StartsWith("http://") || url.StartsWith("https://") ||
            url.StartsWith("ftp://") || url.StartsWith("file://"))
        {
            return Uri.TryCreate(url, UriKind.Absolute, out _);
        }

        // Allow URLs without protocol (assume https)
        if (url.Contains("."))
        {
            return Uri.TryCreate("https://" + url, UriKind.Absolute, out _);
        }

        return false;
    }
}
