<template>
  <div>
    <!-- Breadcrumb Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Quản lý doanh thu</h4>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
          <li class="breadcrumb-item"><a href="javascript:void(0);">Tài chính</a></li>
          <li class="breadcrumb-item active" aria-current="page">Quản lý doanh thu</li>
        </ol>
      </div>
    </div>

    <!-- Main Content Container -->
    <div class="row row-sm">
      <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">

        <!-- Search Form Card -->
        <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>Mô tả</label>
                <input type="text" v-model="searchModel.Search.PredicateObject.Description" class="form-control"
                  placeholder="mô tả...">
              </div>

              <div class="col-lg-3 col-md-4 mb-3">
                <label>Ngày tạo</label>
                <VueDatePicker ref="createDatePicker" v-model="date" :enable-time-picker="false" range
                  multi-calendars auto-apply :format="format" @update:model-value="handleDate" utc="preserve">
                  <template #left-sidebar>
                    <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                  </template>
                </VueDatePicker>
              </div>

              <div class="col-lg-3 col-md-4 mb-3">
                <label>Trạng thái</label>
                <v-select label="Name" :options="statuses" v-model="searchModel.Search.PredicateObject.Status"
                  :reduce="(option) => option.Id"></v-select>
              </div>

              <div class="col-lg-3 col-md-4 mb-3">
                <label>Danh mục doanh thu</label>
                <v-select label="Name" :options="incomeCategories"
                  v-model="searchModel.Search.PredicateObject.IncomeCategoryId" :reduce="(option) => option.Id">
                  <template v-slot:no-options="{ search, searching }">
                    <template v-if="searching">
                      Không có kết quả cho <em>{{ search }}</em>.
                    </template>
                    <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                  </template>
                </v-select>
              </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>

        <!-- Data Table Card -->
        <div class="card card-table shadow-none">
          <div class="card-body card-table-body">
            <!-- Action Buttons -->
            <div class="d-flex flex-row justify-content-between mg-b-10">
              <button @click="fnCreateOrUpdate(0)" type="button" class="btn btn-outline-primary mx-2 button-icon mb-1">
                <i class="fe fe-plus me-2"></i>Tạo mới
              </button>
            </div>

            <!-- Table -->
            <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-18p min-width-2"><span>Mô tả</span></th>
                    <th class="wd-lg-10p"><span>Số tiền</span></th>
                    <th class="wd-lg-12p"><span>Danh mục</span></th>
                    <th class="wd-lg-8p"><span>Trạng thái</span></th>
                    <th class="wd-lg-8p"><span>Người tạo</span></th>
                    <th class="wd-lg-8p"><span>Người duyệt</span></th>
                    <th class="wd-lg-8p"><span>Ngày tạo</span></th>
                    <th class="wd-lg-18p"></th>
                  </tr>
                </thead>

                <!-- Loading State -->
                <tbody v-if="loading">
                  <tr>
                    <td colspan="8" class="tx-semibold text-center text-default">
                      <span class="spinner-border spinner-border-sm"></span>
                    </td>
                  </tr>
                </tbody>

                <!-- Empty State -->
                <tbody v-if="!loading && incomes.length <= 0">
                  <tr>
                    <td colspan="8" class="tx-semibold text-center text-danger">
                      Không tìm thấy bản ghi nào!
                    </td>
                  </tr>
                </tbody>

                <!-- Data Rows -->
                <tbody v-if="!loading && incomes.length > 0">
                  <tr v-for="income in incomes" :key="income.Id">
                    <td class="text-wrap align-top">
                      <div>
                        <strong>{{ income.Description }}</strong>
                        <div v-if="income.Note" class="text-muted small">
                          {{ income.Note }}
                        </div>
                      </div>
                    </td>
                    <td class="align-top">
                      <strong class="text-success">{{ formatCurrency(income.Amount) }}</strong>
                    </td>
                    <td class="align-top">
                      <span class="badge bg-info">{{ income.IncomeCategoryName }}</span>
                    </td>
                    <td class="align-top">
                      <IncomeStatusBadge :status="income.Status" />
                    </td>
                    <td class="align-top">{{ income.CreatedByUserName || '-' }}</td>
                    <td class="align-top">{{ income.ApprovedByUserName || '-' }}</td>
                    <td class="align-top">{{ formatDate(income.CreatedDate) }}</td>
                    <td class="align-top pt-2">
                      <!-- Action Dropdown -->
                      <button type="button" data-bs-toggle="dropdown"
                        class="mb-1 mt-1 mr-1 btn btn-light dropdown-toggle btn-sm" aria-expanded="false">
                        <i class="fas fa-cog"></i> Quản lý
                      </button>
                      <div class="dropdown-menu dropdown-menu-arrow">
                        <a @click="fnCreateOrUpdate(income.Id)" class="dropdown-item" href="javascript:void(0);"
                          v-if="income.Status === 0">
                          <i class="fe fe-edit-2"></i>
                          <span class="mg-l-6">Chỉnh sửa</span>
                        </a>
                        <a v-if="income.CanApprove && income.Status === 0" @click="confirmApprove(income)"
                          class="dropdown-item" href="javascript:void(0);">
                          <i class="fe fe-check"></i>
                          <span class="mg-l-6">Duyệt</span>
                        </a>
                        <a v-if="income.CanReject && income.Status === 0" @click="openRejectModal(income)"
                          class="dropdown-item" href="javascript:void(0);">
                          <i class="fe fe-x"></i>
                          <span class="mg-l-6">Từ chối</span>
                        </a>
                        <a @click="openMarkAsReceivedModal(income)" class="dropdown-item" href="javascript:void(0);"
                          v-if="income.Status === 1 && income.CanMarkAsReceived">
                          <i class="fe fe-credit-card"></i>
                          <span class="mg-l-6">Đánh dấu đã nhận tiền</span>
                        </a>
                        <div class="dropdown-divider" v-if="income.Status === 2 && income.RejectReason"></div>
                        <a class="dropdown-item disabled" href="javascript:void(0);"
                          v-if="income.Status === 2 && income.RejectReason" :title="income.RejectReason">
                          <i class="fe fe-info"></i>
                          <span class="mg-l-6">Lý do từ chối</span>
                        </a>
                        <a @click="confirmDelete(income)" class="dropdown-item" href="javascript:void(0);"
                          v-if="income.Status !== 3">
                          <i class="fe fe-trash"></i>
                          <span class="mg-l-6">Xóa</span>
                        </a>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- Pagination -->
            <pager ref="ctrlPager" v-show="!loading && incomes.length > 0" @PageSizeChanged="PageSizeChanged"
              @PageIndexChanged="PageIndexChanged" :Total="searchModel.Pagination.Total"
              :TotalCurrent="incomes.length">
            </pager>
          </div>
        </div>

      </div>
    </div>

    <!-- Create/Edit Modal -->
    <LadaDialog :visible="modalControl.CreateOrUpdate">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title" v-if="selectedId === '0'">Tạo mới</h5>
          <h5 class="modal-title" v-if="selectedId !== '0'">Cập nhật</h5>
          <button @click="closeModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <IncomeForm :id="selectedId" :is-submitting="isSubmitting" @submit="handleSubmit" @cancel="closeModal" />
      </template>
    </LadaDialog>

    <!-- Approve Modal -->
    <LadaDialog :visible="showApproveModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Xác nhận duyệt</h5>
          <button type="button" class="btn-close" @click="showApproveModal = false"></button>
        </div>
      </template>

      <template #body>
        <p>Bạn có chắc chắn muốn duyệt doanh thu <strong>{{ incomeToApprove?.Description }}</strong>?</p>
      </template>

      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="showApproveModal = false">
            Hủy
          </button>
          <button type="button" class="btn btn-success" @click="handleApprove" :disabled="isSubmitting">
            <span v-if="isSubmitting" class="spinner-border spinner-border-sm me-2"></span>
            Duyệt
          </button>
        </div>
      </template>
    </LadaDialog>

    <!-- Reject Modal -->
    <LadaDialog :visible="showRejectModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Từ chối doanh thu</h5>
          <button type="button" class="btn-close" @click="showRejectModal = false"></button>
        </div>
      </template>

      <template #body>
        <p>Bạn có chắc chắn muốn từ chối doanh thu <strong>{{ incomeToReject?.Description }}</strong>?</p>

        <!-- Hiển thị thông tin doanh thu -->
        <div class="alert alert-light mb-3">
          <div><strong>Số tiền:</strong> {{ formatCurrency(incomeToReject?.Amount) }}</div>
          <div><strong>Danh mục:</strong> {{ incomeToReject?.IncomeCategoryName }}</div>
          <div v-if="incomeToReject?.Note"><strong>Ghi chú:</strong> {{ incomeToReject.Note }}</div>
        </div>

        <div class="mb-3">
          <label class="form-label">Lý do từ chối <span class="text-danger">*</span></label>
          <textarea class="form-control" v-model="rejectReason" rows="3" placeholder="Nhập lý do từ chối..."
            required></textarea>
        </div>
      </template>

      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="showRejectModal = false">
            Hủy
          </button>
          <button type="button" class="btn btn-warning" @click="handleReject"
            :disabled="isSubmitting || !rejectReason.trim()">
            <span v-if="isSubmitting" class="spinner-border spinner-border-sm me-2"></span>
            Từ chối
          </button>
        </div>
      </template>
    </LadaDialog>

    <!-- Mark as Received Modal -->
    <LadaDialog :visible="showMarkAsReceivedModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Đánh dấu đã nhận tiền</h5>
          <button type="button" class="btn-close" @click="showMarkAsReceivedModal = false"></button>
        </div>
      </template>

      <template #body>
        <p>Bạn có chắc chắn muốn đánh dấu doanh thu <strong>{{ incomeToMarkAsReceived?.Description }}</strong> đã nhận
          tiền?</p>

        <div class="mb-3">
          <label class="form-label">Ghi chú</label>
          <textarea class="form-control" v-model="markAsReceivedNote" rows="3"
            placeholder="Nhập ghi chú về giao dịch nhận tiền..."></textarea>
        </div>
      </template>

      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="showMarkAsReceivedModal = false">
            Hủy
          </button>
          <button type="button" class="btn btn-info" @click="handleMarkAsReceived" :disabled="isSubmitting">
            <span v-if="isSubmitting" class="spinner-border spinner-border-sm me-2"></span>
            Đánh dấu
          </button>
        </div>
      </template>
    </LadaDialog>

    <!-- Delete Modal -->
    <LadaDialog :visible="showDeleteModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Xác nhận xóa</h5>
          <button type="button" class="btn-close" @click="closeDeleteModal"></button>
        </div>
      </template>

      <template #body>
        <p>Bạn có chắc chắn muốn xóa doanh thu <strong>{{ incomeToDelete?.Description }}</strong>?</p>
        <p class="text-muted">Hành động này không thể hoàn tác.</p>
      </template>

      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeDeleteModal">
            Hủy
          </button>
          <button type="button" class="btn btn-danger" @click="handleDelete" :disabled="isDeleting">
            <span v-if="isDeleting" class="spinner-border spinner-border-sm me-2"></span>
            Xóa
          </button>
        </div>
      </template>
    </LadaDialog>
  </div>
</template>

<script setup>
//#region Imports
import { ref, reactive, onMounted } from 'vue'
import { useToast } from 'vue-toastification'
import incomeService from '@/services/incomeService'
import incomeCategoryService from '@/services/incomeCategoryService'
//#endregion

//#region Components
import VueDatePicker from "@vuepic/vue-datepicker";
import { LadaDialog, DateRangeSidebar } from '@/components/index';
import { IncomeForm } from './components';
import IncomeStatusBadge from '@/components/income/IncomeStatusBadge.vue';
import vSelect from 'vue-select';
//#endregion

//#region Toast
const toast = useToast();
//#endregion

//#region Data
const loading = ref(false)
const incomes = reactive([])
const searchModel = reactive(incomeService.createDefaultSearchModel())
const ctrlPager = ref()
const date = ref()
const createDatePicker = ref(VueDatePicker)

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

const selectedId = ref('0');
const showDeleteModal = ref(false)
const showApproveModal = ref(false)
const showRejectModal = ref(false)
const showMarkAsReceivedModal = ref(false)
const isSubmitting = ref(false)
const isDeleting = ref(false)
const incomeToDelete = ref(null)
const incomeToApprove = ref(null)
const incomeToReject = ref(null)
const incomeToMarkAsReceived = ref(null)
const rejectReason = ref('')
const markAsReceivedNote = ref('')
//#endregion

//#region Select Options
const statuses = reactive([
  { Id: 0, Name: 'Chờ duyệt' },
  { Id: 1, Name: 'Đã duyệt' },
  { Id: 2, Name: 'Đã từ chối' },
  { Id: 3, Name: 'Đã nhận tiền' }
]);

const incomeCategories = reactive([]);
//#endregion

//#region Utility Functions
const formatCurrency = (amount) => {
  if (!amount) return '0 VND'
  return new Intl.NumberFormat('vi-VN', {
    style: 'currency',
    currency: 'VND'
  }).format(amount)
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    return new Date(dateString).toLocaleDateString('vi-VN')
  } catch {
    return '-'
  }
}

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.CreatedStart = modelData[0];
    searchModel.Search.PredicateObject.CreatedEnd = modelData[1];
  } else {
    searchModel.Search.PredicateObject.CreatedStart = null;
    searchModel.Search.PredicateObject.CreatedEnd = null;
  }
}
//#endregion

//#region SEARCH
async function search() {
  searchModel.Pagination.PageIndex = 1;
  ctrlPager.value.Refresh();
  loadData();
}

async function loadData() {
  loading.value = true;
  incomes.splice(0, incomes.length);
  var searchResult = await incomeService.search(searchModel);
  if (searchResult.Items != null && searchResult.Items.length > 0) {
    searchResult.Items.forEach(income => {
      incomes.push(income);
    });
  }
  searchModel.Pagination.Total = searchResult.TotalRecord || 0;
  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 Actions
async function fnCreateOrUpdate(id) {
  selectedId.value = id;
  modalControl.CreateOrUpdate = true;
}

function closeModal() {
  modalControl.CreateOrUpdate = false;
  selectedId.value = '0';
  loadData(); // Reload data after modal close
}

const handleSubmit = async (data) => {
  try {
    isSubmitting.value = true
    const result = await incomeService.createOrUpdate(data)

    if (result.Result === 1) {
      toast.success(result.Message || (selectedId.value !== '0' ? 'Cập nhật thành công' : 'Tạo mới thành công'))
      closeModal()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra')
    }
  } catch (error) {
    console.error('Error submitting form:', error)
    toast.error('Có lỗi xảy ra khi lưu dữ liệu')
  } finally {
    isSubmitting.value = false
  }
}

const confirmApprove = (income) => {
  incomeToApprove.value = income
  showApproveModal.value = true
}

const openRejectModal = (income) => {
  incomeToReject.value = income
  showRejectModal.value = true
}

const openMarkAsReceivedModal = (income) => {
  incomeToMarkAsReceived.value = income
  showMarkAsReceivedModal.value = true
}

const confirmDelete = (income) => {
  incomeToDelete.value = income
  showDeleteModal.value = true
}

const closeDeleteModal = () => {
  showDeleteModal.value = false
  incomeToDelete.value = null
}

const handleApprove = async () => {
  try {
    isSubmitting.value = true
    const result = await incomeService.approve(incomeToApprove.value.Id)

    if (result.Result === 1) {
      toast.success(result.Message || 'Duyệt thành công')
      showApproveModal.value = false
      incomeToApprove.value = null
      loadData()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi duyệt')
    }
  } catch (error) {
    console.error('Error approving income:', error)
    toast.error('Có lỗi xảy ra khi duyệt doanh thu')
  } finally {
    isSubmitting.value = false
  }
}

const handleReject = async () => {
  try {
    isSubmitting.value = true
    const result = await incomeService.reject(incomeToReject.value.Id, rejectReason.value)

    if (result.Result === 1) {
      toast.success(result.Message || 'Từ chối thành công')
      showRejectModal.value = false
      incomeToReject.value = null
      rejectReason.value = ''
      loadData()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi từ chối')
    }
  } catch (error) {
    console.error('Error rejecting income:', error)
    toast.error('Có lỗi xảy ra khi từ chối doanh thu')
  } finally {
    isSubmitting.value = false
  }
}

const handleMarkAsReceived = async () => {
  try {
    isSubmitting.value = true
    const result = await incomeService.markAsReceived(incomeToMarkAsReceived.value.Id, markAsReceivedNote.value)

    if (result.Result === 1) {
      toast.success(result.Message || 'Đánh dấu đã nhận tiền thành công')
      showMarkAsReceivedModal.value = false
      incomeToMarkAsReceived.value = null
      markAsReceivedNote.value = ''
      loadData()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi đánh dấu')
    }
  } catch (error) {
    console.error('Error marking income as received:', error)
    toast.error('Có lỗi xảy ra khi đánh dấu doanh thu đã nhận tiền')
  } finally {
    isSubmitting.value = false
  }
}

const handleDelete = async () => {
  try {
    isDeleting.value = true
    const result = await incomeService.delete(incomeToDelete.value.Id)

    if (result.Result === 1) {
      toast.success(result.Message || 'Xóa thành công')
      closeDeleteModal()
      loadData()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi xóa')
    }
  } catch (error) {
    console.error('Error deleting income:', error)
    toast.error('Có lỗi xảy ra khi xóa doanh thu')
  } finally {
    isDeleting.value = false
  }
}

//#region Income Categories
async function getIncomeCategories() {
  incomeCategories.splice(0, incomeCategories.length);
  var result = await incomeCategoryService.getAll();
  if (result && Array.isArray(result)) {
    result.forEach(category => incomeCategories.push(category));
  }
}
//#endregion

//#region Lifecycle
onMounted(async () => {
  await getIncomeCategories();
  await search();
})
//#endregion
</script>

<style scoped>
.table th {
  background-color: #f8f9fa;
  border-top: none;
  font-weight: 600;
  color: #495057;
}

.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}

.text-success {
  color: #198754 !important;
}
</style>

