<template>
    <div class="tax-invoice-section">
        <div class="section-divider"></div>
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="section-title mb-0">Hóa đơn thuế</h6>
            <div class="d-flex gap-2">
                <!-- Create Invoice Button -->
                <button v-if="!taxInvoice && canCreate" type="button" class="btn btn-sm btn-primary"
                    @click="openCreateModal" :disabled="processing">
                    <span v-if="processing && action === 'create'" class="spinner-border spinner-border-sm me-1"></span>
                    <i v-else class="fe fe-plus me-1"></i>
                    Tạo hóa đơn
                </button>

                <!-- Update Status Button -->
                <button v-if="taxInvoice && canUpdate" type="button" class="btn btn-sm btn-info"
                    @click="openUpdateModal" :disabled="processing">
                    <span v-if="processing && action === 'update'" class="spinner-border spinner-border-sm me-1"></span>
                    <i v-else class="fe fe-edit me-1"></i>
                    Cập nhật trạng thái
                </button>

                <!-- Delete Invoice Button -->
                <button v-if="taxInvoice && canDelete" type="button" class="btn btn-sm btn-outline-danger"
                    @click="handleDelete" :disabled="processing">
                    <span v-if="processing && action === 'delete'" class="spinner-border spinner-border-sm me-1"></span>
                    <i v-else class="fe fe-trash-2 me-1"></i>
                    Xóa
                </button>
            </div>
        </div>

        <!-- Tax Invoice Info -->
        <div v-if="taxInvoice" class="tax-invoice-info">
            <div class="row g-4">
                <!-- Invoice Number -->
                <div class="col-md-4">
                    <div class="info-item">
                        <label class="info-label">Số hóa đơn</label>
                        <p class="info-value mb-0">{{ taxInvoice.InvoiceNumber || '-' }}</p>
                    </div>
                </div>

                <!-- Invoice Date -->
                <div class="col-md-4">
                    <div class="info-item">
                        <label class="info-label">Ngày xuất</label>
                        <p class="info-value mb-0">{{ taxInvoice.InvoiceDate ? formatDate(taxInvoice.InvoiceDate) : '-'
                            }}</p>
                    </div>
                </div>

                <!-- Status -->
                <div class="col-md-4">
                    <div class="info-item">
                        <label class="info-label">Trạng thái</label>
                        <span :class="getStatusBadgeClass(taxInvoice.Status)">
                            {{ taxInvoice.StatusName }}
                        </span>
                    </div>
                </div>

                <!-- Company Info -->
                <div class="col-md-6">
                    <div class="info-item">
                        <label class="info-label">Công ty</label>
                        <p class="info-value fw-medium mb-0">{{ taxInvoice.CompanyName }}</p>
                        <p class="info-meta">MST: {{ taxInvoice.TaxCode }}</p>
                    </div>
                </div>

                <!-- Email -->
                <div class="col-md-6">
                    <div class="info-item">
                        <label class="info-label">Email hóa đơn</label>
                        <p class="info-value mb-0">{{ taxInvoice.InvoiceEmail }}</p>
                    </div>
                </div>

                <!-- Address -->
                <div class="col-12">
                    <div class="info-item">
                        <label class="info-label">Địa chỉ</label>
                        <p class="info-value mb-0">{{ taxInvoice.Address }}</p>
                    </div>
                </div>

                <!-- Financial Info -->
                <div class="col-md-4">
                    <div class="info-item">
                        <label class="info-label">Tổng tiền</label>
                        <p class="info-amount">{{ formatCurrency(taxInvoice.TotalAmount) }}</p>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="info-item">
                        <label class="info-label">VAT ({{ taxInvoice.VatRate }}%)</label>
                        <p class="info-amount">{{ formatCurrency(taxInvoice.VatAmount) }}</p>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="info-item">
                        <label class="info-label">Tổng cộng</label>
                        <p class="info-amount text-brand-red">{{ formatCurrency(taxInvoice.TotalAmountIncludingVat) }}
                        </p>
                    </div>
                </div>

                <!-- PDF Download -->
                <div class="col-12" v-if="taxInvoice.PdfUrl">
                    <a :href="taxInvoice.PdfUrl" target="_blank" class="btn btn-outline-primary btn-sm">
                        <i class="fe fe-file-text me-2"></i>Xem hóa đơn PDF
                    </a>
                </div>

                <!-- Note -->
                <div class="col-12" v-if="taxInvoice.Note">
                    <div class="info-item">
                        <label class="info-label">Ghi chú</label>
                        <p class="info-value mb-0">{{ taxInvoice.Note }}</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- No Invoice Message -->
        <div v-else class="alert alert-info mb-0">
            <i class="fe fe-info me-2"></i>
            Phiếu đối soát này chưa có hóa đơn thuế. Nhấn "Tạo hóa đơn" để tạo hóa đơn mới.
        </div>

        <!-- Create Tax Invoice Modal -->
        <LadaDialog :visible="showCreateModal">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Tạo hóa đơn thuế</h5>
                    <button @click="closeCreateModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <div class="modal-body">
                    <!-- Customer Info -->
                    <div class="mb-3" v-if="customerInfo">
                        <label class="form-label">Khách hàng:</label>
                        <div>
                            <router-link :to="{ name: 'crm-customer-detail', params: { id: customerInfo.id } }"
                                target="_blank" class="fw-medium text-primary">
                                <i class="fe fe-external-link me-1"></i>
                                {{ customerInfo.name }}
                            </router-link>
                            <div class="text-muted small">{{ customerInfo.phone }}</div>
                        </div>
                    </div>

                    <!-- VAT Info Selection -->
                    <div class="mb-3">
                        <label class="form-label">Thông tin VAT: <span class="text-danger">*</span></label>
                        <div class="d-flex gap-2">
                            <v-select label="CompanyName" :options="vatInfoOptions" v-model="selectedVatInfoId"
                                :reduce="(option) => option.Id" placeholder="Chọn thông tin VAT..."
                                :loading="loadingVatInfo" class="flex-grow-1">
                                <template #option="option">
                                    <div>
                                        <strong>{{ option.CompanyName }}</strong>
                                        <br>
                                        <small class="text-muted">{{ option.TaxCode }} - {{ option.InvoiceEmail
                                            }}</small>
                                    </div>
                                </template>
                                <template #selected-option="option">
                                    <div>
                                        <strong>{{ option.CompanyName }}</strong>
                                        <br>
                                        <small class="text-muted">{{ option.TaxCode }}</small>
                                    </div>
                                </template>
                            </v-select>
                            <button type="button" class="btn btn-outline-primary btn-sm" @click="openVatModal"
                                :disabled="!customerInfo" title="Tạo thông tin VAT mới">
                                <i class="fe fe-plus"></i>
                            </button>
                        </div>
                        <small class="text-muted" v-if="!selectedVatInfoId">
                            Vui lòng chọn thông tin VAT để tiếp tục
                        </small>
                        <small class="text-info d-block mt-1"
                            v-if="vatInfoOptions.length === 0 && !loadingVatInfo && customerInfo">
                            Khách hàng chưa có thông tin VAT. <a href="#" @click.prevent="openVatModal">Tạo mới</a>
                        </small>
                    </div>

                    <!-- Note -->
                    <div class="mb-3">
                        <label class="form-label">Ghi chú:</label>
                        <textarea v-model="note" class="form-control" rows="3"
                            placeholder="Nhập ghi chú cho hóa đơn (tùy chọn)" maxlength="2048"></textarea>
                        <small class="text-muted">Tối đa 2048 ký tự</small>
                    </div>
                </div>
            </template>
            <template #footer>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" @click="closeCreateModal" :disabled="processing">
                        Hủy
                    </button>
                    <button type="button" class="btn btn-primary" @click="submitCreate"
                        :disabled="processing || !selectedVatInfoId">
                        <span v-if="processing" class="spinner-border spinner-border-sm me-1"></span>
                        <i v-else class="fe fe-check me-1"></i>
                        Tạo hóa đơn
                    </button>
                </div>
            </template>
        </LadaDialog>

        <!-- Update Tax Invoice Status Modal -->
        <LadaDialog :visible="showUpdateModal">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Cập nhật trạng thái hóa đơn</h5>
                    <button @click="closeUpdateModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Trạng thái: <span class="text-danger">*</span></label>
                        <select v-model="updateStatus" class="form-select">
                            <option value="">-- Chọn trạng thái --</option>
                            <option value="2">Nháp</option>
                            <option value="3">Đã xuất</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Số hóa đơn: <span class="text-danger">*</span></label>
                        <input type="text" v-model="updateInvoiceNumber" class="form-control"
                            placeholder="Nhập số hóa đơn" maxlength="50">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Ngày xuất hóa đơn: <span class="text-danger">*</span></label>
                        <input type="date" v-model="updateInvoiceDate" class="form-control">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">File PDF hóa đơn: <span class="text-danger">*</span></label>
                        <input type="file" @change="handlePdfFileChange" class="form-control" accept="application/pdf">
                        <small class="text-muted">Chỉ chấp nhận file PDF</small>
                    </div>
                </div>
            </template>
            <template #footer>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" @click="closeUpdateModal" :disabled="processing">
                        Hủy
                    </button>
                    <button type="button" class="btn btn-primary" @click="submitUpdate"
                        :disabled="processing || !updateStatus || !updateInvoiceNumber || !updateInvoiceDate || !selectedPdfFile">
                        <span v-if="processing" class="spinner-border spinner-border-sm me-1"></span>
                        <i v-else class="fe fe-save me-1"></i>
                        Cập nhật
                    </button>
                </div>
            </template>
        </LadaDialog>

        <!-- Create VAT Info Modal -->
        <LadaDialog :visible="showVatModal">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Tạo thông tin VAT mới</h5>
                    <button @click="closeVatModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <CreateOrUpdateVatInfo :id="0" :customerId="customerInfo?.id" @cancel="closeVatModal"
                    @success="onVatCreated" />
            </template>
        </LadaDialog>
    </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useToast } from 'vue-toastification'
import taxService from '@/services/taxService'
import vatInfoService from '@/services/vatInfoService'
import CreateOrUpdateVatInfo from '@/views/crm/customer/detail/components/CreateOrUpdateVatInfo.vue'

const props = defineProps({
    slipId: {
        type: Number,
        required: true
    },
    customerInfo: {
        type: Object,
        required: true,
        validator: (value) => {
            return value && typeof value.id === 'number' && value.name && value.phone
        }
    },
    canCreate: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['refresh'])

const toast = useToast()

// State
const taxInvoice = ref(null)
const processing = ref(false)
const action = ref('')

// VAT Info
const vatInfoOptions = ref([])
const loadingVatInfo = ref(false)
const selectedVatInfoId = ref(null)

// Modals
const showCreateModal = ref(false)
const showUpdateModal = ref(false)
const showVatModal = ref(false)

// Create form
const note = ref('')

// Update form
const updateStatus = ref('')
const updateInvoiceNumber = ref('')
const updateInvoiceDate = ref('')
const selectedPdfFile = ref(null)

// Computed
const canUpdate = computed(() => {
    // Use canUpdate from API response if available, otherwise fallback to status check
    if (taxInvoice.value?.CanUpdate !== undefined) {
        return taxInvoice.value.CanUpdate
    }
    return taxInvoice.value && (taxInvoice.value.Status === 1 || taxInvoice.value.Status === 2)
})

const canDelete = computed(() => {
    // Use canDelete from API response if available, otherwise fallback to status check
    if (taxInvoice.value?.CanDelete !== undefined) {
        return taxInvoice.value.CanDelete
    }
    return taxInvoice.value && taxInvoice.value.Status === 1
})

// Methods
const formatCurrency = (amount) => {
    if (amount === null || amount === undefined) return '0 ₫'
    return new Intl.NumberFormat('vi-VN', {
        style: 'currency',
        currency: 'VND'
    }).format(amount)
}

const formatDate = (dateString) => {
    if (!dateString) return '-'
    const date = new Date(dateString)
    return date.toLocaleDateString('vi-VN', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric'
    })
}

const getStatusBadgeClass = (status) => {
    const classMap = {
        1: 'badge badge-status bg-secondary-light text-secondary', // NotIssued
        2: 'badge badge-status bg-info-light text-info', // Draft
        3: 'badge badge-status bg-success-light text-success' // Issued
    }
    return classMap[status] || 'badge badge-status bg-secondary-light text-secondary'
}

const loadTaxInvoice = async () => {
    try {
        console.log('Loading tax invoice for slipId:', props.slipId)
        const invoice = await taxService.getTaxInvoiceBySlipId(props.slipId)
        console.log('Tax invoice loaded:', invoice)
        taxInvoice.value = invoice
    } catch (error) {
        console.error('Error loading tax invoice:', error)
        taxInvoice.value = null
    }
}

const loadVatInfo = async () => {
    if (!props.customerInfo?.id) return

    try {
        loadingVatInfo.value = true
        const result = await vatInfoService.getByCustomerId(props.customerInfo.id)
        vatInfoOptions.value = result || []

        // Auto select default VAT info
        const defaultVat = vatInfoOptions.value.find(vat => vat.IsDefault)
        if (defaultVat) {
            selectedVatInfoId.value = defaultVat.Id
        }
    } catch (error) {
        console.error('Error loading VAT info:', error)
        toast.error('Có lỗi xảy ra khi tải thông tin VAT')
    } finally {
        loadingVatInfo.value = false
    }
}

// Modal handlers
const openCreateModal = async () => {
    await loadVatInfo()
    showCreateModal.value = true
}

const closeCreateModal = () => {
    showCreateModal.value = false
    selectedVatInfoId.value = null
    note.value = ''
}

const openUpdateModal = () => {
    showUpdateModal.value = true
}

const closeUpdateModal = () => {
    showUpdateModal.value = false
    updateStatus.value = ''
    updateInvoiceNumber.value = ''
    updateInvoiceDate.value = ''
    selectedPdfFile.value = null
}

const openVatModal = () => {
    if (!props.customerInfo?.id) {
        toast.error('Vui lòng chọn khách hàng trước')
        return
    }
    showVatModal.value = true
}

const closeVatModal = () => {
    showVatModal.value = false
}

const onVatCreated = async () => {
    closeVatModal()
    await loadVatInfo()
    toast.success('Tạo thông tin VAT thành công!')
}

const handlePdfFileChange = (event) => {
    const file = event.target.files[0]
    if (file) {
        if (file.type !== 'application/pdf') {
            toast.error('Chỉ chấp nhận file PDF')
            event.target.value = ''
            selectedPdfFile.value = null
            return
        }
        selectedPdfFile.value = file
    } else {
        selectedPdfFile.value = null
    }
}

// Actions
const submitCreate = async () => {
    if (!selectedVatInfoId.value) {
        toast.warning('Vui lòng chọn thông tin VAT')
        return
    }

    processing.value = true
    action.value = 'create'

    try {
        const result = await taxService.createTaxInvoice({
            CustomerReconciliationSlipId: props.slipId,
            VatInfoId: selectedVatInfoId.value,
            Note: note.value.trim()
        })

        if (result && result.Result === 1) {
            toast.success(result.Message || 'Tạo hóa đơn thuế thành công')
            closeCreateModal()
            await loadTaxInvoice()
            emit('refresh')
        } else {
            toast.error(result?.Message || 'Có lỗi xảy ra khi tạo hóa đơn thuế')
        }
    } catch (error) {
        console.error('Error creating tax invoice:', error)
        toast.error(error.response?.data?.Message || error.response?.data?.detail || 'Có lỗi xảy ra khi tạo hóa đơn thuế')
    } finally {
        processing.value = false
        action.value = ''
    }
}

const submitUpdate = async () => {
    if (!updateStatus.value || !updateInvoiceNumber.value || !updateInvoiceDate.value || !selectedPdfFile.value) {
        toast.warning('Vui lòng điền đầy đủ thông tin')
        return
    }

    processing.value = true
    action.value = 'update'

    try {
        const formData = new FormData()
        formData.append('TaxInvoiceId', taxInvoice.value.Id)
        formData.append('Status', parseInt(updateStatus.value))
        formData.append('InvoiceNumber', updateInvoiceNumber.value.trim())
        formData.append('InvoiceDate', new Date(updateInvoiceDate.value).toISOString())
        formData.append('files', selectedPdfFile.value)

        const result = await taxService.updateTaxInvoiceStatus(formData)

        if (result && result.Result === 1) {
            toast.success(result.Message || 'Cập nhật trạng thái hóa đơn thành công')
            closeUpdateModal()
            await loadTaxInvoice()
            emit('refresh')
        } else {
            toast.error(result?.Message || 'Có lỗi xảy ra khi cập nhật trạng thái')
        }
    } catch (error) {
        console.error('Error updating tax invoice status:', error)
        toast.error(error.response?.data?.Message || error.response?.data?.detail || 'Có lỗi xảy ra khi cập nhật trạng thái')
    } finally {
        processing.value = false
        action.value = ''
    }
}

const handleDelete = async () => {
    if (!confirm('Bạn có chắc chắn muốn xóa hóa đơn thuế này? Chỉ có thể xóa hóa đơn ở trạng thái "Chưa xuất".')) {
        return
    }

    processing.value = true
    action.value = 'delete'

    try {
        const result = await taxService.deleteTaxInvoice(taxInvoice.value.Id)
        toast.success(result.Message || 'Xóa hóa đơn thuế thành công')
        taxInvoice.value = null
        emit('refresh')
    } catch (error) {
        console.error('Error deleting tax invoice:', error)
        toast.error(error.response?.data?.Message || error.response?.data?.detail || 'Có lỗi xảy ra khi xóa hóa đơn thuế')
    } finally {
        processing.value = false
        action.value = ''
    }
}

// Watch for slip ID changes
watch(() => props.slipId, () => {
    loadTaxInvoice()
}, { immediate: true })

// Expose methods
defineExpose({
    loadTaxInvoice
})
</script>

<style scoped>
/* Tax Invoice Section */
.tax-invoice-section {
    padding: 0 1.5rem 1.5rem;
}

.tax-invoice-info {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 1.5rem;
}

.section-divider {
    height: 1px;
    background: linear-gradient(to right, #dee2e6 0%, #dee2e6 50%, transparent 50%);
    background-size: 8px 1px;
    margin: 1.5rem 0 1rem;
}

.section-title {
    font-size: 0.9375rem;
    font-weight: 600;
    color: #495057;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.info-item {
    margin-bottom: 0;
}

.info-label {
    font-size: 0.75rem;
    font-weight: 600;
    color: #6c757d;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 0.5rem;
    display: block;
}

.info-value {
    font-size: 0.9375rem;
    color: #212529;
}

.info-meta {
    font-size: 0.875rem;
    color: #6c757d;
    margin-bottom: 0;
    margin-top: 0.25rem;
}

.info-amount {
    font-size: 1.5rem;
    font-weight: 700;
    color: #212529;
    margin-bottom: 0;
}

.text-brand-red {
    color: #EF3636 !important;
}

.badge-status {
    padding: 0.5rem 1rem;
    border-radius: 9999px;
    font-size: 0.875rem;
}

.bg-secondary-light {
    background-color: rgba(108, 117, 125, 0.1);
}

.bg-info-light {
    background-color: rgba(23, 162, 184, 0.1);
}

.bg-success-light {
    background-color: rgba(40, 167, 69, 0.1);
}
</style>
