using System;
using System.Windows.Forms;
using Elfisa.UI.Helpers;
using Elfisa.UI.Theming;
using Электронная_Фармация.Classes;
using Электронная_Фармация.Properties;

namespace Электронная_Фармация.HelpForms
{
    public partial class HF_Settings : Form
    {
        public HF_Settings()
        {
            InitializeComponent();
            Shown += (_, __) => WindowChromeHelper.ApplyTitleBarTheme(this, ThemeManager.Colors);
        }

        private void HF_Settings_Load(object sender, EventArgs e)
        {
            UiThemeHelper.ApplyToControlTree(this);
            WindowChromeHelper.ApplyDialogChrome(this, panelHeader, lblTitle);

            txtLocationId.Text = AppConfig.LocationId;
            txtApiUrl.Text = string.IsNullOrWhiteSpace(Settings.Default.ApiBaseUrl)
                ? AppConfig.DefaultApiBaseUrl
                : Settings.Default.ApiBaseUrl;
            txtInvoiceExportPath.Text = AppConfig.InvoiceExportPath;
        }

        private void btnBrowseExportPath_Click(object sender, EventArgs e)
        {
            using (var dialog = new FolderBrowserDialog())
            {
                dialog.Description = "Выберите папку для экспорта накладных";
                dialog.ShowNewFolderButton = true;
                if (!string.IsNullOrWhiteSpace(txtInvoiceExportPath.Text) &&
                    System.IO.Directory.Exists(txtInvoiceExportPath.Text.Trim()))
                {
                    dialog.SelectedPath = txtInvoiceExportPath.Text.Trim();
                }

                if (dialog.ShowDialog(this) == DialogResult.OK)
                {
                    txtInvoiceExportPath.Text = dialog.SelectedPath;
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            var locationId = (txtLocationId.Text ?? string.Empty).Trim();
            var apiUrl = AppConfig.NormalizeApiBaseUrl(txtApiUrl.Text.Trim());
            var invoiceExportPath = (txtInvoiceExportPath.Text ?? string.Empty).Trim();

            if (string.IsNullOrWhiteSpace(locationId))
            {
                UiDialogs.ShowError("Укажите Location ID торговой точки.", "Настройки", this);
                txtLocationId.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(apiUrl))
            {
                UiDialogs.ShowError("Укажите адрес API сервера.", "Настройки", this);
                txtApiUrl.Focus();
                return;
            }

            if (!string.IsNullOrWhiteSpace(invoiceExportPath) &&
                !System.IO.Directory.Exists(invoiceExportPath))
            {
                UiDialogs.ShowError("Указанная папка для накладных не существует.", "Настройки", this);
                txtInvoiceExportPath.Focus();
                return;
            }

            AppConfig.SetLocationId(locationId);
            Settings.Default.ApiBaseUrl = apiUrl;
            AppConfig.SetInvoiceExportPath(invoiceExportPath);
            Settings.Default.Save();

            AppDebugLog.Info("Settings", $"Настройки сохранены. ApiBaseUrl={apiUrl}, LocationId={locationId}, InvoiceExportPath={invoiceExportPath}");
            ToastNotification.ShowSuccess("Настройки сохранены");

            DialogResult = DialogResult.OK;
            Close();
        }

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