using MauiAppStock.Models;
using MauiAppStock.Data;

namespace MauiAppStock.Views;

public partial class MouvementStockHistoryPage : ContentPage
{
    private List<MouvementStock> allMouvements;
    private List<Piece> pieces;

    public MouvementStockHistoryPage()
    {
        InitializeComponent();
        LoadData();
    }

    private async void LoadData()
    {
        try
        {
            // Load all pieces to get their names
            pieces = await Database.GetPiecesAsync();
            
            // Load all movements
            allMouvements = await Database.GetMouvementsStockAsync();
            
            // Add piece names to movements
            foreach (var mouvement in allMouvements)
            {
                var piece = pieces.FirstOrDefault(p => p.Id == mouvement.PieceId);
                if (piece != null)
                {
                    mouvement.NomPiece = piece.Nom;
                }
            }
            
            // Display all movements initially
            MouvementsCollection.ItemsSource = allMouvements;
        }
        catch (Exception ex)
        {
            await DisplayAlert("Erreur", "Impossible de charger l'historique: " + ex.Message, "OK");
        }
    }

    private void OnFilterChanged(object sender, EventArgs e)
    {
        if (allMouvements == null) return;

        var selectedIndex = FilterPicker.SelectedIndex;
        var filteredMouvements = selectedIndex switch
        {
            1 => allMouvements.Where(m => m.Type == TypeMouvement.EntreeStock).ToList(),
            2 => allMouvements.Where(m => m.Type == TypeMouvement.SortieReparation).ToList(),
            _ => allMouvements
        };

        MouvementsCollection.ItemsSource = filteredMouvements;
    }
} 