<script setup lang="ts">
import { ref, onMounted } from 'vue';
import Tabs from 'primevue/tabs';
import TabList from 'primevue/tablist';
import Tab from 'primevue/tab';
import TabPanels from 'primevue/tabpanels';
import TabPanel from 'primevue/tabpanel';
import Column from 'primevue/column';
import Button from 'primevue/button';
import Tag from 'primevue/tag';
import Card from 'primevue/card';
import InputNumber from 'primevue/inputnumber';
import { useToast } from 'primevue/usetoast';
import BasePageHeader from '@/core/components/BasePageHeader.vue';
import BaseCrudTable from '@/core/components/BaseCrudTable.vue';
import OverheadTypeDialog from '../components/OverheadTypeDialog.vue';
import { settingsService } from '../settings.service';
import type { OverheadType, WorkRule } from '../settings.types';

const toast = useToast();

const activeTab = ref<string>('overhead');
const loading = ref(false);

// Overhead Types
const overheadTypes = ref<OverheadType[]>([]);
const dialogVisible = ref(false);
const dialogLoading = ref(false);
const selectedItem = ref<Partial<OverheadType> | null>(null);

async function loadOverheadTypes() {
  loading.value = true;
  try {
    const { data } = await settingsService.getOverheadTypes();
    overheadTypes.value = Array.isArray(data) ? data : (data as any).items ?? [];
  } catch {
    toast.add({ severity: 'error', summary: '오류', detail: 'Overhead Types 로드 실패', life: 5000 });
  } finally {
    loading.value = false;
  }
}

function openCreateOH() {
  selectedItem.value = null;
  dialogVisible.value = true;
}

function openEditOH(item: OverheadType) {
  selectedItem.value = { ...item };
  dialogVisible.value = true;
}

async function onSaveOH(data: Partial<OverheadType>) {
  dialogLoading.value = true;
  try {
    if (data.id) {
      await settingsService.updateOverheadType(data.id, data);
      toast.add({ severity: 'success', summary: '성공', detail: '수정되었습니다.', life: 3000 });
    } else {
      await settingsService.createOverheadType(data);
      toast.add({ severity: 'success', summary: '성공', detail: '등록되었습니다.', life: 3000 });
    }
    dialogVisible.value = false;
    await loadOverheadTypes();
  } catch {
    toast.add({ severity: 'error', summary: '오류', detail: '저장 실패', life: 5000 });
  } finally {
    dialogLoading.value = false;
  }
}

// Work Rules
const workRule = ref<Partial<WorkRule>>({
  minDailyHours: 8,
  maxWeeklyHours: 52,
});
const ruleSaving = ref(false);

async function loadWorkRules() {
  try {
    const { data } = await settingsService.getWorkRules();
    const rules = Array.isArray(data) ? data[0] : data;
    if (rules) workRule.value = { ...rules };
  } catch {
    // keep defaults
  }
}

async function saveWorkRules() {
  ruleSaving.value = true;
  try {
    await settingsService.updateWorkRules(workRule.value);
    toast.add({ severity: 'success', summary: '성공', detail: '근무 규칙이 저장되었습니다.', life: 3000 });
  } catch {
    toast.add({ severity: 'error', summary: '오류', detail: '저장 실패', life: 5000 });
  } finally {
    ruleSaving.value = false;
  }
}

onMounted(() => {
  loadOverheadTypes();
  loadWorkRules();
});
</script>

<template>
  <div class="settings-view">
    <BasePageHeader title="시스템 설정" subtitle="Overhead Types 및 근무 규칙 관리" />

    <Tabs v-model:value="activeTab">
      <TabList>
        <Tab value="overhead">Overhead Types</Tab>
        <Tab value="rules">Work Rules</Tab>
      </TabList>
      <TabPanels>
        <!-- Overhead Types Tab -->
        <TabPanel value="overhead">
          <BaseCrudTable
            :value="overheadTypes"
            :loading="loading"
            :globalFilterFields="['code', 'name']"
            :paginator="overheadTypes.length > 20"
          >
            <template #toolbar-left>
              <Button label="등록" icon="pi pi-plus" size="small" @click="openCreateOH" />
            </template>

            <Column field="code" header="코드" sortable style="min-width: 120px" />
            <Column field="name" header="이름" sortable style="min-width: 180px" />
            <Column field="isActive" header="상태" style="min-width: 80px">
              <template #body="{ data }">
                <Tag :value="data.isActive ? '활성' : '비활성'" :severity="data.isActive ? 'success' : 'secondary'" />
              </template>
            </Column>
            <Column header="" style="width: 80px">
              <template #body="{ data }">
                <Button icon="pi pi-pencil" text rounded severity="info" @click="openEditOH(data)" />
              </template>
            </Column>
          </BaseCrudTable>
        </TabPanel>

        <!-- Work Rules Tab -->
        <TabPanel value="rules">
          <Card>
            <template #content>
              <div class="form-grid">
                <div class="col-6">
                  <div class="form-field">
                    <label class="form-field__label">일 최소 시수 (h)</label>
                    <InputNumber v-model="workRule.minDailyHours" :min="0" :max="24" :step="0.5" :maxFractionDigits="1" fluid />
                  </div>
                </div>
                <div class="col-6">
                  <div class="form-field">
                    <label class="form-field__label">주 최대 시수 (h)</label>
                    <InputNumber v-model="workRule.maxWeeklyHours" :min="0" :max="168" :step="1" fluid />
                  </div>
                </div>
                <div class="col-6">
                  <div class="form-field">
                    <label class="form-field__label">Location</label>
                    <InputNumber v-model="workRule.id" disabled fluid />
                    <span class="form-field__hint">{{ workRule.location ?? 'Default' }}</span>
                  </div>
                </div>
                <div class="col-12" style="display: flex; justify-content: flex-end; margin-top: 1rem;">
                  <Button label="저장" icon="pi pi-save" :loading="ruleSaving" @click="saveWorkRules" />
                </div>
              </div>
            </template>
          </Card>
        </TabPanel>
      </TabPanels>
    </Tabs>

    <OverheadTypeDialog
      :visible="dialogVisible"
      :item="selectedItem"
      :loading="dialogLoading"
      @update:visible="dialogVisible = $event"
      @save="onSaveOH"
    />
  </div>
</template>
