<template>
  <div class="call-log-dashboard">
    <!-- Date Range Selector -->
    <div class="card mb-4">
      <div class="card-header">
        <div class="d-flex justify-content-between align-items-center">
          <h6 class="mb-0">Bộ lọc thời gian</h6>
          <button 
            class="btn btn-sm btn-outline-primary"
            @click="refreshStatistics"
            :disabled="loading"
          >
            <i class="fas fa-sync-alt me-1"></i>
            Làm mới
          </button>
        </div>
      </div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-3">
            <label class="form-label">Từ ngày:</label>
            <input 
              type="date" 
              class="form-control"
              v-model="dateRange.startDate"
              @change="onDateRangeChange"
            />
          </div>
          <div class="col-md-3">
            <label class="form-label">Đến ngày:</label>
            <input 
              type="date" 
              class="form-control"
              v-model="dateRange.endDate"
              @change="onDateRangeChange"
            />
          </div>
          <div class="col-md-6">
            <label class="form-label">Khoảng thời gian nhanh:</label>
            <div class="btn-group w-100" role="group">
              <button 
                type="button" 
                class="btn btn-outline-secondary"
                @click="setQuickRange('today')"
              >
                Hôm nay
              </button>
              <button 
                type="button" 
                class="btn btn-outline-secondary"
                @click="setQuickRange('week')"
              >
                Tuần này
              </button>
              <button 
                type="button" 
                class="btn btn-outline-secondary"
                @click="setQuickRange('month')"
              >
                Tháng này
              </button>
              <button 
                type="button" 
                class="btn btn-outline-secondary"
                @click="setQuickRange('quarter')"
              >
                Quý này
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Statistics Overview -->
    <CallLogStatistics 
      :start-date="dateRange.startDate" 
      :end-date="dateRange.endDate"
      :key="statisticsKey"
    />

    <!-- Detailed Charts -->
    <div class="row g-4 mt-2">
      <!-- Call Volume by Hour -->
      <div class="col-md-6">
        <div class="card h-100">
          <div class="card-header">
            <h6 class="mb-0">Lượng cuộc gọi theo giờ</h6>
          </div>
          <div class="card-body">
            <div v-if="loading" class="text-center p-4">
              <div class="spinner-border spinner-border-sm"></div>
            </div>
            <div v-else-if="hourlyData.length > 0">
              <canvas ref="hourlyChart" width="400" height="200"></canvas>
            </div>
            <div v-else class="text-center text-muted p-4">
              <i class="fas fa-chart-line fa-2x mb-2"></i>
              <p>Không có dữ liệu</p>
            </div>
          </div>
        </div>
      </div>

      <!-- Call Duration Distribution -->
      <div class="col-md-6">
        <div class="card h-100">
          <div class="card-header">
            <h6 class="mb-0">Phân bố thời lượng cuộc gọi</h6>
          </div>
          <div class="card-body">
            <div v-if="loading" class="text-center p-4">
              <div class="spinner-border spinner-border-sm"></div>
            </div>
            <div v-else-if="durationData.length > 0">
              <canvas ref="durationChart" width="400" height="200"></canvas>
            </div>
            <div v-else class="text-center text-muted p-4">
              <i class="fas fa-chart-pie fa-2x mb-2"></i>
              <p>Không có dữ liệu</p>
            </div>
          </div>
        </div>
      </div>

      <!-- Top Phone Numbers -->
      <div class="col-md-6">
        <div class="card h-100">
          <div class="card-header">
            <h6 class="mb-0">Top số điện thoại gọi nhiều nhất</h6>
          </div>
          <div class="card-body">
            <div v-if="loading" class="text-center p-4">
              <div class="spinner-border spinner-border-sm"></div>
            </div>
            <div v-else-if="topCallers.length > 0" class="list-group list-group-flush">
              <div 
                v-for="(caller, index) in topCallers" 
                :key="caller.phoneNumber"
                class="list-group-item d-flex justify-content-between align-items-center px-0"
              >
                <div>
                  <span class="badge bg-primary me-2">{{ index + 1 }}</span>
                  <strong>{{ caller.phoneNumber }}</strong>
                  <br>
                  <small class="text-muted">{{ caller.displayName || 'Không có tên' }}</small>
                </div>
                <div class="text-end">
                  <span class="badge bg-info">{{ caller.callCount }} cuộc gọi</span>
                  <br>
                  <small class="text-muted">{{ formatDuration(caller.totalDuration) }}</small>
                </div>
              </div>
            </div>
            <div v-else class="text-center text-muted p-4">
              <i class="fas fa-phone fa-2x mb-2"></i>
              <p>Không có dữ liệu</p>
            </div>
          </div>
        </div>
      </div>

      <!-- Call Success Rate -->
      <div class="col-md-6">
        <div class="card h-100">
          <div class="card-header">
            <h6 class="mb-0">Tỷ lệ thành công cuộc gọi</h6>
          </div>
          <div class="card-body">
            <div v-if="loading" class="text-center p-4">
              <div class="spinner-border spinner-border-sm"></div>
            </div>
            <div v-else class="text-center">
              <div class="mb-3">
                <div class="progress" style="height: 20px;">
                  <div 
                    class="progress-bar bg-success" 
                    :style="{ width: successRate + '%' }"
                  >
                    {{ successRate }}%
                  </div>
                </div>
              </div>
              <div class="row text-center">
                <div class="col-4">
                  <h5 class="text-success mb-0">{{ successfulCalls }}</h5>
                  <small class="text-muted">Thành công</small>
                </div>
                <div class="col-4">
                  <h5 class="text-warning mb-0">{{ pendingCalls }}</h5>
                  <small class="text-muted">Đang xử lý</small>
                </div>
                <div class="col-4">
                  <h5 class="text-danger mb-0">{{ failedCalls }}</h5>
                  <small class="text-muted">Thất bại</small>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Export Options -->
    <div class="card mt-4">
      <div class="card-header">
        <h6 class="mb-0">Xuất báo cáo</h6>
      </div>
      <div class="card-body">
        <div class="d-flex gap-2">
          <button 
            class="btn btn-outline-success"
            @click="exportToExcel"
            :disabled="loading"
          >
            <i class="fas fa-file-excel me-2"></i>
            Xuất Excel
          </button>
          <button 
            class="btn btn-outline-danger"
            @click="exportToPDF"
            :disabled="loading"
          >
            <i class="fas fa-file-pdf me-2"></i>
            Xuất PDF
          </button>
          <button 
            class="btn btn-outline-info"
            @click="exportToCSV"
            :disabled="loading"
          >
            <i class="fas fa-file-csv me-2"></i>
            Xuất CSV
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import callLogService from "@/services/crm/callLogService";
import CallLogStatistics from "./CallLogStatistics.vue";

export default {
  name: "CallLogDashboard",
  components: {
    CallLogStatistics
  },
  data() {
    return {
      loading: false,
      statisticsKey: 0,
      dateRange: {
        startDate: this.getDateString(new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)), // 30 days ago
        endDate: this.getDateString(new Date())
      },
      hourlyData: [],
      durationData: [],
      topCallers: [],
      successfulCalls: 0,
      pendingCalls: 0,
      failedCalls: 0
    };
  },
  computed: {
    totalCalls() {
      return this.successfulCalls + this.pendingCalls + this.failedCalls;
    },
    successRate() {
      if (this.totalCalls === 0) return 0;
      return Math.round((this.successfulCalls / this.totalCalls) * 100);
    }
  },
  mounted() {
    this.loadDashboardData();
  },
  methods: {
    getDateString(date) {
      return date.toISOString().split('T')[0];
    },

    setQuickRange(range) {
      const now = new Date();
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      
      switch (range) {
        case 'today':
          this.dateRange.startDate = this.getDateString(today);
          this.dateRange.endDate = this.getDateString(now);
          break;
        case 'week':
          const weekStart = new Date(today);
          weekStart.setDate(today.getDate() - today.getDay());
          this.dateRange.startDate = this.getDateString(weekStart);
          this.dateRange.endDate = this.getDateString(now);
          break;
        case 'month':
          const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
          this.dateRange.startDate = this.getDateString(monthStart);
          this.dateRange.endDate = this.getDateString(now);
          break;
        case 'quarter':
          const quarterStart = new Date(now.getFullYear(), Math.floor(now.getMonth() / 3) * 3, 1);
          this.dateRange.startDate = this.getDateString(quarterStart);
          this.dateRange.endDate = this.getDateString(now);
          break;
      }
      this.onDateRangeChange();
    },

    onDateRangeChange() {
      this.statisticsKey++; // Force refresh statistics component
      this.loadDashboardData();
    },

    refreshStatistics() {
      this.statisticsKey++;
      this.loadDashboardData();
    },

    async loadDashboardData() {
      this.loading = true;
      try {
        // Load mock data for demonstration
        // In real implementation, these would be separate API calls
        await this.loadHourlyData();
        await this.loadDurationData();
        await this.loadTopCallers();
        await this.loadSuccessRateData();
      } catch (error) {
        console.error("Lỗi tải dữ liệu dashboard:", error);
        this.$toast?.error("Có lỗi xảy ra khi tải dữ liệu dashboard");
      } finally {
        this.loading = false;
      }
    },

    async loadHourlyData() {
      // Mock data - replace with actual API call
      this.hourlyData = Array.from({ length: 24 }, (_, i) => ({
        hour: i,
        calls: Math.floor(Math.random() * 50) + 10
      }));
    },

    async loadDurationData() {
      // Mock data - replace with actual API call
      this.durationData = [
        { range: '0-1 phút', count: 120 },
        { range: '1-3 phút', count: 200 },
        { range: '3-5 phút', count: 150 },
        { range: '5-10 phút', count: 80 },
        { range: '>10 phút', count: 30 }
      ];
    },

    async loadTopCallers() {
      // Mock data - replace with actual API call
      this.topCallers = [
        { phoneNumber: '0901234567', displayName: 'Nguyễn Văn A', callCount: 25, totalDuration: 1800 },
        { phoneNumber: '0987654321', displayName: 'Trần Thị B', callCount: 20, totalDuration: 1500 },
        { phoneNumber: '0912345678', displayName: 'Lê Văn C', callCount: 18, totalDuration: 1200 },
        { phoneNumber: '0923456789', displayName: 'Phạm Thị D', callCount: 15, totalDuration: 900 },
        { phoneNumber: '0934567890', displayName: 'Hoàng Văn E', callCount: 12, totalDuration: 800 }
      ];
    },

    async loadSuccessRateData() {
      // Mock data - replace with actual API call
      this.successfulCalls = 350;
      this.pendingCalls = 150;
      this.failedCalls = 100;
    },

    formatDuration(seconds) {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;
      
      if (hours > 0) {
        return `${hours}h ${minutes}m ${secs}s`;
      } else if (minutes > 0) {
        return `${minutes}m ${secs}s`;
      } else {
        return `${secs}s`;
      }
    },

    exportToExcel() {
      this.$toast?.info("Chức năng xuất Excel đang được phát triển");
    },

    exportToPDF() {
      this.$toast?.info("Chức năng xuất PDF đang được phát triển");
    },

    exportToCSV() {
      this.$toast?.info("Chức năng xuất CSV đang được phát triển");
    }
  }
};
</script>

<style scoped>
.call-log-dashboard {
  padding: 20px;
}

.progress {
  background-color: #e9ecef;
}

.list-group-item {
  border: none;
  border-bottom: 1px solid #dee2e6;
}

.list-group-item:last-child {
  border-bottom: none;
}

.btn-group .btn {
  font-size: 0.875rem;
}

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