<template>
<div class="page">
<h2>Estimates</h2>

<section class="form inputs">
<h3>Default Fees</h3>

<div
	v-for="(fee, indx) in fees"
	:key="fee.name + indx" class="fee"
>
	<label @click="() => edit = fee">
	${{fee.amount/100}}{{ fee.perc ? ` ${fee.perc}%` : ''}} - {{fee.name}}<br>
	{{fee.type}}
	</label>
	<img width="21" height="21" src="/assets/image/icon/x-red.svg"
	@click="() => remove(fee)">
</div>
<button @click="() => edit = {}">New Fee</button>
</section>

<fee-dialog v-if="edit"
	:heading="'Fee'"
	:initial="edit"
	:price="0"
	@close="() => edit = null"
	@save="newFee"
/>



<section class="inputs estimates">
<h3>Saved Estimates</h3>

<div class="entry" v-for="e in estimates" v-if="!estimate"
@click="() => estimate = e" key="e.id">
<span>
    {{e.id}} - {{e.property}} - ${{(e.price/100).toLocaleString()}}
</span>
</div>

<div class="details" v-if="estimate">
<label>
#{{estimate.id}} - 
{{estimate.transaction}} - 
{{estimate.property}} - 
${{(estimate.price / 100).toLocaleString()}}
</label>
<label>Borrowers: {{estimate.borrower.num}}</label>
<label>Credit: {{estimate.borrower.credit}}</label>
<label>Income: {{(estimate.borrower.income/100).toLocaleString()}}</label>

<div v-for="(l, i) in estimate.loans" class="details">
<h4>{{l.title}}</h4>
<label>{{l.type.name}}</label>
<label>Total monthly: ${{format(estimate.results[i].totalMonthly)}}</label>
<label>Cash to close: ${{format(estimate.results[i].cashToClose)}}</label>
</div>

<button @click="() => estimate = null">Cancel</button>
</div>

</section>

</div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import FeeDialog from "./fee-dialog.vue"
import { format } from "../helpers.js"

const props = defineProps(['user', 'fees', 'token'])
const emit = defineEmits(['addFeeTemp', 'removeFeeTemp'])
let edit = ref(null)
let estimates = ref([])
let estimate = ref()

function newFee(fee, isDebit) {
    if (!isDebit) {
        fee.amount = -1 * fee.amount || 0
        fee.perc = -1 * fee.perc || 0
    }
    
    fetch(`/api/fee`,
		{method: 'POST',
		    body: JSON.stringify(fee),
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
	}).then(resp => {
		if (resp.ok && resp.status == 200) {
		    resp.json().then(r => emit('addFeeTemp', r))
		} else {
		    // resp.text().then(t => this.errors = [t])
		    // window.location.hash = 'new'
		    resp.text().then(t => console.log(t))
	    }
	})
	edit.value = null
}

function newType() {

}

function remove(fee) {
    fetch(`/api/fee`,
		{method: 'DELETE',
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
    	    body: JSON.stringify(fee)
	}).then(response => {
		if (response.ok) { emit('removeFeeTemp', fee) } else {
		    response.text().then(t => console.log(t))
		}
	})
}

function getEstimates() {
	fetch(`/api/estimates`,
		{method: 'GET',
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
	}).then(response => {
		if (response.ok) { return response.json() } else {
		    response.text().then(t => console.log(t))
		}
	}).then (result => {
		if (!result || !result.length) return // Exit if token is invalid or no fees are saved
		estimates.value = result
		// console.log(result)
	})
}

function summarize() {
	fetch(`/api/estimate/summarize`,
		{method: 'POST',
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
    		body: JSON.stringify(estimate.value),
	}).then(response => {
		if (response.ok) { return response.json() } else {
		    response.text().then(t => console.log(t))
		}
	}).then(result => {
		if (!result || !result.length) return // Exit if token is invalid or no fees are saved
		console.log('done', result)
	})

}

onMounted(() => {
    getEstimates()
})
</script>
