<template>
    <div class="receive-vehicle-container">
        <div class="row">
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">
                            <i class="fas fa-truck text-primary me-2"></i>
                            Nhận Xe
                        </h5>
                    </div>
                    <div class="card-body">
                        <!-- Loading state -->
                        <div v-if="loadingCurrentTruck" class="text-center">
                            <div class="spinner-border spinner-border-sm" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2">Đang kiểm tra xe hiện tại...</p>
                        </div>

                        <!-- Already has truck assigned -->
                        <div v-else-if="currentTruck" class="text-center">
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle fa-2x text-warning mb-3"></i>
                                <h5 class="text-warning">Bạn đã phụ trách xe tải!</h5>
                                <p class="mb-3">Hiện tại bạn đang phụ trách xe: <strong>{{ currentTruck.LicensePlate
                                }}</strong></p>
                                <p class="mb-3">Bạn cần trả xe hiện tại trước khi có thể nhận xe mới.</p>
                                <div class="mt-3">
                                    <button type="button" class="btn btn-warning" @click="goToReturnVehicle">
                                        <i class="fas fa-undo me-2"></i>
                                        Đi đến trang Trả xe
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Receive vehicle form -->
                        <form v-else @submit.prevent="handleReceiveVehicle">
                            <!-- Chọn xe -->
                            <div class="form-group mb-3">
                                <label class="form-label">Chọn xe <span class="text-danger">*</span></label>
                                <select class="form-control" v-model="selectedTruck" @change="onTruckChange" required>
                                    <option value="">-- Chọn xe --</option>
                                    <option v-for="truck in availableTrucks" :key="truck.Id" :value="truck">
                                        {{ truck.LicensePlate }} - {{ truck.AgencyName }}
                                    </option>
                                </select>
                            </div>

                            <!-- Thông tin xe đã chọn -->
                            <div v-if="selectedTruck" class="alert alert-info mb-3">
                                <h6>Thông tin xe đã chọn:</h6>
                                <div class="row">
                                    <div class="col-md-6">
                                        <strong>Biển số:</strong> {{ selectedTruck.LicensePlate }}
                                    </div>
                                    <div class="col-md-6">
                                        <strong>Công ty:</strong> {{ selectedTruck.AgencyName }}
                                    </div>
                                </div>
                                <div class="row mt-2">
                                    <div class="col-md-6">
                                        <strong>Trạng thái hoạt động:</strong>
                                        <span class="badge"
                                            :class="getOperatingStatusClass(selectedTruck.OperatingStatus)">
                                            {{ selectedTruck.OperatingStatusStr }}
                                        </span>
                                    </div>
                                    <div class="col-md-6">
                                        <strong>Trạng thái:</strong>
                                        <span class="badge" :class="getStatusClass(selectedTruck.Status)">
                                            {{ selectedTruck.StatusStr }}
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <!-- Upload ảnh -->
                            <div class="form-group mb-3">
                                <label class="form-label">Ảnh khi nhận xe <span class="text-danger">*</span></label>
                                <div class="upload-area" @click="triggerFileInput" @dragover.prevent
                                    @drop.prevent="handleDrop">
                                    <input ref="fileInput" type="file" multiple accept="image/*"
                                        @change="handleFileSelect" style="display: none;" />
                                    <div class="upload-content">
                                        <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                                        <p class="mb-2">Kéo thả ảnh vào đây hoặc click để chọn</p>
                                        <small class="text-muted">Hỗ trợ: JPG, PNG, GIF (Tối đa 10 ảnh)</small>
                                    </div>
                                </div>
                            </div>

                            <!-- Preview ảnh đã chọn -->
                            <div v-if="selectedImages.length > 0" class="form-group mb-3">
                                <label class="form-label">Ảnh đã chọn ({{ selectedImages.length }})</label>
                                <div class="image-preview-container">
                                    <div v-for="(image, index) in selectedImages" :key="index"
                                        class="image-preview-item">
                                        <img :src="image.preview" :alt="`Ảnh ${index + 1}`" />
                                        <button type="button" class="remove-image-btn" @click="removeImage(index)">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- Ghi chú -->
                            <div class="form-group mb-3">
                                <label class="form-label">Ghi chú</label>
                                <textarea class="form-control" rows="3" v-model="notes"
                                    placeholder="Ghi chú về tình trạng xe khi nhận"></textarea>
                            </div>

                            <!-- Buttons -->
                            <div class="form-group">
                                <button type="submit" class="btn btn-primary me-2"
                                    :disabled="loading || !selectedTruck || selectedImages.length === 0">
                                    <i class="fas fa-check me-2"></i>
                                    {{ loading ? 'Đang xử lý...' : 'Nhận xe' }}
                                </button>
                                <button type="button" class="btn btn-secondary" @click="resetForm">
                                    <i class="fas fa-undo me-2"></i>
                                    Làm mới
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="card">
                    <div class="card-header">
                        <h6 class="card-title">
                            <i class="fas fa-info-circle text-info me-2"></i>
                            Hướng dẫn nhận xe
                        </h6>
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled">
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success me-2"></i>
                                Chọn xe từ danh sách xe có sẵn
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success me-2"></i>
                                Chụp ảnh tình trạng xe khi nhận
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success me-2"></i>
                                Kiểm tra kỹ trước khi xác nhận nhận xe
                            </li>
                        </ul>
                    </div>
                </div>

                <div class="card mt-3">
                    <div class="card-header">
                        <h6 class="card-title">
                            <i class="fas fa-truck text-warning me-2"></i>
                            Danh sách xe có sẵn
                        </h6>
                    </div>
                    <div class="card-body">
                        <div v-if="loadingTrucks" class="text-center">
                            <div class="spinner-border spinner-border-sm" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2">Đang tải danh sách xe...</p>
                        </div>
                        <div v-else-if="availableTrucks.length === 0" class="text-muted text-center">
                            <i class="fas fa-truck fa-2x mb-2"></i>
                            <p>Không có xe nào khả dụng</p>
                        </div>
                        <div v-else>
                            <div v-for="truck in availableTrucks" :key="truck.Id" class="border-bottom pb-2 mb-2">
                                <div class="d-flex justify-content-between">
                                    <strong>{{ truck.LicensePlate }}</strong>
                                    <span class="badge" :class="getOperatingStatusClass(truck.OperatingStatus)">
                                        {{ truck.OperatingStatusStr }}
                                    </span>
                                </div>
                                <small class="text-muted">{{ truck.AgencyName }}</small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Current truck info -->
                <div v-if="currentTruck" class="card mt-3">
                    <div class="card-header">
                        <h6 class="card-title">
                            <i class="fas fa-truck text-info me-2"></i>
                            Xe hiện tại đang phụ trách
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="border-bottom pb-2 mb-2">
                            <div class="d-flex justify-content-between">
                                <strong>{{ currentTruck.LicensePlate }}</strong>
                                <span class="badge" :class="getOperatingStatusClass(currentTruck.OperatingStatus)">
                                    {{ currentTruck.OperatingStatusStr }}
                                </span>
                            </div>
                            <small class="text-muted">{{ currentTruck.AgencyName }}</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import truckService from '@/services/truckService';
import { useToast } from "vue-toastification";

const toast = useToast();

const loading = ref(false);
const loadingTrucks = ref(false);
const loadingCurrentTruck = ref(false);
const selectedTruck = ref(null);
const selectedImages = ref([]);
const notes = ref('');
const availableTrucks = ref([]);
const currentTruck = ref(null);

// File input reference
const fileInput = ref(null);

// Load data on component mount
onMounted(async () => {
    await Promise.all([
        loadCurrentTruck(),
        loadAvailableTrucks()
    ]);
});

// Load current truck from API
const loadCurrentTruck = async () => {
    loadingCurrentTruck.value = true;
    try {
        const result = await truckService.getMyCurrentTruck();

        if (result != null && result.Result === 1 && result.Items && result.Items.length > 0) {
            currentTruck.value = result.Items[0];
        } else {
            currentTruck.value = null;
        }
    } catch (error) {
        console.error('Error loading current truck:', error);
        currentTruck.value = null;
    } finally {
        loadingCurrentTruck.value = false;
    }
};

// Load available trucks from API
const loadAvailableTrucks = async () => {
    loadingTrucks.value = true;
    try {
        const result = await truckService.getAvailableTrucks();

        // Kiểm tra các cấu trúc response có thể có
        let trucks = [];
        if (result != null) {
            if (Array.isArray(result)) {
                trucks = result;
            } else if (result.Items && Array.isArray(result.Items)) {
                trucks = result.Items;
            } else if (result.Data && Array.isArray(result.Data)) {
                trucks = result.Data;
            } else if (result.Result && Array.isArray(result.Result)) {
                trucks = result.Result;
            }
        }

        availableTrucks.value = trucks;
    } catch (error) {
        console.error('Error loading trucks:', error);
        availableTrucks.value = [];
    } finally {
        loadingTrucks.value = false;
    }
};

// Navigate to return vehicle tab
const goToReturnVehicle = () => {
    // Emit event để parent component chuyển tab
    // Hoặc sử dụng router nếu cần
    toast.info('Vui lòng chuyển sang tab "Trả xe" để trả xe hiện tại');
};

// Handle truck selection change
const onTruckChange = () => {
    // Reset images when truck changes
    selectedImages.value = [];
};

// Trigger file input click
const triggerFileInput = () => {
    fileInput.value.click();
};

// Handle file selection
const handleFileSelect = (event) => {
    const files = Array.from(event.target.files);
    addFiles(files);
};

// Handle drag and drop
const handleDrop = (event) => {
    const files = Array.from(event.dataTransfer.files);
    addFiles(files);
};

// Add files to selected images
const addFiles = (files) => {
    const imageFiles = files.filter(file => file.type.startsWith('image/'));

    if (selectedImages.value.length + imageFiles.length > 10) {
        toast.warning('Tối đa chỉ được chọn 10 ảnh!');
        return;
    }

    imageFiles.forEach(file => {
        const reader = new FileReader();
        reader.onload = (e) => {
            selectedImages.value.push({
                file: file,
                preview: e.target.result,
                name: file.name
            });
        };
        reader.readAsDataURL(file);
    });
};

// Remove image from selection
const removeImage = (index) => {
    selectedImages.value.splice(index, 1);
};

// Handle form submission
const handleReceiveVehicle = async () => {
    if (!selectedTruck.value || selectedImages.value.length === 0) {
        toast.warning('Vui lòng chọn xe và upload ít nhất 1 ảnh!');
        return;
    }

    loading.value = true;

    try {
        // Create FormData for multipart/form-data
        const formData = new FormData();

        // Add truck data
        formData.append('TruckId', selectedTruck.value.Id);
        formData.append('Note', notes.value);

        // Add images
        selectedImages.value.forEach((image, index) => {
            formData.append(`Files`, image.file);
        });

        // Send request using service
        const result = await truckService.checkInTruck(formData);

        if (result != null && result.Result === 1) {
            toast.success('Nhận xe thành công!');
            resetForm();
            // Reload current truck info after successful check-in
            await loadCurrentTruck();
        } else {
            toast.error('Thất bại: ' + (result?.Message || 'Có lỗi xảy ra'));
        }
    } catch (error) {
        console.error('Error receiving vehicle:', error);
        toast.error('Có lỗi xảy ra khi nhận xe!');
    } finally {
        loading.value = false;
    }
};

// Get badge class for operating status
const getOperatingStatusClass = (status) => {
    const classes = {
        0: 'bg-secondary', // Không xác định
        1: 'bg-success',   // Đang Dừng / Đỗ
        2: 'bg-warning',   // Đang hoạt động
        3: 'bg-danger'     // Bảo trì
    };
    return classes[status] || 'bg-secondary';
};

// Get badge class for status
const getStatusClass = (status) => {
    const classes = {
        0: 'bg-secondary', // Không có mô tả
        1: 'bg-success',   // Hoạt động
        2: 'bg-warning',   // Tạm dừng
        3: 'bg-danger'     // Khóa
    };
    return classes[status] || 'bg-secondary';
};

// Reset form
const resetForm = () => {
    selectedTruck.value = null;
    selectedImages.value = [];
    notes.value = '';
    if (fileInput.value) {
        fileInput.value.value = '';
    }
};
</script>

<style scoped>
.receive-vehicle-container {
    padding: 20px 0;
}

.card {
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    border: 1px solid rgba(0, 0, 0, 0.125);
}

.card-header {
    background-color: #f8f9fa;
    border-bottom: 1px solid rgba(0, 0, 0, 0.125);
}

.form-label {
    font-weight: 500;
    color: #495057;
}

.btn {
    border-radius: 0.375rem;
}

.btn:disabled {
    opacity: 0.65;
}

.upload-area {
    border: 2px dashed #dee2e6;
    border-radius: 0.375rem;
    padding: 40px 20px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    background-color: #f8f9fa;
}

.upload-area:hover {
    border-color: #007bff;
    background-color: #e7f3ff;
}

.upload-content {
    color: #6c757d;
}

.image-preview-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 10px;
    margin-top: 10px;
}

.image-preview-item {
    position: relative;
    border: 1px solid #dee2e6;
    border-radius: 0.375rem;
    overflow: hidden;
}

.image-preview-item img {
    width: 100%;
    height: 100px;
    object-fit: cover;
    display: block;
}

.remove-image-btn {
    position: absolute;
    top: 5px;
    right: 5px;
    background: rgba(220, 53, 69, 0.9);
    color: white;
    border: none;
    border-radius: 50%;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 12px;
}

.remove-image-btn:hover {
    background: rgba(220, 53, 69, 1);
}

.badge {
    font-size: 0.75em;
}

.alert {
    border-radius: 0.375rem;
}
</style>