using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Media.Imaging;
using System.Linq;
using Avalonia.Platform.Storage;
using demko_v.Models;

namespace demko_v;

public partial class EditAgentWindow : Window
{
    public string PathToImage = string.Empty;
    public Agent agentPresenter;
    public List<string> AgentTypesList { get; }
    
    public EditAgentWindow(Agent agentInput)
    {
        using var ctx = new DemoAgentsContext();
        InitializeComponent();
        agentPresenter = agentInput;
        
        AgentTypesList = ctx.AgentTypes.Select(a => a.Title).ToList();
        TypeAgentAddCombobox.ItemsSource = AgentTypesList;
        
        Otrisovka();
    }

    private async void EditAgent_OnClick(object? sender, RoutedEventArgs e)
    {
        using var ctx = new DemoAgentsContext();

        if (string.IsNullOrWhiteSpace(TitleTextBox.Text)) return;
        agentPresenter.Title = TitleTextBox.Text;

        if (!int.TryParse(PriorityTextBox.Text, out int priority)) return;
        agentPresenter.Priority = priority;

        if (string.IsNullOrWhiteSpace(AddressTextBox.Text)) return;
        agentPresenter.Address = AddressTextBox.Text;

        if (string.IsNullOrWhiteSpace(InnTextBox.Text)) return;
        agentPresenter.Inn = InnTextBox.Text;

        if (string.IsNullOrWhiteSpace(KppTextBox.Text)) return;
        agentPresenter.Kpp = KppTextBox.Text;

        if (string.IsNullOrWhiteSpace(DirectorNameTextBox.Text)) return;
        agentPresenter.DirectorName = DirectorNameTextBox.Text;

        if (string.IsNullOrWhiteSpace(PhoneNumberTextBox.Text)) return;
        agentPresenter.Phone = PhoneNumberTextBox.Text;

        if (string.IsNullOrWhiteSpace(EmailTextBox.Text)) return;
        agentPresenter.Email = EmailTextBox.Text;

        if (TypeAgentAddCombobox.SelectedItem is AgentType selectedAgentType)
        {
            agentPresenter.AgentTypeId = selectedAgentType.Id;
        }

        if (!string.IsNullOrEmpty(PathToImage))
        {
            agentPresenter.Logo = PathToImage;
        }

        ctx.Agents.Update(agentPresenter);
        await ctx.SaveChangesAsync();
        Close(agentPresenter);
    }

    private async Task<Bitmap?> SelectAndSaveImage()
    {
        var showDialog = StorageProvider.OpenFilePickerAsync(
            options: new Avalonia.Platform.Storage.FilePickerOpenOptions()
            {
                Title = "Select an image",
                FileTypeFilter = new[] { FilePickerFileTypes.ImageAll }
            });
        var storageFile = await showDialog;
        try
        {
            var bmp = new Bitmap(storageFile.First().TryGetLocalPath());
            string shortGuid = Guid.NewGuid().ToString("N").Substring(0, 8);
            string path = $"/Users/feitanportor/dev/C#/demko_v/demko_v/bin/Debug/net8.0/agents/{shortGuid}.jpg";
            bmp.Save(path);
            PathToImage = $"agents/{shortGuid}.jpg";
            return bmp;
        }
        catch
        {
            return null;
        }
    }

    private async void SelectImage(object? sender, RoutedEventArgs e)
    {
        AgentImage.Source = await SelectAndSaveImage();
    }
    
    private void TypeAgentAddCombobox_OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        using var ctx = new DemoAgentsContext();
        
        if (TypeAgentAddCombobox.SelectedItem is string selectedTitle)
        {
            var agentType = ctx.AgentTypes.FirstOrDefault(t => t.Title == selectedTitle);
            if (agentType != null)
            {
                agentPresenter.AgentTypeId = agentType.Id;
            }
        }
    }

    private void Otrisovka()
    {
        using var ctx = new DemoAgentsContext();
        
        TitleTextBox.Text = agentPresenter.Title;
        PriorityTextBox.Text = agentPresenter.Priority.ToString();
        AddressTextBox.Text = agentPresenter.Address;
        InnTextBox.Text = agentPresenter.Inn;
        KppTextBox.Text = agentPresenter.Kpp;
        DirectorNameTextBox.Text = agentPresenter.DirectorName;
        PhoneNumberTextBox.Text = agentPresenter.Phone;
        EmailTextBox.Text = agentPresenter.Email;
        
        if (!string.IsNullOrEmpty(agentPresenter.Logo))
        {
            string imagePath = Path.Combine(Environment.CurrentDirectory, agentPresenter.Logo);
            
            if (File.Exists(imagePath))
            {
                var bitmap = new Bitmap(imagePath);
                AgentImage.Source = bitmap;
                PathToImage = agentPresenter.Logo;
            }
        }
        
        if (agentPresenter.AgentTypeId != 0)
        {
            var selectedType = ctx.AgentTypes.FirstOrDefault(t => t.Id == agentPresenter.AgentTypeId)?.Title;
            if (selectedType != null)
            {
                TypeAgentAddCombobox.SelectedItem = selectedType;
            }
        }
    }
}
