<template>
  <div class="call-log-statistics">
    <div v-if="loading" class="text-center p-4">
      <div class="spinner-border" role="status">
        <span class="visually-hidden">Đang tải thống kê...</span>
      </div>
    </div>
    
    <div v-else class="row g-4">
      <!-- Tổng quan -->
      <div class="col-md-3">
        <div class="card bg-primary text-white h-100">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <h6 class="card-title mb-0">Tổng cuộc gọi</h6>
                <h3 class="mb-0">{{ formatNumber(statistics.totalCalls) }}</h3>
              </div>
              <i class="fas fa-phone fa-2x opacity-75"></i>
            </div>
          </div>
        </div>
      </div>
      
      <div class="col-md-3">
        <div class="card bg-success text-white h-100">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <h6 class="card-title mb-0">Tổng thời lượng</h6>
                <h3 class="mb-0">{{ formatDuration(statistics.totalDuration) }}</h3>
              </div>
              <i class="fas fa-clock fa-2x opacity-75"></i>
            </div>
          </div>
        </div>
      </div>
      
      <div class="col-md-3">
        <div class="card bg-warning text-white h-100">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <h6 class="card-title mb-0">Tổng chi phí</h6>
                <h3 class="mb-0">{{ formatCurrency(statistics.totalCost) }}</h3>
              </div>
              <i class="fas fa-dollar-sign fa-2x opacity-75"></i>
            </div>
          </div>
        </div>
      </div>
      
      <div class="col-md-3">
        <div class="card bg-info text-white h-100">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <h6 class="card-title mb-0">Chi phí TB/cuộc gọi</h6>
                <h3 class="mb-0">{{ formatCurrency(averageCost) }}</h3>
              </div>
              <i class="fas fa-calculator fa-2x opacity-75"></i>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Thống kê theo trạng thái -->
      <div class="col-md-6">
        <div class="card h-100">
          <div class="card-header">
            <h6 class="mb-0">Thống kê theo trạng thái Lead</h6>
          </div>
          <div class="card-body">
            <div v-if="statistics.callsByStatus && statistics.callsByStatus.length > 0">
              <div 
                v-for="item in statistics.callsByStatus" 
                :key="item.status"
                class="d-flex justify-content-between align-items-center mb-3"
              >
                <div class="d-flex align-items-center">
                  <span 
                    class="badge me-2"
                    :class="getStatusBadgeClass(item.status)"
                  >
                    {{ item.status }}
                  </span>
                  <span>{{ formatNumber(item.count) }} cuộc gọi</span>
                </div>
                <div class="progress flex-grow-1 ms-3" style="height: 8px;">
                  <div 
                    class="progress-bar"
                    :class="getStatusProgressClass(item.status)"
                    :style="{ width: getPercentage(item.count, statistics.totalCalls) + '%' }"
                  ></div>
                </div>
                <span class="text-muted ms-2">
                  {{ getPercentage(item.count, statistics.totalCalls) }}%
                </span>
              </div>
            </div>
            <div v-else class="text-center text-muted">
              <i class="fas fa-chart-pie fa-2x mb-2"></i>
              <p>Không có dữ liệu thống kê</p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Thống kê theo loại cuộc gọi -->
      <div class="col-md-6">
        <div class="card h-100">
          <div class="card-header">
            <h6 class="mb-0">Thống kê theo loại cuộc gọi</h6>
          </div>
          <div class="card-body">
            <div v-if="statistics.callsByType && statistics.callsByType.length > 0">
              <div 
                v-for="item in statistics.callsByType" 
                :key="item.type"
                class="d-flex justify-content-between align-items-center mb-3"
              >
                <div class="d-flex align-items-center">
                  <span 
                    class="badge me-2"
                    :class="item.type === 'Inbound' ? 'bg-success' : 'bg-warning'"
                  >
                    {{ item.type === 'Inbound' ? 'Cuộc gọi đến' : 'Cuộc gọi đi' }}
                  </span>
                  <span>{{ formatNumber(item.count) }} cuộc gọi</span>
                </div>
                <div class="progress flex-grow-1 ms-3" style="height: 8px;">
                  <div 
                    class="progress-bar"
                    :class="item.type === 'Inbound' ? 'bg-success' : 'bg-warning'"
                    :style="{ width: getPercentage(item.count, statistics.totalCalls) + '%' }"
                  ></div>
                </div>
                <span class="text-muted ms-2">
                  {{ getPercentage(item.count, statistics.totalCalls) }}%
                </span>
              </div>
            </div>
            <div v-else class="text-center text-muted">
              <i class="fas fa-chart-bar fa-2x mb-2"></i>
              <p>Không có dữ liệu thống kê</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { useToast } from 'vue-toastification';

// Services
import callLogService from "@/services/crm/callLogService";

// Props
const props = defineProps({
  startDate: {
    type: String,
    default: null
  },
  endDate: {
    type: String,
    default: null
  }
});

// Toast instance
const toast = useToast();

// Reactive data
const loading = ref(false);
const statistics = reactive({
  totalCalls: 0,
  totalDuration: 0,
  totalCost: 0,
  callsByStatus: [],
  callsByType: []
});

// Computed properties
const averageCost = computed(() => {
  if (statistics.totalCalls === 0) return 0;
  return statistics.totalCost / statistics.totalCalls;
});

// Watchers
watch(() => props.startDate, () => {
  loadStatistics();
});

watch(() => props.endDate, () => {
  loadStatistics();
});

// Methods
async function loadStatistics() {
  loading.value = true;
  try {
    const result = await callLogService.getStatistics(
      props.startDate, 
      props.endDate
    );
    // Update reactive object properties
    statistics.totalCalls = result.totalCalls || 0;
    statistics.totalDuration = result.totalDuration || 0;
    statistics.totalCost = result.totalCost || 0;
    statistics.callsByStatus = result.callsByStatus || [];
    statistics.callsByType = result.callsByType || [];
  } catch (error) {
    console.error("Lỗi tải thống kê:", error);
    toast.error("Có lỗi xảy ra khi tải thống kê");
  } finally {
    loading.value = false;
  }
}

function formatNumber(number) {
  if (!number) return "0";
  return new Intl.NumberFormat('vi-VN').format(number);
}

function formatDuration(seconds) {
  if (!seconds) return "0h 0m";
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  return `${hours}h ${minutes}m`;
}

function formatCurrency(amount) {
  return callLogService.formatCurrency(amount);
}

function getPercentage(value, total) {
  if (!total) return 0;
  return Math.round((value / total) * 100);
}

function getStatusBadgeClass(status) {
  const classes = {
    'New': 'bg-primary',
    'Assigned': 'bg-warning',
    'Success': 'bg-success',
    'Failed': 'bg-danger'
  };
  return classes[status] || 'bg-secondary';
}

function getStatusProgressClass(status) {
  const classes = {
    'New': 'bg-primary',
    'Assigned': 'bg-warning',
    'Success': 'bg-success',
    'Failed': 'bg-danger'
  };
  return classes[status] || 'bg-secondary';
}

// Lifecycle
onMounted(() => {
  loadStatistics();
});
</script>

<style scoped>
.call-log-statistics .card {
  border: none;
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.progress {
  background-color: #e9ecef;
}

.badge {
  font-size: 0.75em;
}

.opacity-75 {
  opacity: 0.75;
}
</style>
