<template>
  <div>
    <div class="d-flex mb-3 pd-l-10 pd-t-10 pd-b-10 bd-b">
      <div class="flex-grow-1 pd-t-10 pd-l-10">
        <b>Thông tin xuất hóa đơn VAT</b>
      </div>
      <div class="pd-t-5">
        <button @click="loadData" type="button" class="btn btn-sm btn-outline-secondary me-2" :disabled="loading">
          <i v-show="!loading" class="fa fa-refresh me-2"></i>
          <span v-show="loading" class="spinner-border spinner-border-sm me-2">

          </span>
          Làm mới
        </button>
        <button @click="fnCreateOrUpdate(0)" type="button" class="btn btn-sm btn-primary">
          <i class="fa fa-plus me-2"></i>Thêm mới
        </button>
      </div>
    </div>

    <!-- Danh sách thông tin VAT -->
    <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin" v-if="items.length > 0">
      <div class="row bd-b p-3 pd-t-1" v-for="item in items" :key="item.Id">
        <div class="col">
          <div class="d-flex justify-content-between align-items-start">
            <div class="flex-grow-1">
              <h6 class="tx-16 mb-1">
                {{ item.CompanyName }}
                <span v-if="item.IsDefault" class="badge bg-success ms-2">Mặc định</span>
              </h6>
              <p class="tx-12 mb-1">
                <i class="fas fa-building me-2"></i>
                <strong>Mã số thuế:</strong> {{ item.TaxCode }}
              </p>
              <p class="tx-12 mb-1">
                <i class="fas fa-envelope me-2"></i>
                <strong>Email hóa đơn:</strong> {{ item.InvoiceEmail }}
              </p>
              <p class="tx-12 mb-1">
                <i class="fas fa-map-marker-alt me-2"></i>
                <strong>Địa chỉ:</strong> {{ item.Address }}
              </p>
              <p class="tx-12 mb-1">
                <i class="fas fa-user me-2"></i>
                <strong>Người liên hệ:</strong> {{ item.ContactName }} - {{ item.ContactPhone }}
              </p>
              <p class="tx-12 mb-1" v-if="item.Note">
                <i class="fas fa-sticky-note me-2"></i>
                <strong>Ghi chú:</strong> {{ item.Note }}
              </p>
              <p class="tx-11 text-muted mb-0">
                <i class="fas fa-clock me-1"></i>
                Cập nhật: {{ formatDate(item.UpdatedDate) }} bởi {{ item.UpdatedBy }}
              </p>
            </div>
            <div class="dropdown">
              <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" :id="'dropdown-' + item.Id"
                data-bs-toggle="dropdown" aria-expanded="false">
                <i class="fas fa-ellipsis-v"></i>
              </button>
              <ul class="dropdown-menu" :aria-labelledby="'dropdown-' + item.Id">
                <li>
                  <a class="dropdown-item" href="#" @click.prevent="fnViewDetail(item.Id)">
                    <i class="fas fa-eye me-2"></i>Xem chi tiết
                  </a>
                </li>
                <li>
                  <a class="dropdown-item" href="#" @click.prevent="fnCreateOrUpdate(item.Id)">
                    <i class="fas fa-edit me-2"></i>Chỉnh sửa
                  </a>
                </li>
                <li v-if="!item.IsDefault">
                  <a class="dropdown-item" href="#" @click.prevent="fnSetAsDefault(item.Id)">
                    <i class="fas fa-star me-2"></i>Đặt làm mặc định
                  </a>
                </li>
                <li>
                  <hr class="dropdown-divider">
                </li>
                <li>
                  <a class="dropdown-item text-danger" href="#" @click.prevent="fnConfirmDelete(item.Id)">
                    <i class="fas fa-trash me-2"></i>Xóa
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Thông báo khi chưa có dữ liệu -->
    <div v-else class="text-center py-4">
      <i class="fas fa-file-invoice fa-3x text-muted mb-3"></i>
      <p class="text-muted">Chưa có thông tin xuất hóa đơn VAT nào.</p>
      <button @click="fnCreateOrUpdate(0)" type="button" class="btn btn-primary">
        <i class="fa fa-plus me-2"></i>Thêm thông tin VAT đầu tiên
      </button>
    </div>

    <!-- Modal thêm/sửa -->
    <LadaDialog :visible="modalControl.CreateOrUpdate">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title" v-if="selectedId <= 0">Thêm thông tin VAT</h5>
          <h5 class="modal-title" v-if="selectedId > 0">Cập nhật thông tin VAT</h5>
          <button @click="closeModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <CreateOrUpdateVatInfo @cancel="closeModal" @success="handleSuccess" :id="selectedId"
          :customerId="props.customerId">
        </CreateOrUpdateVatInfo>
      </template>
    </LadaDialog>

    <!-- Modal xem chi tiết -->
    <LadaDialog :visible="modalControl.ViewDetail">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Chi tiết thông tin VAT</h5>
          <button @click="closeModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <ViewVatInfoDetail @cancel="closeModal" :id="selectedId">
        </ViewVatInfoDetail>
      </template>
    </LadaDialog>

    <!-- Modal xác nhận xóa -->
    <LadaDialog :visible="modalControl.ConfirmDelete">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Xác nhận xóa</h5>
          <button @click="closeModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <ConfirmDeleteVatInfo @cancel="closeModal" @success="handleDeleteSuccess" :id="selectedId">
        </ConfirmDeleteVatInfo>
      </template>
    </LadaDialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import vatInfoService from "@/services/vatInfoService.js";
import CreateOrUpdateVatInfo from "./CreateOrUpdateVatInfo.vue";
import ViewVatInfoDetail from "./ViewVatInfoDetail.vue";
import ConfirmDeleteVatInfo from "./ConfirmDeleteVatInfo.vue";

import { useToast } from "vue-toastification";
const toast = useToast();

//#region props
const props = defineProps({
  customerId: {
    type: [String, Number],
    required: true
  },
  customerName: {
    type: String,
    default: ''
  }
});
//#endregion

//#region DATA
const items = reactive([]);
const loading = ref(false);
const selectedId = ref(0);

const modalControl = reactive({
  CreateOrUpdate: false,
  ViewDetail: false,
  ConfirmDelete: false
});

function closeModal() {
  modalControl.CreateOrUpdate = false;
  modalControl.ViewDetail = false;
  modalControl.ConfirmDelete = false;
  selectedId.value = 0;
}
//#endregion

//#region Methods
async function loadData() {
  try {
    loading.value = true;
    const result = await vatInfoService.getByCustomerId(props.customerId);
    // API trả về object với thuộc tính Items
    const vatInfoList = result.Items || result || [];
    items.splice(0, items.length, ...vatInfoList);
  } catch (error) {
    console.error('Error loading VAT info:', error);
    toast.error('Có lỗi xảy ra khi tải dữ liệu');
  } finally {
    loading.value = false;
  }
}

async function fnCreateOrUpdate(id) {
  selectedId.value = id;
  modalControl.CreateOrUpdate = true;
}

async function fnViewDetail(id) {
  selectedId.value = id;
  modalControl.ViewDetail = true;
}

async function fnConfirmDelete(id) {
  selectedId.value = id;
  modalControl.ConfirmDelete = true;
}

async function fnSetAsDefault(id) {
  try {
    loading.value = true;
    const result = await vatInfoService.setAsDefault(id);

    if (result && result.Result === 1) {
      toast.success('Đặt làm mặc định thành công!');
      await loadData();
    } else {
      toast.error('Thất bại: ' + (result.Message || 'Có lỗi xảy ra'));
    }
  } catch (error) {
    console.error('Error setting as default:', error);
    toast.error('Có lỗi xảy ra khi đặt làm mặc định');
  } finally {
    loading.value = false;
  }
}

function handleSuccess() {
  closeModal();
  loadData();
}

function handleDeleteSuccess() {
  closeModal();
  loadData();
}

function formatDate(dateString) {
  if (!dateString) return '';
  try {
    return new Date(dateString).toLocaleString('vi-VN');
  } catch {
    return dateString;
  }
}
//#endregion

//#region Events
onMounted(async () => {
  await loadData();
});
//#endregion
</script>

<style scoped>
.bd-b {
  border-bottom: 1px solid #e9ecef;
}

.pd-l-10 {
  padding-left: 10px;
}

.pd-t-10 {
  padding-top: 10px;
}

.pd-b-10 {
  padding-bottom: 10px;
}

.pd-t-5 {
  padding-top: 5px;
}

.pd-t-1 {
  padding-top: 1px;
}

.tx-16 {
  font-size: 16px;
}

.tx-12 {
  font-size: 12px;
}

.tx-11 {
  font-size: 11px;
}

.dropdown-toggle::after {
  display: none;
}
</style>
