<template>
  <div class="expense-detail-page">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
      <div class="d-flex align-items-center">
        <button type="button" class="btn btn-outline-secondary me-3" @click="goBack">
          <i class="fe fe-arrow-left me-2"></i>Quay lại
        </button>
        <div>
          <h4 class="mb-1">Chi tiết chi phí</h4>
          <p class="text-muted mb-0">Thông tin chi tiết về chi phí</p>
        </div>
      </div>
      <div class="d-flex gap-2">
        <button v-if="expense && expense.Status === 0 && expense.CanApprove" type="button" class="btn btn-success"
          @click="approveExpense" :disabled="isUpdating">
          <span v-if="isUpdating" class="spinner-border spinner-border-sm me-2"></span>
          <i v-else class="fe fe-check me-2"></i>
          Phê duyệt
        </button>
        <button v-if="expense && expense.Status === 0 && expense.CanReject" type="button" class="btn btn-danger"
          @click="openRejectModal" :disabled="isUpdating">
          <i class="fe fe-x me-2"></i>Từ chối
        </button>
        <button v-if="expense && expense.Status === 1 && expense.CanReject" type="button" class="btn btn-warning"
          @click="openUnapproveModal" :disabled="isUpdating">
          <i class="fe fe-x-circle me-2"></i>Bỏ duyệt
        </button>
        <button v-if="expense && expense.Status === 1 && expense.CanMarkAsPaid" type="button" class="btn btn-info"
          @click="openMarkAsPaidModal" :disabled="isUpdating">
          <i class="fe fe-dollar-sign me-2"></i>Đánh dấu đã chuyển tiền
        </button>
        <button v-if="expense" type="button" class="btn btn-primary" @click="editExpense">
          <i class="fe fe-edit-2 me-2"></i>Chỉnh sửa
        </button>
      </div>
    </div>

    <!-- Loading -->
    <div v-if="loading" class="text-center py-5">
      <Loader />
    </div>

    <!-- Error -->
    <div v-else-if="error" class="alert alert-danger">
      <i class="fe fe-alert-circle me-2"></i>{{ error }}
    </div>

    <!-- Content -->
    <div v-else-if="expense" class="row">
      <!-- Main Information -->
      <div class="col-lg-9">
        <div class="card">
          <div class="card-header">
            <h5 class="card-title mb-0">Thông tin chi phí</h5>
          </div>
          <div class="card-body">
            <div class="row">
              <div class="col-md-6 mb-3">
                <label class="form-label text-muted">Mô tả chi phí</label>
                <p class="mb-0"><strong>{{ expense.Description }}</strong></p>
              </div>
              <div class="col-md-6 mb-3">
                <label class="form-label text-muted">Số tiền</label>
                <p class="mb-0 text-primary fs-5"><strong>{{ formatCurrency(expense.Amount) }}</strong></p>
              </div>
              <div class="col-md-6 mb-3">
                <label class="form-label text-muted">Danh mục chi phí</label>
                <p class="mb-0">
                  <span class="badge bg-info fs-6">{{ expense.ExpenseCategoryName }}</span>
                </p>
              </div>
              <div class="col-md-6 mb-3">
                <label class="form-label text-muted">Trạng thái</label>
                <p class="mb-0">
                  <ExpenseStatusBadge :status="expense.Status" />
                </p>
              </div>
              <div class="col-12 mb-3" v-if="expense.Note">
                <label class="form-label text-muted">Ghi chú</label>
                <p class="mb-0">{{ expense.Note }}</p>
              </div>
              <div class="col-md-6 mb-3" v-if="expense.TransactionId">
                <label class="form-label text-muted">ID giao dịch</label>
                <p class="mb-0">{{ expense.TransactionId }}</p>
              </div>
              <div class="col-md-6 mb-3" v-if="expense.OrderId">
                <label class="form-label text-muted">ID đơn hàng</label>
                <p class="mb-0">{{ expense.OrderId }}</p>
              </div>
              <div class="col-12 mb-3" v-if="expense.RejectReason">
                <label class="form-label text-muted">Lý do từ chối</label>
                <div class="alert alert-danger">
                  {{ expense.RejectReason }}
                </div>
              </div>

              <!-- Bank Account Information -->
              <div class="col-12" v-if="expense.BankAccountNumber">
                <hr class="my-3" />
                <h6 class="mb-3"><i class="fe fe-credit-card me-2"></i>Thông tin tài khoản ngân hàng</h6>
                <div class="row">
                  <div class="col-md-6 mb-3">
                    <label class="form-label text-muted">Số tài khoản</label>
                    <p class="mb-0"><strong>{{ expense.BankAccountNumber }}</strong></p>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label text-muted">Chủ tài khoản</label>
                    <p class="mb-0">{{ expense.BankAccountHolderName }}</p>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label text-muted">Ngân hàng</label>
                    <p class="mb-0">{{ expense.BankName }} ({{ expense.BankCode }})</p>
                  </div>
                  <div class="col-md-6 mb-3" v-if="expense.BankBranchName">
                    <label class="form-label text-muted">Chi nhánh</label>
                    <p class="mb-0">{{ expense.BankBranchName }}</p>
                  </div>
                </div>
              </div>

              <!-- Additional Information -->
              <div class="col-12">
                <hr class="my-3" />
                <h6 class="mb-3"><i class="fe fe-info me-2"></i>Thông tin bổ sung</h6>
                <div class="row">
                  <div class="col-md-3 mb-3">
                    <label class="form-label text-muted">Người tạo</label>
                    <p class="mb-0">{{ expense.CreatedByUserName || '-' }}</p>
                  </div>
                  <div class="col-md-3 mb-3">
                    <label class="form-label text-muted">Ngày tạo</label>
                    <p class="mb-0">{{ formatDateTime(expense.CreatedTime) }}</p>
                  </div>
                  <div class="col-md-3 mb-3">
                    <label class="form-label text-muted">Người cập nhật</label>
                    <p class="mb-0">{{ expense.UpdatedByUserName || '-' }}</p>
                  </div>
                  <div class="col-md-3 mb-3">
                    <label class="form-label text-muted">Ngày cập nhật</label>
                    <p class="mb-0">{{ formatDateTime(expense.UpdatedTime) }}</p>
                  </div>
                  <div class="col-md-3 mb-3" v-if="expense.ApprovedBy">
                    <label class="form-label text-muted">Người phê duyệt</label>
                    <p class="mb-0">{{ expense.ApprovedByUserName }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- History Section -->
      <div class="col-lg-3" v-if="expense && expense.Histories && expense.Histories.length > 0">
        <ExpenseHistory :histories="expense.Histories" />
      </div>
    </div>

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

      <template #body>
        <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="4" 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="closeRejectModal">
            Hủy
          </button>
          <button type="button" class="btn btn-danger" @click="rejectExpense"
            :disabled="!rejectReason.trim() || isUpdating">
            <span v-if="isUpdating" class="spinner-border spinner-border-sm me-2"></span>
            Từ chối
          </button>
        </div>
      </template>
    </LadaDialog>

    <!-- Mark As Paid Modal -->
    <LadaDialog :visible="showMarkAsPaidModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Đánh dấu đã chuyển tiền</h5>
          <button type="button" class="btn-close" @click="closeMarkAsPaidModal"></button>
        </div>
      </template>

      <template #body>
        <div class="mb-3">
          <label class="form-label">Ghi chú về giao dịch</label>
          <textarea class="form-control" v-model="markAsPaidNote" rows="4"
            placeholder="Ví dụ: Đã chuyển qua VCB vào 20/12/2025..."></textarea>
          <small class="text-muted">Ghi chú sẽ được lưu vào lịch sử thay đổi</small>
        </div>
      </template>

      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeMarkAsPaidModal">
            Hủy
          </button>
          <button type="button" class="btn btn-info" @click="markExpenseAsPaid" :disabled="isUpdating">
            <span v-if="isUpdating" class="spinner-border spinner-border-sm me-2"></span>
            <i v-else class="fe fe-dollar-sign me-2"></i>
            Xác nhận đã chuyển tiền
          </button>
        </div>
      </template>
    </LadaDialog>

    <!-- Unapprove Modal -->
    <LadaDialog :visible="showUnapproveModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Bỏ duyệt chi phí</h5>
          <button type="button" class="btn-close" @click="closeUnapproveModal"></button>
        </div>
      </template>

      <template #body>
        <div class="alert alert-warning">
          <i class="fe fe-alert-triangle me-2"></i>
          <strong>Lưu ý:</strong> Chi phí sẽ quay về trạng thái "Chờ duyệt" sau khi bỏ duyệt.
        </div>
        <p>Bạn có chắc chắn muốn bỏ duyệt chi phí <strong>{{ expense?.Description }}</strong>?</p>
        <div class="mb-3">
          <label class="form-label">Lý do bỏ duyệt</label>
          <textarea class="form-control" v-model="unapproveReason" rows="3"
            placeholder="Nhập lý do bỏ duyệt..."></textarea>
          <small class="text-muted">Lý do sẽ được lưu vào lịch sử thay đổi</small>
        </div>
      </template>

      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeUnapproveModal">
            Hủy
          </button>
          <button type="button" class="btn btn-warning" @click="unapproveExpense" :disabled="isUpdating">
            <span v-if="isUpdating" class="spinner-border spinner-border-sm me-2"></span>
            <i v-else class="fe fe-x-circle me-2"></i>
            Xác nhận bỏ duyệt
          </button>
        </div>
      </template>
    </LadaDialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useToast } from 'vue-toastification'
import expenseService from '@/services/expenseService'
import { ExpenseStatusBadge, ExpenseHistory } from './components'

// Router & Toast
const route = useRoute()
const router = useRouter()
const toast = useToast()

// Data
const loading = ref(false)
const error = ref('')
const expense = ref(null)
const isUpdating = ref(false)
const showRejectModal = ref(false)
const rejectReason = ref('')
const showMarkAsPaidModal = ref(false)
const markAsPaidNote = ref('')
const showUnapproveModal = ref(false)
const unapproveReason = ref('')

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

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

// Methods
const loadExpense = async () => {
  try {
    loading.value = true
    error.value = ''

    const expenseId = route.params.id
    if (!expenseId) {
      error.value = 'ID chi phí không hợp lệ'
      return
    }

    const result = await expenseService.getById(expenseId)
    if (result) {
      expense.value = result
    } else {
      error.value = 'Không tìm thấy chi phí'
    }
  } catch (err) {
    console.error('Error loading expense:', err)
    error.value = 'Có lỗi xảy ra khi tải thông tin chi phí'
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.push('/quan-ly-chi-phi')
}

const editExpense = () => {
  router.push(`/quan-ly-chi-phi/chinh-sua/${expense.value.Id}`)
}

const approveExpense = async () => {
  try {
    isUpdating.value = true

    const result = await expenseService.approve(expense.value.Id)

    if (result.Result === 1) {
      toast.success('Phê duyệt chi phí thành công')
      loadExpense() // Reload to get updated data
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi phê duyệt')
    }
  } catch (error) {
    console.error('Error approving expense:', error)
    toast.error('Có lỗi xảy ra khi phê duyệt chi phí')
  } finally {
    isUpdating.value = false
  }
}

const openRejectModal = () => {
  rejectReason.value = ''
  showRejectModal.value = true
}

const closeRejectModal = () => {
  showRejectModal.value = false
  rejectReason.value = ''
}

const rejectExpense = async () => {
  try {
    isUpdating.value = true

    const result = await expenseService.reject(expense.value.Id, rejectReason.value.trim())

    if (result.Result === 1) {
      toast.success('Từ chối chi phí thành công')
      closeRejectModal()
      loadExpense() // Reload to get updated data
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi từ chối')
    }
  } catch (error) {
    console.error('Error rejecting expense:', error)
    toast.error('Có lỗi xảy ra khi từ chối chi phí')
  } finally {
    isUpdating.value = false
  }
}

const openMarkAsPaidModal = () => {
  markAsPaidNote.value = ''
  showMarkAsPaidModal.value = true
}

const closeMarkAsPaidModal = () => {
  showMarkAsPaidModal.value = false
  markAsPaidNote.value = ''
}

const markExpenseAsPaid = async () => {
  try {
    isUpdating.value = true

    const result = await expenseService.markAsPaid(
      expense.value.Id,
      markAsPaidNote.value.trim() || 'Đã chuyển tiền'
    )

    if (result.Result === 1) {
      toast.success(result.Message || 'Đánh dấu đã chuyển tiền thành công')
      closeMarkAsPaidModal()
      loadExpense() // Reload to get updated data
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi đánh dấu')
    }
  } catch (error) {
    console.error('Error marking expense as paid:', error)
    toast.error('Có lỗi xảy ra khi đánh dấu đã chuyển tiền')
  } finally {
    isUpdating.value = false
  }
}

const openUnapproveModal = () => {
  unapproveReason.value = ''
  showUnapproveModal.value = true
}

const closeUnapproveModal = () => {
  showUnapproveModal.value = false
  unapproveReason.value = ''
}

const unapproveExpense = async () => {
  try {
    isUpdating.value = true

    const result = await expenseService.unapprove(
      expense.value.Id,
      unapproveReason.value.trim() || 'Bỏ duyệt'
    )

    if (result.Result === 1) {
      toast.success(result.Message || 'Bỏ duyệt chi phí thành công')
      closeUnapproveModal()
      loadExpense() // Reload to get updated data
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi bỏ duyệt')
    }
  } catch (error) {
    console.error('Error unapproving expense:', error)
    toast.error('Có lỗi xảy ra khi bỏ duyệt chi phí')
  } finally {
    isUpdating.value = false
  }
}

// Lifecycle
onMounted(() => {
  loadExpense()
})
</script>

<style scoped>
.expense-detail-page {
  padding: 1rem;
}

.form-label {
  font-size: 0.875rem;
  font-weight: 500;
  margin-bottom: 0.25rem;
}

.text-muted {
  color: #6c757d !important;
}

.text-primary {
  color: #0d6efd !important;
}

.fs-5 {
  font-size: 1.25rem !important;
}

.fs-6 {
  font-size: 1rem !important;
}

.alert {
  padding: 0.75rem 1rem;
  margin-bottom: 0;
  border: 1px solid transparent;
  border-radius: 0.375rem;
}

.alert-danger {
  color: #721c24;
  background-color: #f8d7da;
  border-color: #f5c6cb;
}
</style>
