<template>
  <div>
    <!-- Breadcrumb Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Chi tiết chấm công - {{ fullName }}</h4>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
          <li class="breadcrumb-item"><a href="javascript:void(0);">Nhân sự</a></li>
          <li class="breadcrumb-item">
            <a href="javascript:void(0);" @click="goBack">Báo cáo chấm công</a>
          </li>
          <li class="breadcrumb-item active" aria-current="page">Chi tiết</li>
        </ol>
      </div>
    </div>

    <!-- Main Content -->
    <div class="row row-sm">
      <div class="col-12 grid-margin">
        <!-- Info Card -->
        <div class="card shadow-none mb-3">
          <div class="card-body">
            <div class="row">
              <div class="col-md-3">
                <div class="d-flex align-items-center">
                  <i class="fe fe-user me-2 text-primary" style="font-size: 2rem;"></i>
                  <div>
                    <small class="text-muted">Nhân viên</small>
                    <div class="fw-bold">{{ fullName }}</div>
                  </div>
                </div>
              </div>
              <div class="col-md-2">
                <div class="d-flex align-items-center">
                  <i class="fe fe-calendar me-2 text-info" style="font-size: 2rem;"></i>
                  <div>
                    <small class="text-muted">Thời gian</small>
                    <div class="fw-bold">Tháng {{ month }}/{{ year }}</div>
                  </div>
                </div>
              </div>
              <div class="col-md-2">
                <div class="d-flex align-items-center">
                  <i class="fe fe-clock me-2 text-success" style="font-size: 2rem;"></i>
                  <div>
                    <small class="text-muted">Tổng công</small>
                    <div class="fw-bold text-success">{{ totalWorkCredits.toFixed(2) }}</div>
                  </div>
                </div>
              </div>
              <div class="col-md-2">
                <div class="d-flex align-items-center">
                  <i class="fe fe-activity me-2 text-warning" style="font-size: 2rem;"></i>
                  <div>
                    <small class="text-muted">Tổng giờ</small>
                    <div class="fw-bold text-warning">{{ totalWorkingHours.toFixed(1) }}h</div>
                  </div>
                </div>
              </div>
              <div class="col-md-2">
                <div class="d-flex align-items-center">
                  <i class="fe fe-navigation me-2 text-danger" style="font-size: 2rem;"></i>
                  <div>
                    <small class="text-muted">Tổng km</small>
                    <div class="fw-bold text-danger">{{ totalOdo.toFixed(0) }} km</div>
                  </div>
                </div>
              </div>
              <div class="col-md-1 d-flex align-items-center">
                <button class="btn btn-outline-secondary w-100" @click="goBack">
                  <i class="fe fe-arrow-left me-2"></i>
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Data Table -->
        <div class="card card-table shadow-none">
          <div class="card-body card-table-body pt-0">
            <div class="d-flex justify-content-between align-items-center m-3">
              <h5 class="mb-0">Chi tiết từng ngày</h5>
              <button type="button" class="btn btn-outline-success btn-sm" @click="exportExcel"
                :disabled="loading || items.length === 0">
                <i class="fe fe-download me-2"></i>Xuất Excel
              </button>
            </div>

            <div class="table-responsive border-top">
              <table class="table table-vcenter mb-0" style="min-height:300px">
                <thead>
                  <tr>
                    <th class="wd-5p text-center">STT</th>
                    <th>Ngày làm việc</th>
                    <th class="text-center">Giờ vào</th>
                    <th class="text-center">Giờ ra</th>
                    <th class="text-center">Số giờ làm</th>
                    <th class="text-center">Số công</th>
                    <th class="text-center">ODO đầu</th>
                    <th class="text-center">ODO cuối</th>
                    <th class="text-center">Tổng ODO</th>
                  </tr>
                </thead>

                <!-- Loading State -->
                <tbody v-if="loading">
                  <tr>
                    <td colspan="9" class="tx-semibold text-center text-default">
                      <span class="spinner-border spinner-border-sm"></span>
                    </td>
                  </tr>
                </tbody>

                <!-- Empty State -->
                <tbody v-if="!loading && items.length === 0">
                  <tr>
                    <td colspan="9" class="tx-semibold text-center text-danger">
                      Không tìm thấy dữ liệu!
                    </td>
                  </tr>
                </tbody>

                <!-- Data Rows -->
                <tbody v-if="!loading && items.length > 0">
                  <tr v-for="(item, index) in items" :key="index">
                    <td class="text-center">{{ index + 1 }}</td>
                    <td>
                      <div class="fw-bold">{{ formatDate(item.WorkDate) }}</div>
                      <small class="text-muted">{{ getDayOfWeek(item.WorkDate) }}</small>
                    </td>
                    <td class="text-center">
                      <span class="text-success">{{ item.CheckInTime || '-' }}</span>
                    </td>
                    <td class="text-center">
                      <span class="text-danger">{{ item.CheckOutTime || '-' }}</span>
                    </td>
                    <td class="text-center">
                      <span class="badge bg-info">{{ item.WorkingHours.toFixed(1) }}h</span>
                    </td>
                    <td class="text-center">
                      <span class="badge" :class="{
                        'bg-success': item.WorkCredit >= 1,
                        'bg-warning': item.WorkCredit >= 0.5 && item.WorkCredit < 1,
                        'bg-secondary': item.WorkCredit < 0.5
                      }">
                        {{ item.WorkCredit.toFixed(2) }}
                      </span>
                    </td>
                    <td class="text-center">
                      <small>{{ item.StartOdo || '-' }}</small>
                    </td>
                    <td class="text-center">
                      <small>{{ item.EndOdo || '-' }}</small>
                    </td>
                    <td class="text-center">
                      <span v-if="item.TotalOdo" class="badge bg-primary">{{ item.TotalOdo }} km</span>
                      <span v-else>-</span>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <!-- Legend -->
        <div v-if="!loading && items.length > 0" class="card shadow-none">
          <div class="card-body">
            <h6 class="mb-3">Quy tắc tính công:</h6>
            <div class="row">
              <div class="col-md-3">
                <span class="badge bg-success me-2">1.0</span>
                <span>Trên 8 giờ - Full công</span>
              </div>
              <div class="col-md-3">
                <span class="badge bg-warning me-2">0.5</span>
                <span>3-8 giờ - Nửa công</span>
              </div>
              <div class="col-md-3">
                <span class="badge bg-secondary me-2">0.25</span>
                <span>2-3 giờ - 1/4 công</span>
              </div>
              <div class="col-md-3">
                <span class="badge bg-secondary me-2">0</span>
                <span>Dưới 2 giờ - Không tính</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import attendanceService from '@/services/hr/attendanceService';
import { useToast } from 'vue-toastification';

const router = useRouter();
const route = useRoute();
const toast = useToast();
const loading = ref(false);
const items = reactive([]);

// Get parameters from route
const userId = computed(() => parseInt(route.params.userId));
const month = computed(() => parseInt(route.query.month) || new Date().getMonth() + 1);
const year = computed(() => parseInt(route.query.year) || new Date().getFullYear());
const fullName = computed(() => route.query.fullName || 'Nhân viên');

// Computed totals
const totalWorkCredits = computed(() => {
  return items.reduce((sum, item) => sum + item.WorkCredit, 0);
});

const totalWorkingHours = computed(() => {
  return items.reduce((sum, item) => sum + item.WorkingHours, 0);
});

const totalOdo = computed(() => {
  return items.reduce((sum, item) => sum + (item.TotalOdo || 0), 0);
});

// Format date function
function formatDate(dateString) {
  const date = new Date(dateString);
  const day = date.getDate().toString().padStart(2, '0');
  const monthNum = (date.getMonth() + 1).toString().padStart(2, '0');
  const yearNum = date.getFullYear();
  return `${day}/${monthNum}/${yearNum}`;
}

// Get day of week
function getDayOfWeek(dateString) {
  const date = new Date(dateString);
  const days = ['Chủ nhật', 'Thứ hai', 'Thứ ba', 'Thứ tư', 'Thứ năm', 'Thứ sáu', 'Thứ bảy'];
  return days[date.getDay()];
}

// Load data function
async function loadData() {
  loading.value = true;
  items.splice(0, items.length);

  try {
    const result = await attendanceService.getUserAttendanceDetail(
      month.value,
      year.value,
      userId.value
    );

    if (result && Array.isArray(result)) {
      result.forEach(item => items.push(item));

      if (result.length === 0) {
        toast.info('Không có dữ liệu chấm công cho nhân viên này trong tháng');
      }
    }
  } catch (error) {
    console.error('Error fetching user attendance detail:', error);

    // Handle specific error messages from API
    if (error.response && error.response.data) {
      toast.error(error.response.data);
    } else {
      toast.error('Lỗi khi tải dữ liệu chi tiết chấm công!');
    }
  } finally {
    loading.value = false;
  }
}

// Go back function
function goBack() {
  router.push({ name: 'hr-attendance-report' });
}

// Export Excel function
function exportExcel() {
  if (items.length === 0) {
    toast.warning('Không có dữ liệu để xuất!');
    return;
  }

  // Create CSV content
  const headers = [
    'STT',
    'Ngày làm việc',
    'Thứ',
    'Giờ vào',
    'Giờ ra',
    'Số giờ làm',
    'Số công',
    'ODO đầu',
    'ODO cuối',
    'Tổng ODO'
  ];

  const rows = items.map((item, index) => [
    index + 1,
    formatDate(item.WorkDate),
    getDayOfWeek(item.WorkDate),
    item.CheckInTime || '',
    item.CheckOutTime || '',
    item.WorkingHours.toFixed(1),
    item.WorkCredit.toFixed(2),
    item.StartOdo || '',
    item.EndOdo || '',
    item.TotalOdo || ''
  ]);

  let csvContent = headers.join(',') + '\n';
  rows.forEach(row => {
    csvContent += row.map(cell => `"${cell}"`).join(',') + '\n';
  });

  // Add summary row
  csvContent += '\n';
  csvContent += `"","","","","Tổng cộng:",${totalWorkingHours.value.toFixed(1)},${totalWorkCredits.value.toFixed(2)},"","",""` + '\n';

  // Add BOM for Excel UTF-8 support
  const BOM = '\uFEFF';
  const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);

  link.setAttribute('href', url);
  link.setAttribute('download', `ChiTietChamCong_${userId.value}_${month.value}_${year.value}.csv`);
  link.style.visibility = 'hidden';

  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  toast.success('Đã xuất file Excel thành công!');
}

// Load data on mount
onMounted(async () => {
  await loadData();
});
</script>

<style scoped>
.badge {
  font-size: 0.875rem;
  padding: 0.35rem 0.65rem;
}

.table th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.card {
  border-radius: 8px;
}
</style>
