<template>
    <div class="handover-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-exchange-alt text-primary me-2"></i>
                            Bàn giao xe
                        </h5>
                    </div>
                    <div class="card-body">
                        <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 trạng thái xe...</p>
                        </div>

                        <!-- Nếu chưa nhận xe -->
                        <form v-else-if="!currentTruck" @submit.prevent="handleReceiveVehicle">
                            <div class="alert alert-info mb-3">
                                <i class="fas fa-info-circle me-2"></i>
                                Bạn chưa nhận xe nào. Vui lòng nhận xe để bắt đầu ca làm.
                            </div>
                            <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>
                            <div class="form-group mb-3">
                                <label class="form-label">Số ODO hiện tại <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" v-model="odo" min="0" required
                                    placeholder="Nhập số ODO hiện tại" />
                            </div>
                            <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>
                            <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>
                            <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>
                            <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>
                            <div class="form-group">
                                <button type="submit" class="btn btn-primary me-2"
                                    :disabled="loading || !selectedTruck || selectedImages.length === 0 || !odo">
                                    <i class="fas fa-check me-2"></i>
                                    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>

                        <!-- Nếu đã nhận xe -->
                        <form v-else @submit.prevent="handleReturnVehicle">
                            <div class="alert alert-info mb-3">
                                <i class="fas fa-info-circle me-2"></i>
                                Bạn đang phụ trách xe <strong>{{ currentTruck.LicensePlate }}</strong>. Vui lòng trả xe
                                khi kết thúc ca làm.
                            </div>
                            <div class="form-group mb-3">
                                <label class="form-label">Số ODO hiện tại <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" v-model="odo" min="0" required
                                    placeholder="Nhập số ODO hiện tại" />
                            </div>
                            <div class="form-group mb-3">
                                <label class="form-label">Ảnh khi trả 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>
                            <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>
                            <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ú khi trả xe"></textarea>
                            </div>
                            <div class="form-group">
                                <button type="submit" class="btn btn-warning me-2"
                                    :disabled="loading || selectedImages.length === 0 || !odo">
                                    <i class="fas fa-undo me-2"></i>
                                    Trả 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 bàn giao 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>
                                Nếu chưa nhận xe, hãy chọn xe và upload ảnh nhận xe
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success me-2"></i>
                                Nếu đã nhận xe, hãy upload ảnh trả xe và ghi chú khi trả
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success me-2"></i>
                                Chỉ được nhận 1 xe tại 1 thời điểm
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="card mt-3" v-if="currentTruck">
                    <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, onMounted } from 'vue';
import truckService from '@/services/truckService';
import { useToast } from 'vue-toastification';

const toast = useToast();
const loading = ref(false);
const loadingCurrentTruck = ref(false);
const selectedTruck = ref(null);
const selectedImages = ref([]);
const notes = ref('');
const availableTrucks = ref([]);
const currentTruck = ref(null);
const fileInput = ref(null);
const odo = ref('');

onMounted(async () => {
    await Promise.all([
        loadCurrentTruck(),
        loadAvailableTrucks()
    ]);
});

const loadCurrentTruck = async () => {
    loadingCurrentTruck.value = true;
    try {
        const result = await truckService.getMyCurrentTruck();
        if (result && result.Result === 1 && result.Items && result.Items.length > 0) {
            currentTruck.value = result.Items[0];
        } else {
            currentTruck.value = null;
        }
    } catch (error) {
        currentTruck.value = null;
    } finally {
        loadingCurrentTruck.value = false;
    }
};

const loadAvailableTrucks = async () => {
    try {
        const result = await truckService.getAvailableTrucks();
        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) {
        availableTrucks.value = [];
    }
};

const onTruckChange = () => {
    selectedImages.value = [];
};

const triggerFileInput = () => {
    fileInput.value.click();
};

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

const handleDrop = (event) => {
    const files = Array.from(event.dataTransfer.files);
    addFiles(files);
};

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);
    });
};

const removeImage = (index) => {
    selectedImages.value.splice(index, 1);
};

const resetForm = () => {
    selectedTruck.value = null;
    selectedImages.value = [];
    notes.value = '';
    odo.value = '';
    if (fileInput.value) fileInput.value.value = '';
};

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;
    }
    if (!odo.value || odo.value <= 0) {
        toast.warning('Vui lòng nhập số ODO hợp lệ!');
        return;
    }
    loading.value = true;
    try {
        const formData = new FormData();
        formData.append('TruckId', selectedTruck.value.Id);
        formData.append('Note', notes.value);
        formData.append('Odo', odo.value);
        selectedImages.value.forEach(img => {
            formData.append('Files', img.file);
        });
        const result = await truckService.checkInTruck(formData);
        if (result && result.Result === 1) {
            toast.success('Nhận xe thành công!');
            resetForm();
            await loadCurrentTruck();
        } else {
            toast.error(result?.Message || 'Có lỗi khi nhận xe!');
        }
    } catch (error) {
        toast.error('Có lỗi khi gửi dữ liệu!');
    } finally {
        loading.value = false;
    }
};

const handleReturnVehicle = async () => {
    if (!currentTruck.value || selectedImages.value.length === 0) {
        toast.warning('Vui lòng upload ít nhất 1 ảnh!');
        return;
    }
    if (!odo.value || odo.value <= 0) {
        toast.warning('Vui lòng nhập số ODO hợp lệ!');
        return;
    }
    loading.value = true;
    try {
        const formData = new FormData();
        formData.append('TruckId', currentTruck.value.Id);
        formData.append('Note', notes.value);
        formData.append('Odo', odo.value);
        selectedImages.value.forEach(img => {
            formData.append('Files', img.file);
        });
        const result = await truckService.checkOutTruck(formData);
        if (result && result.Result === 1) {
            toast.success('Trả xe thành công!');
            resetForm();
            await loadCurrentTruck();
        } else {
            toast.error(result?.Message || 'Có lỗi khi trả xe!');
        }
    } catch (error) {
        toast.error('Có lỗi khi gửi dữ liệu!');
    } finally {
        loading.value = false;
    }
};

const getOperatingStatusClass = (status) => {
    const classes = {
        0: 'bg-secondary',
        1: 'bg-success',
        2: 'bg-warning',
        3: 'bg-danger'
    };
    return classes[status] || 'bg-secondary';
};
const getStatusClass = (status) => {
    const classes = {
        0: 'bg-secondary',
        1: 'bg-success',
        2: 'bg-warning',
        3: 'bg-danger'
    };
    return classes[status] || 'bg-secondary';
};
</script>

<style scoped>
.handover-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>