<template>
    <div class="activity-history-container">
        <!-- Thông tin xe tải -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fe fe-truck me-2"></i>Thông tin xe tải
                </h5>
            </div>
            <div class="card-body">
                <div v-if="Object.keys(truckInfo).length === 0" class="text-center py-3">
                    <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
                    <span class="ms-2">Đang tải thông tin xe tải...</span>
                </div>
                <div v-else class="row">
                    <div class="col-md-6">
                        <div class="info-item">
                            <label class="fw-bold">Biển số:</label>
                            <span class="ms-2">{{ truckInfo.LicensePlate || 'N/A' }}</span>
                        </div>
                        <div class="info-item">
                            <label class="fw-bold">Trạng thái:</label>
                            <span class="ms-2">
                                <span :class="[
                                    'badge',
                                    truckInfo.OperatingStatus == 1 ? 'bg-secondary' : (truckInfo.OperatingStatus == 2 ? 'bg-success' : 'bg-secondary')
                                ]">
                                    {{ truckInfo.OperatingStatusStr || 'N/A' }}
                                </span>
                            </span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-item">
                            <label class="fw-bold">Chi nhánh:</label>
                            <span class="ms-2">{{ truckInfo.AgencyName || 'N/A' }}</span>
                        </div>
                        <div class="info-item">
                            <label class="fw-bold">Người lái:</label>
                            <span class="ms-2">
                                {{ truckInfo.PicUserName || 'N/A' }}
                                <span v-if="truckInfo.PicFullName">({{ truckInfo.PicFullName }})</span>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Lịch sử giao nhận -->
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fe fe-clock me-2"></i>Lịch sử giao nhận
                </h5>
            </div>
            <div class="card-body">
                <div v-if="loading" class="text-center py-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Đang tải...</span>
                    </div>
                    <p class="mt-2">Đang tải lịch sử giao nhận...</p>
                </div>

                <div v-else-if="activityHistory.length === 0" class="text-center py-4">
                    <i class="fe fe-inbox fs-1 text-muted"></i>
                    <p class="mt-2 text-muted">Chưa có lịch sử giao nhận nào</p>
                </div>

                <div v-else class="timeline">
                    <div v-for="(activity, index) in activityHistory" :key="activity.id" class="timeline-item">
                        <div class="timeline-marker" :class="getMarkerClass(activity.actionType)">
                            <i :class="getMarkerIcon(activity.actionType)"></i>
                        </div>
                        <div class="timeline-content">
                            <div class="timeline-header">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h6 class="mb-1">
                                        <span :class="getActionBadgeClass(activity.actionType)">
                                            {{ activity.actionTypeStr }}
                                        </span>
                                    </h6>
                                    <small class="text-muted">
                                        {{ formatDateTime(activity.createdTime) }}
                                    </small>
                                </div>
                                <p class="text-muted mb-2">
                                    <i class="fe fe-user me-1"></i>
                                    {{ activity.createdByUserName }}
                                </p>
                            </div>

                            <div class="timeline-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="info-item">
                                            <label class="fw-bold">Số km hiện tại:</label>
                                            <span class="ms-2">{{ formatNumber(activity.currentOdo) }} km</span>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="info-item">
                                            <label class="fw-bold">Ghi chú:</label>
                                            <span class="ms-2">{{ activity.note || 'Không có ghi chú' }}</span>
                                        </div>
                                    </div>
                                </div>

                                <!-- Media items -->
                                <div v-if="hasMediaItems(activity)" class="mt-3">
                                    <h6 class="mb-2">
                                        <i class="fe fe-image me-1"></i>
                                        Hình ảnh ({{ activity.mediaItems.length }})
                                    </h6>
                                    <div class="media-gallery">
                                        <div v-for="media in activity.mediaItems" :key="media.id" class="media-item">
                                            <div class="media-card">
                                                <div class="image-container">
                                                    <img :src="media.mediaUrl" :alt="media.altText" class="media-image"
                                                        @click="openImageModal(media)" @error="handleImageError"
                                                        @load="handleImageLoad" loading="lazy">
                                                    <div class="image-overlay">
                                                        <i class="fe fe-maximize-2"></i>
                                                    </div>
                                                </div>
                                                <div class="media-info">
                                                    <small class="text-muted">{{ media.mediaTypeStr }}</small>
                                                    <p v-if="media.caption" class="caption">{{ media.caption }}</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- Debug info -->
                                <div v-else class="mt-3">
                                    <small class="text-muted">
                                        <i class="fe fe-info me-1"></i>
                                        Không có hình ảnh cho hoạt động này
                                    </small>
                                </div>

                                <!-- Debug info for development -->
                                <div v-if="isDevelopment" class="mt-2">
                                    <details class="debug-info">
                                        <summary class="text-muted small">Debug Info</summary>
                                        <pre class="mt-2 small text-muted">{{ JSON.stringify(activity, null, 2) }}</pre>
                                    </details>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Image Modal -->
        <div class="modal fade" id="imageModal" tabindex="-1" aria-labelledby="imageModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="imageModalLabel">{{ selectedImage?.altText || 'Hình ảnh' }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body text-center">
                        <img v-if="selectedImage" :src="selectedImage.mediaUrl" :alt="selectedImage.altText"
                            class="img-fluid">
                        <p v-if="selectedImage?.caption" class="mt-2 text-muted">{{ selectedImage.caption }}</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

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

const toast = useToast();

// Props
const props = defineProps({
    truckId: {
        type: Number,
        required: true
    }
});

// Reactive data
const loading = ref(false);
const truckInfo = reactive({});
const activityHistory = ref([]);
const selectedImage = ref(null);
const isDevelopment = ref(import.meta.env.DEV);

// Methods
const loadTruckInfo = async () => {
    if (!props.truckId) return;

    try {
        const response = await truckService.getTruckByIds({ ids: [props.truckId] });
        if (response.Result === 1 && response.Items && response.Items.length > 0) {
            Object.assign(truckInfo, response.Items[0]);
        } else {
            console.error('Failed to load truck info:', response.Message);
        }
    } catch (error) {
        console.error('Error loading truck info:', error);
    }
};

const loadActivityHistory = async () => {
    if (!props.truckId) return;

    loading.value = true;
    try {
        const response = await truckService.getActivityHistory(props.truckId);
        console.log('Activity history response:', response);

        if (response.result === "Success" || response.Result === 1) {
            activityHistory.value = response.items || response.Items || [];
            console.log('Activity history items:', activityHistory.value);

            // Debug: Kiểm tra mediaItems trong từng activity
            activityHistory.value.forEach((activity, index) => {
                console.log(`Activity ${index}:`, activity);
                if (activity.mediaItems) {
                    console.log(`Activity ${index} mediaItems:`, activity.mediaItems);
                }
            });
        } else {
            toast.error(response.message || response.Message || 'Có lỗi xảy ra khi tải lịch sử');
        }
    } catch (error) {
        console.error('Error loading activity history:', error);
        toast.error('Có lỗi xảy ra khi tải lịch sử giao nhận');
    } finally {
        loading.value = false;
    }
};

// Helper function để kiểm tra xem activity có mediaItems không
const hasMediaItems = (activity) => {
    return activity.mediaItems && Array.isArray(activity.mediaItems) && activity.mediaItems.length > 0;
};

const formatDateTime = (dateTime) => {
    return moment(dateTime).format('DD/MM/YYYY HH:mm');
};

const formatNumber = (number) => {
    return new Intl.NumberFormat('vi-VN').format(number);
};

const getMarkerClass = (actionType) => {
    return actionType === 'CheckIn' ? 'checkin' : 'checkout';
};

const getMarkerIcon = (actionType) => {
    return actionType === 'CheckIn' ? 'fe fe-log-in' : 'fe fe-log-out';
};

const getActionBadgeClass = (actionType) => {
    const baseClass = 'badge';
    return actionType === 'CheckIn'
        ? `${baseClass} bg-success`
        : `${baseClass} bg-warning`;
};

const openImageModal = (media) => {
    selectedImage.value = media;
    // Sử dụng Bootstrap modal
    const modal = new bootstrap.Modal(document.getElementById('imageModal'));
    modal.show();
};

const handleImageError = (event) => {
    console.error('Image failed to load:', event.target.src);
    // Thay thế bằng ảnh placeholder hoặc ẩn ảnh
    event.target.style.display = 'none';
    event.target.alt = 'Không thể tải ảnh';
};

const handleImageLoad = (event) => {
    console.log('Image loaded successfully:', event.target.src);
};

// Lifecycle
onMounted(() => {
    loadTruckInfo();
    loadActivityHistory();
});

watch(() => props.truckId, (newId) => {
    if (newId) {
        loadTruckInfo();
        loadActivityHistory();
    }
});
</script>

<style scoped>
.activity-history-container {
    padding: 20px;
}

.info-item {
    margin-bottom: 10px;
}

.timeline {
    position: relative;
    padding-left: 30px;
}

.timeline::before {
    content: '';
    position: absolute;
    left: 15px;
    top: 0;
    bottom: 0;
    width: 2px;
    background: #e9ecef;
}

.timeline-item {
    position: relative;
    margin-bottom: 30px;
}

.timeline-marker {
    position: absolute;
    left: -22px;
    top: 0;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 12px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.timeline-marker.checkin {
    background: #28a745;
}

.timeline-marker.checkout {
    background: #ffc107;
}

.timeline-content {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    margin-left: 20px;
    border: 1px solid #e9ecef;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.timeline-header {
    border-bottom: 1px solid #dee2e6;
    padding-bottom: 10px;
    margin-bottom: 15px;
}

.timeline-body {
    background: white;
    border-radius: 6px;
    padding: 15px;
    margin-top: 10px;
}

.media-gallery {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 15px;
    margin-top: 15px;
}

.media-card {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    overflow: hidden;
    background: white;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.2s;
}

.media-card:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.image-container {
    position: relative;
    overflow: hidden;
}

.media-image {
    width: 100%;
    height: 120px;
    object-fit: cover;
    cursor: pointer;
    transition: transform 0.2s;
    display: block;
}

.media-image:hover {
    transform: scale(1.05);
}

.image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.2s;
    color: white;
    font-size: 1.5rem;
}

.image-container:hover .image-overlay {
    opacity: 1;
}

.media-info {
    padding: 10px;
}

.caption {
    font-size: 12px;
    margin: 5px 0 0 0;
    color: #6c757d;
}

.badge {
    font-size: 0.75em;
    padding: 0.375em 0.75em;
}

.debug-info {
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 10px;
    background: #f8f9fa;
}

.debug-info summary {
    cursor: pointer;
    font-weight: 500;
}

.debug-info pre {
    background: #fff;
    border: 1px solid #e9ecef;
    border-radius: 4px;
    padding: 10px;
    max-height: 200px;
    overflow-y: auto;
    font-size: 11px;
}

@media (max-width: 768px) {
    .activity-history-container {
        padding: 10px;
    }

    .timeline {
        padding-left: 20px;
    }

    .timeline-marker {
        left: -15px;
        width: 25px;
        height: 25px;
        font-size: 10px;
    }

    .timeline-content {
        margin-left: 15px;
    }

    .media-gallery {
        grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    }
}
</style>