<script setup lang="ts">
import { ref, computed } from 'vue';
import Card from 'primevue/card';
import Select from 'primevue/select';
import DatePicker from 'primevue/datepicker';
import Button from 'primevue/button';
import Chart from 'primevue/chart';
import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import ProgressSpinner from 'primevue/progressspinner';
import { useToast } from 'primevue/usetoast';
import BasePageHeader from '@/core/components/BasePageHeader.vue';
import { reportService } from '../report.service';
import { projectService } from '@/modules/project/project.service';
import type { ReportFilter } from '../report.types';

const toast = useToast();

const loading = ref(false);
const projects = ref<any[]>([]);
const filter = ref<ReportFilter>({ groupBy: 'project' });
const fromDate = ref<Date | null>(null);
const toDate = ref<Date | null>(null);

const chartData = ref<any>(null);
const tableData = ref<any[]>([]);

const groupByOptions = [
  { label: '프로젝트별', value: 'project' },
  { label: 'WBS별', value: 'wbs' },
  { label: '사용자별', value: 'user' },
  { label: '월별', value: 'month' },
];

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

async function loadProjects() {
  try {
    const { data } = await projectService.getAll();
    projects.value = ((data as any).items ?? data ?? []).map((p: any) => ({
      label: `${p.projectCode} - ${p.name}`,
      value: p.id,
    }));
  } catch {
    projects.value = [];
  }
}

function formatDateStr(d: Date | null): string | undefined {
  if (!d) return undefined;
  return d.toISOString().slice(0, 10);
}

async function search() {
  loading.value = true;
  try {
    const params: Record<string, unknown> = {
      ...filter.value,
      from: formatDateStr(fromDate.value),
      to: formatDateStr(toDate.value),
    };

    const { data } = await reportService.getProjectHours(params);
    const result = data as any;

    tableData.value = result.rows ?? result.items ?? [];

    const labels = tableData.value.map((r: any) => r.label ?? r.name ?? r.projectCode ?? '');
    const values = tableData.value.map((r: any) => r.totalHours ?? r.hours ?? 0);

    chartData.value = {
      labels,
      datasets: [
        {
          label: '시수 (h)',
          backgroundColor: 'var(--p-primary-color)',
          data: values,
        },
      ],
    };
  } catch {
    toast.add({ severity: 'error', summary: '오류', detail: '리포트 조회 실패', life: 5000 });
    chartData.value = null;
    tableData.value = [];
  } finally {
    loading.value = false;
  }
}

async function exportExcel() {
  try {
    const params: Record<string, unknown> = {
      ...filter.value,
      from: formatDateStr(fromDate.value),
      to: formatDateStr(toDate.value),
    };
    const { data } = await reportService.exportProjectHours(params);
    const url = window.URL.createObjectURL(new Blob([data as any]));
    const link = document.createElement('a');
    link.href = url;
    link.download = 'report.xlsx';
    link.click();
    window.URL.revokeObjectURL(url);
  } catch {
    toast.add({ severity: 'error', summary: '오류', detail: 'Excel 다운로드 실패', life: 5000 });
  }
}

loadProjects();
</script>

<template>
  <div class="report-view">
    <BasePageHeader title="리포트" subtitle="시수 통계 및 분석">
      <template #actions>
        <Button label="Excel 다운로드" icon="pi pi-file-excel" severity="success" :disabled="!tableData.length" @click="exportExcel" />
      </template>
    </BasePageHeader>

    <!-- Filter Panel -->
    <Card class="report-view__filter">
      <template #content>
        <div class="form-grid">
          <div class="col-4">
            <div class="form-field">
              <label class="form-field__label">프로젝트</label>
              <Select
                v-model="filter.projectId"
                :options="projects"
                optionLabel="label"
                optionValue="value"
                placeholder="전체"
                showClear
                fluid
              />
            </div>
          </div>
          <div class="col-3">
            <div class="form-field">
              <label class="form-field__label">시작일</label>
              <DatePicker v-model="fromDate" dateFormat="yy-mm-dd" placeholder="YYYY-MM-DD" fluid />
            </div>
          </div>
          <div class="col-3">
            <div class="form-field">
              <label class="form-field__label">종료일</label>
              <DatePicker v-model="toDate" dateFormat="yy-mm-dd" placeholder="YYYY-MM-DD" fluid />
            </div>
          </div>
          <div class="col-2">
            <div class="form-field">
              <label class="form-field__label">그룹</label>
              <Select v-model="filter.groupBy" :options="groupByOptions" optionLabel="label" optionValue="value" fluid />
            </div>
          </div>
          <div class="col-12" style="display: flex; justify-content: flex-end;">
            <Button label="조회" icon="pi pi-search" :loading="loading" @click="search" />
          </div>
        </div>
      </template>
    </Card>

    <div v-if="loading" style="display: flex; justify-content: center; padding: 3rem;">
      <ProgressSpinner />
    </div>

    <template v-else-if="chartData">
      <!-- Chart -->
      <Card class="report-view__chart">
        <template #content>
          <div style="height: 320px; position: relative;">
            <Chart type="bar" :data="chartData" :options="chartOptions" />
          </div>
        </template>
      </Card>

      <!-- Table -->
      <Card class="report-view__table">
        <template #content>
          <DataTable :value="tableData" size="small" stripedRows :paginator="tableData.length > 20" :rows="20" removableSort>
            <Column field="label" :header="filter.groupBy === 'project' ? '프로젝트' : filter.groupBy === 'wbs' ? 'WBS' : filter.groupBy === 'user' ? '사용자' : '월'" sortable />
            <Column field="totalHours" header="총 시수 (h)" sortable>
              <template #body="{ data }">{{ (data.totalHours ?? data.hours ?? 0).toFixed(1) }}h</template>
            </Column>
            <Column field="userCount" header="인원" sortable v-if="filter.groupBy !== 'user'" />
            <Column field="entryCount" header="건수" sortable />
          </DataTable>
        </template>
      </Card>
    </template>

    <div v-else style="text-align: center; padding: 3rem; color: var(--p-text-muted-color);">
      조회 조건을 설정하고 "조회" 버튼을 클릭하세요.
    </div>
  </div>
</template>

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

.report-view {
  &__filter {
    margin-bottom: $space-md;
  }
  &__chart {
    margin-bottom: $space-md;
  }
  &__table {
    margin-bottom: $space-md;
  }
}
</style>
