<template>
<div>
<section class="form inputs">
<h3>Loan</h3>
<label>Name</label>
<input :value="loan.title" required
@input="(e) => $emit('update:name', stripLetters(e))">
<button @click="() => $emit('del')">Delete</button>
</section>

<section class="form inputs">

<div class="hint">
	<img class="icon" src="/assets/image/icon/question-circle.svg" alt="">
	<div class="tooltip">
		<p>Assumes borrower is not self employed, not bankrupt in the past 7
		years, a citizen, and intends to occupy the property.</p>
	</div>
</div>

<h3>Borrower</h3>
<label>Number of Borrowers</label>
<input :value="estimate.borrower.num"
@input="(e) => $emit('update:borrowerNum', stripInt(e))">
<label>Credit Score</label>
<input :value="estimate.borrower.credit"
@input="(e) => $emit('update:borrowerCredit', stripInt(e))">
<label>Monthly Income ($)</label>
<input :value="estimate.borrower.income/100"
@input="(e) => $emit('update:borrowerIncome', strip(e))">

</section>

<section class="radios form">
<h3>Transaction Type</h3>
<input selected type="radio" name="transaction_type"
:selected="estimate.transaction == 'Purchase'"
:value="estimate.transaction"
@input="() => $emit('update:transaction', 'Purchase')"
>
<label>Purchase</label>
<input type="radio" name="transaction_type"
:selected="estimate.transaction == 'Refinance'"
:value="estimate.transaction"
@input="() => $emit('update:transaction', 'Refinance')"
>
<label>Refinance</label>
</section>

<section class="radios form">
<h3>Occupancy</h3>
<input type="radio" name="occupancy"
:value="estimate.occupancy"
@input="() => $emit('update:occupancy', 'Primary')"
>
<label>Primary</label>
<input type="radio" name="occupancy"
:value="estimate.occupancy"
@input="() => $emit('update:occupancy', 'Secondary')"
>
<label>Secondary</label>
<input type="radio" name="occupancy"
:value="estimate.occupancy"
@input="() => $emit('update:occupancy', 'Residential')"
>
<label>Residential</label>
</section>

<section class="form inputs">
<h3>Property Details</h3>
<label>Price ($)</label>
<input :value="estimate.price/100" @input="(e) => $emit('update:price', strip(e))">
<label>Type</label>
<select id="" name=""
    :value="estimate.property"
    @change="(e) => $emit('update:property', e.target.value)">
	<option value="Single Attached">Single Family Attached</option>
	<option value="Single Detached">Single Family Detached</option>
	<option value="Condo Lo-rise">Lo-rise (4 stories or less)</option>
	<option value="Condo Hi-rise">Hi-rise (over 4 stories)</option>
</select>
</section>

<section class="radios form">
<h3>Loan Type</h3>
<input type="radio"
    name="loan_type"
    :checked="loan.type.id == 1"
    value="1"
    @change="(e) => $emit('update:loanType', 1)"
>
<label>Conventional</label>
<input type="radio"
    name="loan_type"
    value="2"
    :checked="loan.type.id == 2"
    @change="(e) => $emit('update:loanType', 2)">
<label>FHA</label>
<input type="radio"
    name="loan_type"
    value="3"
    :checked="loan.type.id == 3"
    @change="(e) => $emit('update:loanType', 3)">
<label>VA</label>
<input type="radio"
    name="loan_type"
    value="4"
    :checked="loan.type.id == 4"
    @change="(e) => $emit('update:loanType', 4)">
<label>USDA</label>
</section>

<section class="form inputs">
<h3>Loan Details</h3>
<label>Loan Term (years)</label>
<input :value="loan.term"
@input="(e) => $emit('update:term', stripInt(e))">

<label>Loan Program</label>
<select id="" name=""
    :value="loan.program"
    @change="(e) => $emit('update:program', e.target.value)">
	<option value="none">None</option>
</select>

<label>Loan to Value (%)</label>
<input :value="loan.ltv" @input="(e) => $emit('update:ltv', e)">
<label>Loan Amount ($)</label>
<input :value="loan.amount / 100"
@input="(e) => $emit('update:amount', e)">
<label>Housing Expense DTI (%) - Optional</label>
<input :value="loan.housingDti"
@input="(e) => $emit('update:housingDti', e)">
<label>Total DTI (%) - Optional</label>
<input :value="loan.dti" @input="(e) => $emit('update:dti', e)">
<label>Home Owner's Association ($/month)</label>
<input :value="loan.hoi / 100"
@input="(e) => { $emit('update:hoi', strip(e)) }">

<label>Interest Rate (%)</label>
<input :value="loan.interest"
@input="(e) => { $emit('update:interest', stripPerc(e)) }">
<label>Days of Interest</label>
<input :value="loan.interestDays"
@input="(e) => $emit('update:interestDays', stripInt(e))">

<label>Hazard Insurance Escrow (months)</label>
<input :value="loan.hazardEscrow"
@input="(e) => { $emit('update:hazardEscrow', stripInt(e)) }">
<label>Hazard Insurance ($/month)</label>
<input :value="loan.hazard / 100"
@input="(e) => $emit('update:hazard', strip(e))">

<label>Real Estate Tax Escrow (months)</label>
<input :value="loan.taxEscrow"
@input="e => $emit('update:taxEscrow', stripInt(e))">
<label>Real Estate Tax ($/month)</label>
<input :value="loan.tax/100"
@input="(e) => $emit('update:tax', strip(e))">
</section>

<section class="form inputs">
<h3>Fees</h3>
<div v-for="(fee, indx) in loan.fees"
:key="fee.name + indx" class="fee" :class="fee.required && 'required'"
>
	<label>
	${{(fee.amount / 100).toFixed(2)}}
	{{ fee.perc ? ` ${fee.perc}%` : ''}} - {{fee.name}}<br>
	{{fee.type}}
	</label>
	<img v-if="!fee.required" width="21" height="21" src="/assets/image/icon/x-red.svg"
	@click="() => loan.fees.splice(indx, 1)">
</div>
<button @click="resetFees">Reset</button>
<button @click="createFee">New</button>
</section>

<fee-dialog v-if="newFee"
	:heading="'New Fee'"
	:initial="{}"
	:price="estimate.price"
	@close="() => newFee = null"
	@save="addFee"
/>

<section class="form inputs mi">
<h3>Mortgage Insurance</h3>
<div class="row">
    <input checked type="radio" name="mi"/><label>Manual %</label>
    <input type="checkbox" :checked="loan.mi.monthly"
    @change="e => $emit('toggle:manualMIMonthly')" />
    <label>monthly</label>
</div>
<div class="row">
<input :value="loan.mi.rate"
@input="e => $emit('update:manualMI', stripPerc(e))" />
</div>
</section>

<section class="form inputs">

	<button @click="validate">Continue</button>

	<ul class="errors">
	<li v-for="e in errors">{{e}}</li>
	</ul>

</section>

</div>
</template>

<script>
import FeeDialog from "../fee-dialog.vue"
import { stripLetters, strip, stripInt, stripPerc } from "../../helpers.js" 

const newFee = {
	name: '', type: '', amount: 0, perc: 0
 }

// Setup this.newFee for the creation dialog
function createFee() {
	this.newFee = Object.assign({}, newFee)
}

// If valid, add the current this.newFee to the array of fees and reset
// this.newFee to null
function addFee(fee, isDebit) {

	if (!isDebit) fee.amount = fee.amount * -1
	this.loan.fees.push(fee)
	this.newFee = null
}

function validate() {
    fetch(`/api/estimate/validate`,
		{method: 'POST',
		    body: JSON.stringify(this.estimate),
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${this.token}`,
    		},
	}).then(resp => {
		if (resp.ok && resp.status == 200) {
		    this.errors = []
		    this.$emit('continue')
		    return
		} else {
		    resp.text().then(t => this.errors = [t])
	    }
	})

}

function generate() {
    const errors = this.validate()
    if (errors.length) {
        this.errors = errors
        return
    }
}

export default {
	components: { FeeDialog },
	methods: {
		strip, stripInt, stripLetters, stripPerc, createFee, addFee, validate,
		generate
	},
	props: ['estimate', 'loan', 'token'],
	// Loan updates assume the currently selected loan is being modified, and
	// $emit has no need to clarify.
	emits: [
	    'del',
	    'update:name',
	    'update:borrowerNum',
	    'update:borrowerCredit',
	    'update:borrowerIncome',
	    'update:transaction', 
	    'update:occupancy', 
	    'update:price',
	    'update:property',
	    
	    // Loan specific emits
	    'update:loanType',
	    'update:term',
	    'update:program',
	    'update:ltv',
	    'update:amount',
	    'update:housingDti',
	    'update:dti',
	    'update:hoi',
	    'update:interest',
	    'update:interestDays',
	    'update:hazardEscrow',
	    'update:hazard',
	    'update:taxEscrow',
	    'update:tax',
	    'update:manualMI',
	    'toggle:manualMIMonthly',
	    
	    'continue'
	],
	data() {
		return {
				newFee: null,
				errors: [],
				hash: window.location.hash
			}
	},
	created() {
	}
}
</script>