using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Elfisa.UI.Controls;
using Электронная_Фармация.Classes;

namespace Электронная_Фармация.UserControls
{
    public sealed class UCRefusals : UserControl
    {
        private readonly ModernDataGridView _grid;
        private readonly ModernDataGridView _detailsGrid;
        private readonly Panel _header;
        private readonly Label _title;
        private readonly ModernButton _btnRefresh;
        private readonly SplitContainer _split;

        public UCRefusals()
        {
            AutoScaleMode = AutoScaleMode.Dpi;
            Dock = DockStyle.Fill;
            Tag = "chrome-child";

            _header = new Panel
            {
                Dock = DockStyle.Top,
                Height = 44,
                Padding = new Padding(12, 10, 12, 8),
                Tag = "keep-bg"
            };

            _title = new Label
            {
                Dock = DockStyle.Left,
                Width = 200,
                Text = "Отказы",
                Font = new Font("Segoe UI Semibold", 13f, FontStyle.Bold),
                TextAlign = ContentAlignment.MiddleLeft
            };

            _btnRefresh = new ModernButton
            {
                Dock = DockStyle.Right,
                Width = 180,
                Text = "Обновить с сервера"
            };
            _btnRefresh.Click += async (_, __) => await RefreshFromServerAsync();

            _grid = CreateGrid();
            _detailsGrid = CreateGrid();

            _split = new SplitContainer
            {
                Dock = DockStyle.Fill,
                Orientation = Orientation.Horizontal,
                SplitterDistance = 260
            };
            _split.Panel1.Controls.Add(_grid);
            _split.Panel2.Controls.Add(_detailsGrid);

            _header.Controls.Add(_btnRefresh);
            _header.Controls.Add(_title);
            Controls.Add(_split);
            Controls.Add(_header);

            _grid.SelectionChanged += (_, __) => LoadRefusalDetails();

            Load += OnLoad;
        }

        private static ModernDataGridView CreateGrid()
        {
            return new ModernDataGridView
            {
                Dock = DockStyle.Fill,
                ReadOnly = true,
                MultiSelect = false,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                AllowUserToResizeRows = false
            };
        }

        private void OnLoad(object sender, EventArgs e)
        {
            UiThemeHelper.ApplyToControlTree(this);
            _header.Tag = "toolbar";
            ModernButtonStyles.ApplyAuto(_btnRefresh);
            Reload();
        }

        private async Task RefreshFromServerAsync()
        {
            _btnRefresh.Enabled = false;
            UseWaitCursor = true;
            try
            {
                var sync = new InvoiceSyncService();
                int count = await sync.SyncFromServerAsync();
                ToastNotification.ShowSuccess($"Загружено накладных: {count}");
                Reload();
            }
            catch (Exception ex)
            {
                AppDebugLog.Error("Refusals", "Не удалось загрузить отказы с API", ex);
                ToastNotification.ShowError($"Не удалось загрузить отказы: {ex.Message}");
            }
            finally
            {
                _btnRefresh.Enabled = true;
                UseWaitCursor = false;
            }
        }

        private void Reload()
        {
            using (var con = new SQLiteConnection(AppConfig.SqliteConnectionString))
            {
                con.Open();
                using (var cmd = new SQLiteCommand(GetQueryForNewSchema(), con))
                using (var da = new SQLiteDataAdapter(cmd))
                {
                    var table = new DataTable();
                    da.Fill(table);
                    _grid.DataSource = table;
                    if (_grid.Columns.Contains("ИД заказа"))
                    {
                        _grid.Columns["ИД заказа"].Visible = false;
                    }
                }
            }

            LoadRefusalDetails();
        }

        private void LoadRefusalDetails()
        {
            if (_grid.SelectedRows.Count == 0)
            {
                _detailsGrid.DataSource = null;
                return;
            }

            var orderNumber = _grid.SelectedRows[0].Cells["Номер заказа"]?.Value?.ToString();
            if (string.IsNullOrWhiteSpace(orderNumber))
            {
                return;
            }

            using (var con = new SQLiteConnection(AppConfig.SqliteConnectionString))
            {
                con.Open();
                using (var cmd = new SQLiteCommand(@"
select
    oi.[DrugName] as [Наименование],
    o.[SupplierName] as [Поставщик],
    oi.[Price] as [Цена],
    oi.[Zakaz] as [Заказано],
    ifnull(oi.[RefuseItemsCount], 0) as [Отказано],
    oi.[ExpiryPeriod] as [Срок годности]
from OrderItems oi
inner join Orders o on o.Id_Order = oi.Id_Order
where o.OrderNumber = @orderNumber
  and ifnull(oi.[RefuseItemsCount], 0) > 0
order by oi.[DrugName]", con))
                {
                    cmd.Parameters.AddWithValue("@orderNumber", orderNumber);
                    using (var da = new SQLiteDataAdapter(cmd))
                    {
                        var table = new DataTable();
                        da.Fill(table);
                        _detailsGrid.DataSource = table;
                    }
                }
            }
        }
        private static string GetQueryForNewSchema()
        {
            return @"
select
    o.[Id_Order] as [ИД заказа],
    o.[OrderNumber] as [Номер заказа],
    o.[OrderDate] as [Дата],
    o.[SupplierName] as [Поставщик],
    ifnull(o.[OrderedCountItems], 0) as [К-во товара в заказе],
    o.[SummaZakaza] as [Сумма заказа],
    sum(ifnull(oi.[RefuseItemsCount], 0)) as [К-во отказанного товара],
    sum(
        ifnull(oi.[RefuseItemsCount], 0) *
        ifnull(cast(replace(oi.[Price], ',', '.') as real), 0)
    ) as [Сумма отказа],
    o.[Comment] as [Комментарий],
    o.[OrderState] as [Статус]
from [Orders] o
inner join [OrderItems] oi on oi.[Id_Order] = o.[Id_Order]
group by
    o.[Id_Order],
    o.[OrderNumber],
    o.[OrderDate],
    o.[SupplierName],
    o.[OrderedCountItems],
    o.[SummaZakaza],
    o.[Comment],
    o.[OrderState]
having sum(ifnull(oi.[RefuseItemsCount], 0)) > 0
order by o.[OrderDate] desc;";
        }
    }
}
