<template>
  <div class="call-log-management">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
      <h2 class="mb-0">Quản lý CallLog</h2>
      <div class="d-flex gap-2">
        <button class="btn btn-outline-secondary" @click="showStatistics = !showStatistics">
          <i class="fas fa-chart-bar me-2"></i>
          Thống kê
        </button>
        <button class="btn btn-primary" @click="openCreateModal">
          <i class="fas fa-plus me-2"></i>
          Tạo CallLog
        </button>
      </div>
    </div>

    <!-- Statistics Panel -->
    <div v-if="showStatistics" class="card mb-4">
      <div class="card-header">
        <h5 class="mb-0">Thống kê CallLog</h5>
      </div>
      <div class="card-body">
        <CallLogStatistics :start-date="searchModel.Search?.PredicateObject?.TimeStart"
          :end-date="searchModel.Search?.PredicateObject?.TimeEnd" />
      </div>
    </div>

    <!-- Search Filters -->
    <div class="card card-search shadow-none">
      <form class="card-body" @submit.prevent="search">
        <div class="row">
          <div class="col-lg-3 col-md-4 mb-3">
            <label>Từ khóa</label>
            <input type="text" class="form-control" v-model="searchModel.Search.PredicateObject.Keyword"
              placeholder="Số điện thoại, tên hiển thị..." />
          </div>
          <div class="col-lg-3 col-md-4 mb-3">
            <label>Thời gian cuộc gọi</label>
            <VueDatePicker ref="createDatePicker" v-model="date" :enable-time-picker="false" range multi-calendars
              auto-apply :format="format" @update:model-value="handleDate">
              <template #left-sidebar>
                <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
              </template>
            </VueDatePicker>
          </div>
          <div class="col-lg-3 col-md-4 mb-3">
            <label>Loại cuộc gọi</label>
            <v-select label="Name" :options="callTypes" v-model="searchModel.Search.PredicateObject.CallType"
              :reduce="(option) => option.Value"></v-select>
          </div>
          <div class="col-lg-3 col-md-4 mb-3">
            <label>Trạng thái Lead</label>
            <v-select label="Name" :options="leadStatuses" v-model="searchModel.Search.PredicateObject.LeadStatus"
              :reduce="(option) => option.Value"></v-select>
          </div>
          <div class="col-lg-3 col-md-4 mb-3">
            <label>Số nguồn</label>
            <input type="text" class="form-control" v-model="searchModel.Search.PredicateObject.FromNo"
              placeholder="Số điện thoại nguồn" />
          </div>
          <div class="col-lg-3 col-md-4 mb-3">
            <label>Số đích</label>
            <input type="text" class="form-control" v-model="searchModel.Search.PredicateObject.ToNo"
              placeholder="Số điện thoại đích" />
          </div>
        </div>
        <div class="row">
          <div class="col-lg mb-3">
            <button type="submit" class="btn btn-dark" :disabled="loading">
              <i v-show="!loading" class="fe fe-search"></i>
              <span v-show="loading" class="spinner-border spinner-border-sm"></span>
              <span>Tìm kiếm</span>
            </button>
          </div>
        </div>
      </form>
    </div>

    <!-- Results Table -->
    <div class="card card-table shadow-none">
      <div class="card-body card-table-body">
        <div class="d-flex flex-row justify-content-between mg-b-10">
          <div></div>
        </div>
        <div class="table-responsive border-top mg-b-10">
          <table class="table table-vcenter mb-0" style="min-height:300px">
            <thead>
              <tr>
                <th class="wd-lg-12p min-width-2"><span>Thời gian</span></th>
                <th class="wd-lg-12p min-width-2"><span>Từ số</span></th>
                <th class="wd-lg-8p min-width-1"><span>Nhánh</span></th>
                <th class="wd-lg-8p min-width-1"><span>Tên tổng đài viên</span></th>
                <th class="wd-lg-8p min-width-1"><span>Thời lượng</span></th>
                <th class="wd-lg-8p min-width-1"><span>Trạng thái Lead</span></th>
                <th class="wd-lg-8p"></th>
              </tr>
            </thead>
            <tbody v-if="loading">
              <tr>
                <td colspan="7" class="tx-semibold text-center text-default">
                  <span class="spinner-border spinner-border-sm"></span>
                </td>
              </tr>
            </tbody>
            <tbody v-if="!loading && items.length <= 0">
              <tr>
                <td colspan="7" class="tx-semibold text-center text-danger">
                  Không tìm thấy bản ghi nào!
                </td>
              </tr>
            </tbody>
            <tbody v-if="!loading && items.length > 0">
              <tr v-for="item in items" :key="item.Id">
                <td class="text-wrap align-top">
                  <div class="fw-bold">{{ item.CreatedTime }}</div>
                  <small class="text-muted">{{ item.HistoryID }}</small>
                </td>
                <td class="text-wrap align-top">
                  <div>{{ item.FromNo }}</div>
                  <small class="text-muted">{{ item.FromDispName }}</small>
                </td>
                <td class="text-wrap align-top">
                  <div class="fw-bold">{{ item.FinalDN || 'N/A' }}</div>
                </td>
                <td class="text-wrap align-top">
                  <div>{{ item.FinalDispName || 'N/A' }}</div>
                </td>
                <td class="text-wrap align-top">
                  <span class="badge bg-info">{{ item.Duration }}</span>
                </td>
                <td class="text-wrap align-top">
                  <span class="badge" :class="getLeadStatusClass(item.LeadStatus)">
                    {{ item.LeadStatusStr }}
                  </span>
                </td>
                <td class="align-top pt-2">
                  <button @click="viewDetail(item)" type="button" class="btn btn-outline-primary btn-sm">
                    <i class="fe fe-eye me-1"></i>Xem chi tiết
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <pager ref="ctrlPager" v-show="!loading && items.length > 0" @PageSizeChanged="PageSizeChanged"
          @PageIndexChanged="PageIndexChanged" :Total="searchModel.Pagination.Total" :TotalCurrent="items.length">
        </pager>
      </div>
    </div>

    <!-- Modals -->

    <LadaDialog :visible="modalControl.Detail">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Chi tiết CallLog</h5>
          <button @click="closeDetailModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <CallLogDetailModal :call-log-id="selectedCallLogId" @close="closeDetailModal" />
      </template>
    </LadaDialog>
  </div>
</template>

<script setup>
//#region Imports
import { ref, reactive, onMounted } from 'vue';
import callLogService from "@/services/crm/callLogService";
//#endregion

//#region Components
import DatepickerInstance from "@vuepic/vue-datepicker";
import { LadaDialog, DateRangeSidebar } from '@/components/index';
import CallLogStatistics from "./components/CallLogStatistics.vue";
import CallLogDetailModal from "./components/CallLogDetailModal.vue";
import { useToast } from "vue-toastification";
const toast = useToast();
//#endregion

//#region Modals
const modalControl = reactive({
  Detail: false
});

const selectedCallLogId = ref(null);

function viewDetail(item) {
  selectedCallLogId.value = item.Id;
  modalControl.Detail = true;
}

function closeDetailModal() {
  modalControl.Detail = false;
  selectedCallLogId.value = null;
}

//#endregion

//#region SEARCH
const callTypes = [
  { Value: '', Name: 'Tất cả' },
  { Value: 'Inbound', Name: 'Cuộc gọi đến' },
  { Value: 'Outbound', Name: 'Cuộc gọi đi' }
];

const leadStatuses = [
  { Value: '', Name: 'Tất cả' },
  { Value: '1', Name: 'Tạo mới' },
  { Value: '2', Name: 'Đã tiếp nhận' },
  { Value: '3', Name: 'Thành công' },
  { Value: '4', Name: 'Thất bại' }
];

const searchModel = reactive({
  Pagination: {
    Total: 0,
    PageIndex: 1,
    PageSize: 25
  },
  Sort: {
    Predicate: "TimeStart",
    Reverse: true
  },
  Search: {
    PredicateObject: {
      Keyword: '',
      TimeStart: null,
      TimeEnd: null,
      LeadStatus: '',
      CallType: '',
      FromNo: '',
      ToNo: ''
    }
  }
});

const items = reactive([]);
const loading = ref(false);
const showStatistics = ref(false);

const date = ref();
const createDatePicker = ref(DatepickerInstance);

const format = (dates) => {
  let start = dates[0];
  let end = dates[1];
  const dayStart = start.getDate();
  const monthStart = start.getMonth() + 1;
  const yearStart = start.getFullYear();
  const dayEnd = end.getDate();
  const monthEnd = end.getMonth() + 1;
  const yearEnd = end.getFullYear();

  return `${dayStart}/${monthStart}/${yearStart} - ${dayEnd}/${monthEnd}/${yearEnd}`;
}

async function onChangeDate(newDates) {
  date.value = newDates;
  createDatePicker.value.closeMenu();
  handleDate(newDates);
}

function handleDate(modelData) {
  if (modelData != null) {
    searchModel.Search.PredicateObject.TimeStart = modelData[0];
    searchModel.Search.PredicateObject.TimeEnd = modelData[1];
  } else {
    searchModel.Search.PredicateObject.TimeStart = null;
    searchModel.Search.PredicateObject.TimeEnd = null;
  }
}

const ctrlPager = ref();
async function search() {
  searchModel.Pagination.PageIndex = 1;
  ctrlPager.value.Refresh();
  loadData();
}

async function loadData() {
  loading.value = true;
  items.splice(0, items.length);
  var searchResult = await callLogService.search(searchModel);
  if (searchResult.Items != null && searchResult.Items.length > 0) {
    searchResult.Items.forEach(item => {
      items.push(item);
    });
  }
  searchModel.Pagination.Total = searchResult.TotalRecord;
  loading.value = false;
}

function PageSizeChanged(pagesize) {
  searchModel.Pagination.PageSize = pagesize;
  searchModel.Pagination.PageIndex = 1;
  loadData();
}

function PageIndexChanged(pageIndex) {
  searchModel.Pagination.PageIndex = pageIndex;
  loadData();
}
//#endregion

//#region Utilities
function formatDateTime(dateTime) {
  if (!dateTime) return "";
  return new Date(dateTime).toLocaleString('vi-VN');
}

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

function getLeadStatusClass(status) {
  const statusClasses = {
    1: 'bg-primary',
    2: 'bg-warning',
    3: 'bg-success',
    4: 'bg-danger'
  };
  return statusClasses[status] || 'bg-secondary';
}
//#endregion

onMounted(async () => {
  await search();
})
</script>

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

.table th {
  font-weight: 600;
  border-bottom: 2px solid #dee2e6;
}

.btn-group-sm .btn {
  padding: 0.25rem 0.5rem;
}

.badge {
  font-size: 0.75em;
}

.pagination .page-link {
  color: #6c757d;
}

.pagination .page-item.active .page-link {
  background-color: #0d6efd;
  border-color: #0d6efd;
}
</style>
