<template>
    <div class="transaction-statistics-chart">
        <div class="chart-header mb-3">
            <h6 class="mb-0">
                <i class="fas fa-chart-pie me-2"></i>
                Thống kê theo loại giao dịch
            </h6>
        </div>
        
        <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="!statistics || !statistics.TypeStatistics || statistics.TypeStatistics.length === 0" 
             class="text-center py-3 text-muted">
            <i class="fas fa-chart-pie fa-2x mb-2"></i>
            <p class="mb-0">Không có dữ liệu thống kê</p>
        </div>
        
        <div v-else>
            <!-- Pie Chart -->
            <div class="chart-container mb-4">
                <canvas ref="pieChart" width="300" height="300"></canvas>
            </div>
            
            <!-- Statistics List -->
            <div class="statistics-list">
                <div v-for="stat in statistics.TypeStatistics" :key="stat.TransactionType" 
                     class="stat-item d-flex justify-content-between align-items-center mb-2 p-2 rounded"
                     :style="{ backgroundColor: getStatColor(stat.TransactionType) + '20' }">
                    <div class="d-flex align-items-center">
                        <div class="stat-color-indicator me-2" 
                             :style="{ backgroundColor: getStatColor(stat.TransactionType) }"></div>
                        <div>
                            <div class="fw-medium">{{ stat.TransactionTypeName }}</div>
                            <small class="text-muted">{{ stat.TransactionCount }} giao dịch</small>
                        </div>
                    </div>
                    <div class="text-end">
                        <div class="fw-bold">{{ formatCurrency(stat.TotalAmount) }}</div>
                        <small class="text-muted">{{ stat.Percentage.toFixed(1) }}%</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import { formatCurrency } from '@/infrastructure/utilities/currencyHelper';

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

const pieChart = ref(null);

// Color palette for different transaction types
const colorPalette = [
    '#007bff', '#28a745', '#ffc107', '#dc3545', '#6f42c1',
    '#20c997', '#fd7e14', '#e83e8c', '#6c757d', '#17a2b8'
];

const getStatColor = (transactionType) => {
    const colorMap = {
        '1': '#007bff',  // Cước vận chuyển
        '2': '#28a745',  // Thu hộ COD
        '3': '#ffc107',  // Chi phí nhiên liệu
        '4': '#dc3545',  // Lương
        '5': '#6f42c1',  // Chuyển khoản
        '6': '#20c997',  // Nạp tiền
        '7': '#fd7e14',  // Rút tiền
        '8': '#e83e8c',  // Hoàn tiền
        '9': '#6c757d',  // Phạt
        '10': '#17a2b8'  // Thưởng
    };
    return colorMap[transactionType] || colorPalette[0];
};

const drawPieChart = () => {
    if (!pieChart.value || !props.statistics?.TypeStatistics) return;
    
    const ctx = pieChart.value.getContext('2d');
    const data = props.statistics.TypeStatistics;
    
    // Clear canvas
    ctx.clearRect(0, 0, pieChart.value.width, pieChart.value.height);
    
    if (data.length === 0) return;
    
    const centerX = pieChart.value.width / 2;
    const centerY = pieChart.value.height / 2;
    const radius = Math.min(centerX, centerY) - 20;
    
    let currentAngle = -Math.PI / 2; // Start from top
    
    data.forEach((stat, index) => {
        const sliceAngle = (stat.Percentage / 100) * 2 * Math.PI;
        const color = getStatColor(stat.TransactionType);
        
        // Draw slice
        ctx.beginPath();
        ctx.moveTo(centerX, centerY);
        ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle);
        ctx.closePath();
        ctx.fillStyle = color;
        ctx.fill();
        
        // Draw border
        ctx.strokeStyle = '#fff';
        ctx.lineWidth = 2;
        ctx.stroke();
        
        // Draw label
        const labelAngle = currentAngle + sliceAngle / 2;
        const labelX = centerX + Math.cos(labelAngle) * (radius + 30);
        const labelY = centerY + Math.sin(labelAngle) * (radius + 30);
        
        ctx.fillStyle = '#333';
        ctx.font = '12px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(`${stat.Percentage.toFixed(1)}%`, labelX, labelY);
        
        currentAngle += sliceAngle;
    });
    
    // Draw center circle
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius * 0.4, 0, 2 * Math.PI);
    ctx.fillStyle = '#fff';
    ctx.fill();
    ctx.strokeStyle = '#ddd';
    ctx.lineWidth = 2;
    ctx.stroke();
    
    // Draw total in center
    ctx.fillStyle = '#333';
    ctx.font = 'bold 14px Arial';
    ctx.textAlign = 'center';
    ctx.fillText('Tổng', centerX, centerY - 5);
    ctx.font = '12px Arial';
    ctx.fillText(formatCurrency(props.statistics.TotalIncome + props.statistics.TotalOutcome), centerX, centerY + 10);
};

// Watch for statistics changes
watch(() => props.statistics, () => {
    nextTick(() => {
        drawPieChart();
    });
}, { deep: true });

onMounted(() => {
    nextTick(() => {
        drawPieChart();
    });
});
</script>

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

.chart-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
}

.stat-item {
    transition: all 0.2s ease;
    border: 1px solid transparent;
}

.stat-item:hover {
    border-color: #dee2e6;
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.stat-color-indicator {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    flex-shrink: 0;
}

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

@media (max-width: 768px) {
    .chart-container {
        min-height: 250px;
    }
    
    .stat-item {
        flex-direction: column;
        align-items: flex-start !important;
        text-align: left;
    }
    
    .stat-item .text-end {
        text-align: left !important;
        margin-top: 0.5rem;
    }
}
</style>
