<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import Card from 'primevue/card';
import Chart from 'primevue/chart';
import Tag from 'primevue/tag';
import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import ProgressSpinner from 'primevue/progressspinner';
import BasePageHeader from '@/core/components/BasePageHeader.vue';
import { dashboardService } from '../dashboard.service';
import { TIMESHEET_STATUS } from '@/core/constants/app.constants';
import type { DashboardStat } from '../dashboard.types';

const loading = ref(false);
const stats = ref<DashboardStat[]>([]);
const weeklyHoursData = ref<any>(null);
const pendingApprovals = ref<any[]>([]);

const chartOptions = computed(() => ({
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: { display: false },
  },
  scales: {
    y: { beginAtZero: true, title: { display: true, text: '시간 (h)' } },
    x: { title: { display: true, text: '요일' } },
  },
}));

const defaultStats: DashboardStat[] = [
  { label: '금주 시수', value: 0, icon: 'pi pi-clock' },
  { label: '미제출 건수', value: 0, icon: 'pi pi-exclamation-triangle' },
  { label: '결재 대기', value: 0, icon: 'pi pi-check-square' },
  { label: '프로젝트 수', value: 0, icon: 'pi pi-briefcase' },
];

onMounted(async () => {
  loading.value = true;
  try {
    const { data } = await dashboardService.getDashboard();
    stats.value = data.stats ?? defaultStats;
    pendingApprovals.value = data.pendingApprovals ?? [];
    weeklyHoursData.value = {
      labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
      datasets: [
        {
          label: '시수',
          backgroundColor: 'var(--p-primary-color)',
          data: data.weeklyHours ?? [0, 0, 0, 0, 0, 0],
        },
      ],
    };
  } catch {
    stats.value = defaultStats;
    weeklyHoursData.value = {
      labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
      datasets: [{ label: '시수', backgroundColor: 'var(--p-primary-color)', data: [0, 0, 0, 0, 0, 0] }],
    };
  } finally {
    loading.value = false;
  }
});

function statusSeverity(status: string) {
  return (TIMESHEET_STATUS as Record<string, any>)[status]?.severity ?? 'secondary';
}
function statusLabel(status: string) {
  return (TIMESHEET_STATUS as Record<string, any>)[status]?.label ?? status;
}
</script>

<template>
  <div class="dashboard-view">
    <BasePageHeader title="대시보드" subtitle="금주 시수 현황 및 결재 현황" />

    <div v-if="loading" class="dashboard-view__loading">
      <ProgressSpinner />
    </div>

    <template v-else>
      <!-- Stat Cards -->
      <div class="dashboard-view__stats">
        <Card v-for="(stat, idx) in stats" :key="idx" class="dashboard-view__stat-card">
          <template #content>
            <div class="stat-card">
              <div class="stat-card__icon">
                <i :class="stat.icon" />
              </div>
              <div class="stat-card__info">
                <span class="stat-card__value">{{ stat.value }}</span>
                <span class="stat-card__label">{{ stat.label }}</span>
              </div>
              <div v-if="stat.trend != null" class="stat-card__trend" :class="{ 'stat-card__trend--up': stat.trend > 0, 'stat-card__trend--down': stat.trend < 0 }">
                <i :class="stat.trend > 0 ? 'pi pi-arrow-up' : stat.trend < 0 ? 'pi pi-arrow-down' : 'pi pi-minus'" />
                {{ Math.abs(stat.trend) }}%
              </div>
            </div>
          </template>
        </Card>
      </div>

      <!-- 2-column grid -->
      <div class="dashboard-view__grid">
        <!-- Weekly Hours Chart -->
        <Card class="dashboard-view__chart-card">
          <template #title>금주 시수 현황</template>
          <template #content>
            <div class="dashboard-view__chart-wrapper">
              <Chart v-if="weeklyHoursData" type="bar" :data="weeklyHoursData" :options="chartOptions" />
            </div>
          </template>
        </Card>

        <!-- Pending Approvals -->
        <Card class="dashboard-view__approvals-card">
          <template #title>결재 대기 목록</template>
          <template #content>
            <DataTable :value="pendingApprovals" :rows="5" :paginator="pendingApprovals.length > 5" size="small" stripedRows>
              <Column field="requesterName" header="요청자" />
              <Column field="projectName" header="프로젝트" />
              <Column field="totalHours" header="시수">
                <template #body="{ data }">{{ data.totalHours }}h</template>
              </Column>
              <Column field="status" header="상태">
                <template #body="{ data }">
                  <Tag :value="statusLabel(data.status)" :severity="statusSeverity(data.status)" />
                </template>
              </Column>
              <template #empty>
                <div style="text-align: center; padding: 1rem; color: var(--p-text-muted-color);">
                  결재 대기 건이 없습니다.
                </div>
              </template>
            </DataTable>
          </template>
        </Card>
      </div>
    </template>
  </div>
</template>

<style lang="scss" scoped>
@use '@/assets/styles/variables' as *;

.dashboard-view {
  &__loading {
    display: flex;
    justify-content: center;
    padding: $space-2xl;
  }

  &__stats {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: $space-md;
    margin-bottom: $space-lg;

    @media (max-width: $bp-tablet) {
      grid-template-columns: repeat(2, 1fr);
    }
    @media (max-width: $bp-mobile) {
      grid-template-columns: 1fr;
    }
  }

  &__stat-card {
    :deep(.p-card-body) {
      padding: $space-md;
    }
    :deep(.p-card-content) {
      padding: 0;
    }
  }

  &__grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: $space-md;

    @media (max-width: $bp-tablet) {
      grid-template-columns: 1fr;
    }
  }

  &__chart-wrapper {
    height: 280px;
    position: relative;
  }
}

.stat-card {
  display: flex;
  align-items: center;
  gap: $space-md;

  &__icon {
    width: 48px;
    height: 48px;
    border-radius: $radius-lg;
    background: var(--p-primary-100);
    color: var(--p-primary-color);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: $font-size-xl;
    flex-shrink: 0;
  }

  &__info {
    display: flex;
    flex-direction: column;
    min-width: 0;
  }

  &__value {
    font-size: $font-size-2xl;
    font-weight: 700;
    color: $color-text;
    line-height: 1.2;
  }

  &__label {
    font-size: $font-size-sm;
    color: $color-text-muted;
  }

  &__trend {
    margin-left: auto;
    font-size: $font-size-sm;
    font-weight: 600;
    &--up { color: $color-success; }
    &--down { color: $color-danger; }
  }
}
</style>
