<script lang="ts">
  import { fade } from "svelte/transition";
  import ModalEstatico from "./ModalEstatico.svelte";
  import ModificarPropiedadForm from "./modificarPropiedadForm.svelte";

  let { id, ubicacion, tipo, letra, piso,canthabitaciones, servicios, btnbaja = "Baja", monto, iddivisa = 0 }  = $props();

	import { urlG } from "../stores/urlStore";
    import ModalPublicarPropiedadParaVenta from "./ModalPublicarPropiedadParaVenta.svelte";
    import type { setVenta } from "../types";

  let modal: boolean = $state(false);
  let modalpayload: string = $state("");
  
  let modificar: boolean = $state(false);
  let showPublicarVenta: boolean = $state(false);

  function setmod(){
    modificar = !modificar;
  }
  
  async function BajaPropiedad(){
    modal = false;
    try {
      const responce = await fetch(String($urlG)+"/api/propiedad?id="+id, {
        method: "DELETE",
        headers:{
          'Auth' : String(sessionStorage.getItem("token")),
          'Email' : String(localStorage.getItem("email"))
        }, 
        });
      
        const json = await responce.json();
        modalpayload = json.message;
        modal = true;
        window.location.reload();      
    }catch (e){
      console.error(e);
    }
  }

  function setventa() {
    showPublicarVenta = true;
  }
  async function sendMod(data:setVenta) {
    data.idpropiedad = id;
    try {
      const responce = await fetch(String($urlG)+"/api/propiedad/setPropiedadAVenta", {
        method: "PUT",
        headers:{
          'Auth' : String(sessionStorage.getItem("token")),
          'Content-Type': "application/json",
        }, 
        body: JSON.stringify(data),
        });
        if(responce.ok){
          window.location.reload();      
        }

        const json = await responce.json();
        modalpayload = json.message;
        modal = true;
    }catch (e){
      console.error(e);
    }
  }
</script>

<tr in:fade>
  <td>{id}</td>
  <td>{ubicacion}</td>
  <td>{canthabitaciones}</td>
  <td>{letra}</td>
  <td>{piso}</td>  	
 	<td>{tipo}</td>
  <td>{servicios}</td>
  <td>
    {#if iddivisa == 0}
    AR$
    {:else}
    US$
    {/if}
  </td>
  <td>{monto}</td>
  <td class="d-flex justify-content-between gap-2">
    <button class="btn btn-secondary btn-sm" onclick={()=> setmod()}>Modificar</button>
    <button class="btn btn-secondary btn-sm" onclick={()=> setventa()}>Publicar a venta</button>
    <button class="btn btn-danger btn-sm" onclick={() => BajaPropiedad()}>{btnbaja}</button>
  </td>
</tr>
{#if modal}
	<ModalEstatico payload={modalpayload}/>
{/if}
{#if modificar}
  <tr transition:fade={{duration:100}}> 
    <td colspan="10">
      <ModificarPropiedadForm {id} {ubicacion} {canthabitaciones} {letra} {piso} {tipo} {servicios} {monto} {iddivisa}/>
    </td>
  </tr>
{/if}

{#if showPublicarVenta}
  <ModalPublicarPropiedadParaVenta onClose={()=>!!(showPublicarVenta = false)} onConfirm={sendMod}/>
{/if}