using FrymasterBadgeApp.Services;
using Microsoft.Data.SqlClient;

namespace FrymasterBadgeApp;

public partial class CompanyPage : ContentPage
{
    private readonly SqlService _db;
    private Dictionary<string, object>? _selectedCompany;
    private string _tempLogoPath = "";

    public CompanyPage(SqlService db)
    {
        InitializeComponent();
        _db = db;
        LoadCompanies();
    }

    private string GetLogoDirectory() =>
        Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
            "FrymasterBadgeApp",
            "Logos"
        );

    private void LoadCompanies() =>
        CompanyList.ItemsSource = _db.Query("SELECT * FROM Companies", null);

    private void OnCompanySelected(object sender, SelectedItemChangedEventArgs e)
    {
        _selectedCompany = e.SelectedItem as Dictionary<string, object>;
        if (_selectedCompany == null)
            return;

        CompName.Text = _selectedCompany["Name"]?.ToString();
        CompAddress.Text = _selectedCompany["Address"]?.ToString();
        _tempLogoPath = _selectedCompany.GetValueOrDefault("logo")?.ToString() ?? "";
        LogoPreview.Source = File.Exists(_tempLogoPath)
            ? ImageSource.FromFile(_tempLogoPath)
            : null;
    }

    private async void OnSelectLogoClicked(object sender, EventArgs e)
    {
        var result = await FilePicker.Default.PickAsync(
            new PickOptions { PickerTitle = "Select Logo", FileTypes = FilePickerFileType.Images }
        );
        if (result != null)
        {
            _tempLogoPath = result.FullPath;
            LogoPreview.Source = ImageSource.FromFile(_tempLogoPath);
        }
    }

    private void OnSaveClicked(object sender, EventArgs e)
    {
        string logoDir = GetLogoDirectory();
        if (!Directory.Exists(logoDir))
            Directory.CreateDirectory(logoDir);

        string finalLogoPath = _tempLogoPath;
        if (!string.IsNullOrEmpty(_tempLogoPath) && !_tempLogoPath.Contains(logoDir))
        {
            string dest = Path.Combine(logoDir, Path.GetFileName(_tempLogoPath));
            File.Copy(_tempLogoPath, dest, true);
            finalLogoPath = dest;
        }

        if (_selectedCompany == null)
        {
            _db.Execute(
                "INSERT INTO Companies (Name, Address, logo) VALUES (@n, @a, @l)",
                new SqlParameter[]
                {
                    new("@n", CompName.Text),
                    new("@a", CompAddress.Text),
                    new("@l", finalLogoPath),
                }
            );
        }
        else
        {
            _db.Execute(
                "UPDATE Companies SET Name=@n, Address=@a, logo=@l WHERE ID=@id",
                new SqlParameter[]
                {
                    new("@n", CompName.Text),
                    new("@a", CompAddress.Text),
                    new("@l", finalLogoPath),
                    new("@id", _selectedCompany["ID"]),
                }
            );
        }
        LoadCompanies();
    }

    private void OnAddNewClicked(object sender, EventArgs e)
    {
        _selectedCompany = null;
        CompName.Text = CompAddress.Text = "";
        LogoPreview.Source = null;
    }

    private void OnDeleteClicked(
        object sender,
        EventArgs e
    ) { /* Delete logic */
    }
}
