using System.Drawing.Printing;
using OrderPROPrint.Models;
using OrderPROPrint.Services;

namespace OrderPROPrint.Forms;

public partial class SettingsForm : Form
{
    private readonly AppSettings _settings;

    public SettingsForm(AppSettings settings)
    {
        _settings = settings;
        InitializeComponent();
        LoadSettings();
        LoadPrinters();
    }

    private void LoadSettings()
    {
        txtApiUrl.Text = _settings.ApiUrl;
        txtApiKey.Text = _settings.ApiKey;
        nudPollInterval.Value = Math.Clamp(_settings.PollIntervalSeconds, 5, 300);
    }

    private void LoadPrinters()
    {
        cmbPrinter.Items.Clear();
        foreach (string printer in PrinterSettings.InstalledPrinters)
        {
            cmbPrinter.Items.Add(printer);
        }

        if (!string.IsNullOrEmpty(_settings.PrinterName) && cmbPrinter.Items.Contains(_settings.PrinterName))
        {
            cmbPrinter.SelectedItem = _settings.PrinterName;
        }
        else if (cmbPrinter.Items.Count > 0)
        {
            cmbPrinter.SelectedIndex = 0;
        }
    }

    private async void BtnTestConnection_Click(object sender, EventArgs e)
    {
        var url = txtApiUrl.Text.Trim();
        var key = txtApiKey.Text.Trim();

        if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(key))
        {
            lblStatus.ForeColor = Color.Red;
            lblStatus.Text = "Wypełnij URL i klucz API";
            return;
        }

        lblStatus.ForeColor = Color.Gray;
        lblStatus.Text = "Testowanie...";
        btnTestConnection.Enabled = false;

        try
        {
            var client = new PrintApiClient(url, key);
            var success = await client.TestConnectionAsync();

            if (success)
            {
                lblStatus.ForeColor = Color.Green;
                lblStatus.Text = "Połączono \u2713";
            }
            else
            {
                lblStatus.ForeColor = Color.Red;
                lblStatus.Text = "Błąd autoryzacji — sprawdź klucz API";
            }
        }
        catch (Exception ex)
        {
            lblStatus.ForeColor = Color.Red;
            lblStatus.Text = $"Błąd: {ex.Message}";
        }
        finally
        {
            btnTestConnection.Enabled = true;
        }
    }

    private void BtnSave_Click(object sender, EventArgs e)
    {
        _settings.ApiUrl = txtApiUrl.Text.Trim().TrimEnd('/');
        _settings.ApiKey = txtApiKey.Text.Trim();
        _settings.PrinterName = cmbPrinter.SelectedItem?.ToString() ?? "";
        _settings.PollIntervalSeconds = (int)nudPollInterval.Value;
        _settings.Save();

        DialogResult = DialogResult.OK;
        Close();
    }

    private void BtnCancel_Click(object sender, EventArgs e)
    {
        DialogResult = DialogResult.Cancel;
        Close();
    }
}
