using MauiAppStock.Models;
using MauiAppStock.Data;

namespace MauiAppStock.Views;

public partial class MouvementStockPage : ContentPage
{
    private List<Piece> pieces;
    private Piece selectedPiece;

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

    private async void LoadData()
    {
        try
        {
            pieces = await Database.GetPiecesAsync();
            PiecePicker.ItemsSource = pieces;
        }
        catch (Exception ex)
        {
            await DisplayAlert("Erreur", "Impossible de charger les données: " + ex.Message, "OK");
        }
    }

    private void OnPieceSelected(object sender, EventArgs e)
    {
        if (PiecePicker.SelectedItem != null)
        {
            selectedPiece = (Piece)PiecePicker.SelectedItem;
        }
    }

    private async void OnViewHistoryClicked(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new MouvementStockHistoryPage());
    }

    private async void OnSaveClicked(object sender, EventArgs e)
    {
        if (selectedPiece == null)
        {
            await DisplayAlert("Erreur", "Veuillez sélectionner une pièce", "OK");
            return;
        }

        if (!int.TryParse(QuantiteEntry.Text, out int quantite) || quantite <= 0)
        {
            await DisplayAlert("Erreur", "Veuillez entrer une quantité valide", "OK");
            return;
        }

        try
        {
            // Create new stock movement
            var mouvement = new MouvementStock
            {
                PieceId = selectedPiece.Id,
                DateMouvement = DateTime.Now,
                Type = TypeMouvementPicker.SelectedIndex == 0 ? TypeMouvement.EntreeStock : TypeMouvement.SortieReparation,
                Quantite = quantite,
                Commentaire = CommentaireEditor.Text
            };

            // Update piece stock
            if (TypeMouvementPicker.SelectedIndex == 0)
            {
                selectedPiece.Stock += quantite;
            }
            else
            {
                if (selectedPiece.Stock < quantite)
                {
                    await DisplayAlert("Erreur", "Stock insuffisant", "OK");
                    return;
                }
                selectedPiece.Stock -= quantite;
            }

            // Save changes using Database class
            await Database.AddMouvementStockAsync(mouvement);
            await Database.UpdatePieceAsync(selectedPiece);

            await DisplayAlert("Succès", "Mouvement de stock enregistré", "OK");
            await Navigation.PopAsync();
        }
        catch (Exception ex)
        {
            await DisplayAlert("Erreur", "Impossible d'enregistrer le mouvement: " + ex.Message, "OK");
        }
    }

    private async void OnCancelClicked(object sender, EventArgs e)
    {
        await Navigation.PopAsync();
    }
} 