<template>
    <div>
        <LadaDialog v-model="showCollectMoneyModal" title="Nhận tiền">
            <template #content>
                <div class="p-4">
                    <!-- Số tiền đang giữ (hiện có) -->
                    <div class="mb-4 p-3 bg-blue-50 rounded-md">
                        <h4 class="text-sm font-semibold text-gray-700 mb-2">Số tiền đang giữ</h4>
                        <div class="grid grid-cols-3 gap-2 text-xs">
                            <div>
                                <span class="text-gray-600">COD:</span>
                                <span class="font-medium ml-1">{{ formatMoney(cashierData.CodAmount) }}</span>
                            </div>
                            <div>
                                <span class="text-gray-600">Phí lấy:</span>
                                <span class="font-medium ml-1">{{ formatMoney(cashierData.SourceFeeAmount) }}</span>
                            </div>
                            <div>
                                <span class="text-gray-600">Phí giao:</span>
                                <span class="font-medium ml-1">{{ formatMoney(cashierData.DestFeeAmount) }}</span>
                            </div>
                        </div>
                    </div>

                    <!-- Số tiền dự kiến (đang trên đường) -->
                    <div class="mb-4 p-3 bg-amber-50 rounded-md">
                        <h4 class="text-sm font-semibold text-gray-700 mb-2">Số tiền dự kiến (đang trên đường)</h4>
                        <div class="grid grid-cols-3 gap-2 text-xs">
                            <div>
                                <span class="text-gray-600">COD:</span>
                                <span class="font-medium ml-1">{{ formatMoney(cashierData.ExpectedCodAmount) }}</span>
                            </div>
                            <div>
                                <span class="text-gray-600">Phí lấy:</span>
                                <span class="font-medium ml-1">{{ formatMoney(cashierData.ExpectedSourceFeeAmount)
                                    }}</span>
                            </div>
                            <div>
                                <span class="text-gray-600">Phí giao:</span>
                                <span class="font-medium ml-1">{{ formatMoney(cashierData.ExpectedDestFeeAmount)
                                    }}</span>
                            </div>
                        </div>
                    </div>

                    <!-- Form thu tiền -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700">Tiền mặt (Cash)</label>
                        <input type="number" v-model.number="collectMoneyForm.CashAmount"
                            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" />
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700">Chuyển khoản (Transfer)</label>
                        <input type="number" v-model.number="collectMoneyForm.TransferAmount"
                            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" />
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700">Tổng tiền nộp</label>
                        <input type="number" :value="totalAmountCalculated" disabled
                            class="mt-1 block w-full rounded-md border-gray-100 bg-gray-50 shadow-sm" />
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700">Ghi chú</label>
                        <textarea v-model="collectMoneyForm.Note"
                            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                            rows="2"></textarea>
                    </div>
                    <div v-if="collectMoneyForm.OrderList?.length > 0" class="mt-4">
                        <p class="text-xs text-gray-500">Thu cho {{ collectMoneyForm.OrderList.length }} đơn hàng</p>
                    </div>
                </div>
            </template>
            <template #footer>
                <div class="flex justify-end space-x-2">
                    <button @click="showCollectMoneyModal = false"
                        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50">
                        Hủy
                    </button>
                    <button @click="handleCollectMoney"
                        class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 border border-transparent rounded-md hover:bg-indigo-700">
                        Nhận tiền
                    </button>
                </div>
            </template>
        </LadaDialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            showCollectMoneyModal: false,
            cashierData: {
                CodAmount: 0,
                SourceFeeAmount: 0,
                DestFeeAmount: 0,
                ExpectedCodAmount: 0,
                ExpectedSourceFeeAmount: 0,
                ExpectedDestFeeAmount: 0
            },
            collectMoneyForm: {
                FromUserId: null,
                CashAmount: 0,
                TransferAmount: 0,
                TotalAmount: 0,
                Note: '',
                OrderList: []
            }
        }
    },
    computed: {
        totalAmountCalculated() {
            return (this.collectMoneyForm.CashAmount || 0) + (this.collectMoneyForm.TransferAmount || 0)
        }
    },
    methods: {
        formatMoney(amount) {
            return new Intl.NumberFormat('vi-VN').format(amount || 0)
        },
        /**
         * @param {Object} cashierItem Item from /api/Cashier/Search
         */
        openCollectMoneyModal(cashierItem) {
            const totalToCollect = (cashierItem.CodAmount || 0) + (cashierItem.SourceFeeAmount || 0) + (cashierItem.DestFeeAmount || 0)

            // Calculate expected amounts from OrderList
            let expectedCod = 0
            let expectedSourceFee = 0
            let expectedDestFee = 0

            if (cashierItem.OrderList && cashierItem.OrderList.length > 0) {
                cashierItem.OrderList.forEach(order => {
                    expectedCod += order.ExpectedCod || 0
                    expectedSourceFee += order.ExpectedSourceFee || 0
                    expectedDestFee += order.ExpectedDestFee || 0
                })
            }

            // Store cashier data for display
            this.cashierData = {
                CodAmount: cashierItem.CodAmount || 0,
                SourceFeeAmount: cashierItem.SourceFeeAmount || 0,
                DestFeeAmount: cashierItem.DestFeeAmount || 0,
                ExpectedCodAmount: expectedCod,
                ExpectedSourceFeeAmount: expectedSourceFee,
                ExpectedDestFeeAmount: expectedDestFee
            }

            this.collectMoneyForm = {
                FromUserId: cashierItem.Id,
                CashAmount: totalToCollect,
                TransferAmount: 0,
                TotalAmount: totalToCollect,
                Note: '',
                OrderList: (cashierItem.OrderList || []).map(o => ({
                    Id: o.Id,
                    CodAmount: o.CodAmount || 0,
                    SourceFee: o.SourceFee || 0,
                    DestFee: o.DestFee || 0
                }))
            }
            this.showCollectMoneyModal = true
        },


        async handleCollectMoney() {
            try {
                this.collectMoneyForm.TotalAmount = this.totalAmountCalculated

                const response = await this.$axios.post('/api/Cashier/Collect', this.collectMoneyForm)
                if (response.data?.Result === 1) {
                    this.$toast.success('Nhận tiền thành công')
                    this.showCollectMoneyModal = false
                    this.$emit('success')
                } else {
                    this.$toast.error(response.data?.Message || 'Có lỗi xảy ra')
                }
            } catch (error) {
                this.$toast.error(error.response?.data?.Message || 'Có lỗi xảy ra')
            }
        }
    }
}
</script>