<template>
<div>
    <ul class="nav nav-tabs mb-3">
        <li class="nav-item" v-for="option in chartOptions" :key="option.key">
            <button
                class="nav-link"
                :class="{ active: selectedChart === option.key }"
                @click="selectedChart = option.key; fetchChart()">
                {{ option.label }}
            </button>
        </li>
    </ul>

    <div class="d-flex gap-3 justify-content-end align-items-center">
        <label for="range" class="form-label">Select Time Range:</label>
        <select id="range" v-model="selectedRange" @change="fetchChart" class="form-select">
            <option value="6m">Last 6 months</option>
            <option value="12m">Last 12 months</option>
            <option value="2y">Last 2 years</option>
            <option value="5y">Last 5 years</option>
            <option value="all">All time</option>
        </select>
    </div>

    <canvas ref="canvas"></canvas>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { Chart, registerables } from 'chart.js';

// Register all necessary chart types and plugins
Chart.register(...registerables);

const canvas = ref(null);
let chartInstance = null;

const selectedRange = ref('6m');
const selectedChart = ref('county');

const chartOptions = [
    { key: 'county', label: 'Averages by County', routeName: 'averages-price-by-county' },
    { key: 'zip', label: 'Zip Code', routeName: 'averages-price-by-zip' },
    { key: 'subtype', label: 'Property Sub-Type', routeName: 'averages-price-by-subtype' },
    { key: 'city', label: 'City', routeName: 'averages-price-by-city' },
];

const fetchChart = async () => {
    const option = chartOptions.find(opt => opt.key === selectedChart.value);

    const res = await fetch(route(option.routeName, { range: selectedRange.value }));
    const chartConfig = await res.json();
    if (chartInstance) {
        chartInstance.destroy()
    }
    chartInstance = new Chart(canvas.value, chartConfig);
};

onMounted(fetchChart);
</script>

<style lang="scss" scoped>
canvas {
    max-width: 100%;
}
</style>
