<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import Button from 'primevue/button';
import Dialog from 'primevue/dialog';
import Select from 'primevue/select';
import InputText from 'primevue/inputtext';
import DatePicker from 'primevue/datepicker';
import Tag from 'primevue/tag';
import ProgressBar from 'primevue/progressbar';
import { useToast } from 'primevue/usetoast';
import api from '../api.js';

const router = useRouter();
const toast = useToast();

const rows = ref([]);
const loading = ref(true);
const suppliers = ref([]);
const productGroups = ref([]);

async function load() {
  loading.value = true;
  const { data } = await api.getImports();
  rows.value = data;
  loading.value = false;
}

function statusSeverity(status) {
  return { Onboarding: 'warn', 'Pending Approval': 'info', Integrated: 'success', Unintegrated: 'secondary' }[status] || 'secondary';
}

function progressPercent(row) {
  if (!row.total_rows) return 0;
  return Math.round(((row.onboarded_rows + row.discarded_rows) / row.total_rows) * 100);
}

function openWizard(row) {
  router.push({ name: 'import-onboarding', params: { id: row.id } });
}

// ---- Create import dialog ----
const createVisible = ref(false);
const form = ref({
  import_number: '', supplier_id: null, product_group_id: null, season: '',
  effective_from: new Date(), effective_to: new Date(),
});

async function openCreate() {
  createVisible.value = true;
  if (suppliers.value.length === 0) {
    const [sup, pg] = await Promise.all([api.getSuppliers(), api.getProductGroups()]);
    suppliers.value = sup.data;
    productGroups.value = pg.data;
  }
}

function toDateStr(d) {
  const dt = new Date(d);
  return dt.toISOString().slice(0, 10);
}

async function submitCreate() {
  try {
    const payload = {
      ...form.value,
      effective_from: toDateStr(form.value.effective_from),
      effective_to: toDateStr(form.value.effective_to),
    };
    await api.createImport(payload);
    toast.add({ severity: 'success', summary: 'Import created', detail: 'Ready for onboarding', life: 3000 });
    createVisible.value = false;
    load();
  } catch (e) {
    toast.add({ severity: 'error', summary: 'Error', detail: e.response?.data?.error || 'Create failed', life: 4000 });
  }
}

onMounted(load);
</script>

<template>
  <div class="page module-accent" style="--accent-color: var(--module-imports)">
    <div class="page-header">
      <div>
        <h1>Import Management</h1>
        <p class="page-subtitle">Supplier price file imports, working through the style onboarding wizard.</p>
      </div>
      <Button label="Create Import" icon="pi pi-plus" @click="openCreate" />
    </div>

    <div class="card-block">
      <DataTable :value="rows" :loading="loading" dataKey="id" stripedRows responsiveLayout="scroll">
        <Column field="import_number" header="Import" />
        <Column field="supplier_name" header="Supplier" />
        <Column field="product_group_name" header="Product Group" />
        <Column field="season" header="Season" />
        <Column field="status" header="Status">
          <template #body="{ data }">
            <Tag :value="data.status" :severity="statusSeverity(data.status)" />
          </template>
        </Column>
        <Column header="Progress" style="width: 200px">
          <template #body="{ data }">
            <ProgressBar :value="progressPercent(data)" :showValue="true" style="height: 0.8rem" />
            <span class="page-subtitle" style="font-size: 0.72rem">
              {{ data.onboarded_rows + data.discarded_rows }} / {{ data.total_rows }} classified
            </span>
          </template>
        </Column>
        <Column field="imported_by" header="Imported By" />
        <Column header="" style="width: 140px">
          <template #body="{ data }">
            <Button label="Open" icon="pi pi-arrow-right" text @click="openWizard(data)" />
          </template>
        </Column>
        <template #empty>
          <div class="empty-state">No imports yet. Create one to start onboarding styles.</div>
        </template>
      </DataTable>
    </div>

    <Dialog v-model:visible="createVisible" modal header="Create Import" style="width: 480px">
      <div class="field">
        <label>Import Reference</label>
        <InputText v-model="form.import_number" fluid placeholder="Import File 4" />
      </div>
      <div class="field">
        <label>Supplier</label>
        <Select v-model="form.supplier_id" :options="suppliers" optionLabel="name" optionValue="id" fluid placeholder="Select a supplier" />
      </div>
      <div class="field">
        <label>Product Group</label>
        <Select v-model="form.product_group_id" :options="productGroups" optionLabel="name" optionValue="id" fluid placeholder="Select a product group" />
      </div>
      <div class="field">
        <label>Season</label>
        <InputText v-model="form.season" fluid placeholder="AW26" />
      </div>
      <div class="grid-2">
        <div class="field">
          <label>Effective From</label>
          <DatePicker v-model="form.effective_from" dateFormat="yy-mm-dd" fluid />
        </div>
        <div class="field">
          <label>Effective To</label>
          <DatePicker v-model="form.effective_to" dateFormat="yy-mm-dd" fluid />
        </div>
      </div>
      <template #footer>
        <Button label="Cancel" text @click="createVisible = false" />
        <Button label="Create" @click="submitCreate" />
      </template>
    </Dialog>
  </div>
</template>

<style scoped>
.field {
  margin-bottom: 1rem;
}
.field label {
  display: block;
  font-size: 0.8rem;
  font-weight: 500;
  margin-bottom: 0.35rem;
}
.grid-2 {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}
</style>
