<script lang="ts">
    import { onMount } from "svelte";
    import NavBarAutocompletable from "../Componentes/NavBarAutocompletable.svelte";
    import type { VentasDto } from "../types";
    import ModalEstatico from "../Componentes/ModalEstatico.svelte";
    import { urlG } from "../stores/urlStore";
    import Ventas from "./Ventas.svelte";
    import { navigate } from "svelte-routing";

    let token:string = sessionStorage.getItem("token")||"";
    let modaldata:string = $state("");

    let ventas:VentasDto[] = $state([]);

    onMount(()=>{
        obtenerVentas();
    });

    async function obtenerVentas() {
        try{
            const r = await fetch($urlG+"/api/ventas", {
                method: "GET",
                headers: {
                    "Auth": token
                }
            });
            let data = await r.json();
            if (!r.ok){
                modaldata = data;
                return;
            }
            ventas = data;
        }catch{
            modaldata = "Fallo al hacer la request";
        }
    }

</script>

<NavBarAutocompletable/>

{#if modaldata}
    <ModalEstatico payload={modaldata} close={()=> !!(modaldata = "")} />
{/if}

<div class="container-fluid mt-3">
    <div class="row">
        {#each ventas as venta (venta.id)}
            <div class="col-md-6 mb-4">
                <div class="card">
                    <div class="card-header">
                        <h5>{venta.nombreVendedor} → {venta.nombreComprador}</h5>
                    </div>
                    <div class="card-body">
                    <p class="card-text">
                        <strong>Monto:</strong> {venta.monto} {venta.divisa}<br>
                        <strong>Ubicación:</strong> {venta.ubicacion}<br>
                        <strong>Estado:</strong> {venta.estado}
                    </p>
                    </div>
                    <div class="card-footer d-flex justify-content-center">
                        <button class="btn btn-secondary" onclick={()=>navigate("/Ventas?idventa="+venta.id)}>Ver</button>
                    </div>
                </div>
            </div>
        {/each}
    </div>
</div>

<style>
    .card {
        border-radius: 10px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }
</style>