<template>
    <div class="balance-history-chart">
        <div v-if="loading" class="text-center py-3">
            <div class="spinner-border spinner-border-sm text-primary" role="status">
                <span class="visually-hidden">Đang tải...</span>
            </div>
        </div>

        <div v-else-if="!balanceHistory || !balanceHistory.DailyBalanceHistory || balanceHistory.DailyBalanceHistory.length === 0"
            class="text-center py-3 text-muted">
            <i class="fas fa-chart-line fa-2x mb-2"></i>
            <p class="mb-0">Không có dữ liệu lịch sử</p>
        </div>

        <div v-else>
            <!-- Chart Container -->
            <div class="chart-container">
                <v-chart ref="balanceChart" :option="chartOption" style="height: 300px;"></v-chart>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, computed } from 'vue';
import VChart from 'vue-echarts';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart } from 'echarts/charts';
import {
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent
} from 'echarts/components';

// Đăng ký ECharts components
use([
    CanvasRenderer,
    LineChart,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent
]);

const props = defineProps({
    balanceHistory: {
        type: Object,
        default: null
    },
    loading: {
        type: Boolean,
        default: false
    }
});

const balanceChart = ref(null);

const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('vi-VN');
};

const getChangeClass = (change) => {
    return change >= 0 ? 'text-success' : 'text-danger';
};

// Computed property for chart option (tham khảo cấu hình từ orderRevenue.vue)
const chartOption = computed(() => {
    if (!props.balanceHistory?.DailyBalanceHistory || props.balanceHistory.DailyBalanceHistory.length === 0) {
        return {};
    }

    const data = props.balanceHistory.DailyBalanceHistory;
    const labels = data.map(item => formatDate(item.Date));
    const balanceData = data.map(item => item.EndOfDayBalance);
    const changeData = data.map(item => item.DailyChange);

    return {
        title: {
            text: 'Biến động số dư theo thời gian',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'cross' },
            formatter: function (params) {
                let result = params[0].name + '<br/>';
                params.forEach(param => {
                    result += param.marker + param.seriesName + ': ' +
                        new Intl.NumberFormat('vi-VN', {
                            style: 'currency',
                            currency: 'VND'
                        }).format(param.value) + '<br/>';
                });
                return result;
            }
        },
        legend: {
            data: ['Số dư cuối ngày', 'Thay đổi hàng ngày'],
            top: '10%'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '20%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: labels
        },
        yAxis: {
            type: 'value',
            min: 0,
            axisLabel: {
                formatter: function (value) {
                    return new Intl.NumberFormat('vi-VN').format(value);
                }
            }
        },
        series: [
            {
                name: 'Số dư cuối ngày',
                type: 'line',
                data: balanceData,
                smooth: true,
                lineStyle: { color: '#28a745' },
                itemStyle: { color: '#28a745' },
                areaStyle: { color: 'rgba(40, 167, 69, 0.1)' }
            },
            {
                name: 'Thay đổi hàng ngày',
                type: 'line',
                data: changeData,
                smooth: true,
                lineStyle: { color: '#17a2b8' },
                itemStyle: { color: '#17a2b8' },
                areaStyle: { color: 'rgba(23, 162, 184, 0.1)' }
            }
        ]
    };
});
</script>

<style scoped>
.balance-history-chart {
    background: #fff;
    border-radius: 0.5rem;
    padding: 1rem;
}

.chart-container {
    position: relative;
    background: #fafafa;
    border-radius: 0.375rem;
    padding: 1rem;
    border: 1px solid #e9ecef;
}

.chart-controls {
    background: #f8f9fa;
    padding: 0.75rem;
    border-radius: 0.375rem;
    border: 1px solid #e9ecef;
}

.chart-legend {
    background: #f8f9fa;
    padding: 1rem;
    border-radius: 0.375rem;
    border: 1px solid #e9ecef;
}

.legend-item {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
}

.legend-color {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    flex-shrink: 0;
}

.chart-header h6 {
    color: #495057;
    font-weight: 600;
}

@media (max-width: 768px) {
    .chart-container {
        padding: 0.5rem;
    }

    .chart-controls .row {
        flex-direction: column;
        gap: 0.5rem;
    }

    .chart-controls .col-md-6 {
        width: 100%;
    }

    .chart-controls .text-end {
        text-align: left !important;
    }

    .chart-legend .row {
        flex-direction: column;
        gap: 1rem;
    }

    .chart-legend .col-4 {
        width: 100%;
    }
}
</style>
