<template>
    <div class="attendance-container">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">
                            <i class="fas fa-user-check text-primary me-2"></i>
                            Chấm công
                        </h5>
                    </div>
                    <div class="card-body">
                        <div v-if="attendanceInfo" class="alert alert-info mb-4">
                            <div class="d-flex align-items-center mb-2">
                                <i class="fas fa-info-circle me-2"></i>
                                <span>Đã check-in lúc <strong>{{ attendanceInfo.CheckInTime }}</strong></span>
                            </div>
                            <div v-if="attendanceInfo.CheckInOdo != null">
                                <span>ODO: <strong>{{ attendanceInfo.CheckInOdo }}</strong></span>
                            </div>
                            <div v-if="attendanceInfo.CheckInMedias && attendanceInfo.CheckInMedias.length > 0"
                                class="mt-2">
                                <span>Ảnh check-in:</span>
                                <div class="image-preview-container mt-1">
                                    <img v-for="img in attendanceInfo.CheckInMedias" :key="img.Id" :src="img.Url"
                                        :alt="img.AltText || 'Ảnh check in'"
                                        style="max-width:80px;max-height:80px;object-fit:cover;border-radius:4px;margin-right:6px;" />
                                </div>
                            </div>
                        </div>
                        <div v-if="loading" class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2">Đang xử lý...</p>
                        </div>
                        <form v-else @submit.prevent="handlePunch">
                            <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 chấm công <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 5 ả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 mt-4">
                                <button type="submit" class="btn btn-primary me-2"
                                    :disabled="selectedImages.length === 0 || !odo">
                                    <i class="fas fa-check me-2"></i>
                                    {{ attendanceInfo ? 'Check-Out' : 'Check-In' }}
                                </button>
                                <button type="button" class="btn btn-secondary" @click="resetForm">
                                    <i class="fas fa-undo me-2"></i>
                                    Làm mới
                                </button>
                            </div>
                            <div v-if="attendanceInfo" class="alert alert-info mt-3">
                                <i class="fas fa-info-circle me-2"></i>
                                Bạn đã check-in lúc <strong>{{ attendanceInfo.CheckInTime }}</strong>, vui lòng
                                check-out khi kết thúc ca làm.
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

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

const toast = useToast();
const loading = ref(false);
const selectedImages = ref([]);
const attendanceInfo = ref(null); // Lưu toàn bộ object Item
const fileInput = ref(null);
const odo = ref('');

// Lưu/đọc thông tin chấm công từ localStorage
const ATTENDANCE_KEY = 'driver_attendance_info';
const loadAttendanceInfo = () => {
    const data = localStorage.getItem(ATTENDANCE_KEY);
    attendanceInfo.value = data ? JSON.parse(data) : null;
};
const saveAttendanceInfo = (info) => {
    attendanceInfo.value = info;
    localStorage.setItem(ATTENDANCE_KEY, JSON.stringify(info));
};
const clearAttendanceInfo = () => {
    attendanceInfo.value = null;
    localStorage.removeItem(ATTENDANCE_KEY);
};

onMounted(() => {
    loadAttendanceInfo();
});

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 > 5) {
        toast.warning('Tối đa chỉ được chọn 5 ả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 = () => {
    selectedImages.value = [];
    odo.value = '';
    if (fileInput.value) fileInput.value.value = '';
};

const handlePunch = async () => {
    if (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();
        if (attendanceInfo.value && attendanceInfo.value.Id) {
            formData.append('AttendanceId', attendanceInfo.value.Id);
        }
        formData.append('CurrentOdo', odo.value);
        selectedImages.value.forEach(img => {
            formData.append('MediaFiles', img.file);
        });
        const result = await driverUtilsService.punchAttendance(formData);
        if (result && result.Result === 1) {
            if (result.ActionType === 'CheckIn' && result.Item) {
                // Check-in thành công, lưu lại toàn bộ object Item
                saveAttendanceInfo(result.Item);
                toast.success('Check-In thành công!');
            } else if (result.ActionType === 'CheckOut') {
                // Check-out thành công, xóa thông tin chấm công
                clearAttendanceInfo();
                toast.success('Check-Out thành công!');
            } else {
                toast.success('Chấm công thành công!');
            }
            resetForm();
        } else {
            toast.error(result?.Message || 'Có lỗi xảy ra khi chấm công!');
        }
    } catch (error) {
        toast.error('Có lỗi xảy ra khi gửi dữ liệu!');
    } finally {
        loading.value = false;
    }
};
</script>

<style scoped>
.attendance-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);
}
</style>