<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import Button from 'primevue/button';
import Tag from 'primevue/tag';
import { useToast } from 'primevue/usetoast';
import api from '../api.js';

const props = defineProps({ id: { type: [String, Number], required: true } });
const router = useRouter();
const toast = useToast();

const importInfo = ref(null);
const groupedRows = ref({});
const summary = ref({});
const loading = ref(true);
const selectedRows = ref([]);

const steps = [
  { key: 'sample', label: 'Sample Styles', description: 'Matched to the Sample Module. Confirm onboard or discard.' },
  { key: 'existing', label: 'Existing Styles', description: 'Matched to existing system styles. Confirm cost updates.' },
  { key: 'non_continuable', label: 'Non-Continuable / Discontinued', description: 'Matched to styles currently discontinued or non-continuable.' },
  { key: 'inactive', label: 'Inactive (No Price)', description: 'No current price supplied — likely production has stopped.' },
  { key: 'new', label: 'New Styles', description: 'New to the system. Choose to onboard or discard.' },
];

const activeStepIndex = ref(0);
const activeStep = computed(() => steps[activeStepIndex.value]);
const activeRows = computed(() => groupedRows.value[activeStep.value?.key] || []);
const pendingInActiveStep = computed(() => activeRows.value.filter((r) => r.row_status === 'pending'));

async function load() {
  loading.value = true;
  const { data } = await api.getImportDetail(props.id);
  importInfo.value = data.import;
  groupedRows.value = data.rows_by_classification;
  summary.value = data.summary;
  loading.value = false;
  selectedRows.value = [];
}

function stepClass(index) {
  if (index === activeStepIndex.value) return 'wizard-step active';
  const key = steps[index].key;
  const s = summary.value[key];
  if (s && s.pending === 0 && s.total > 0) return 'wizard-step done';
  return 'wizard-step';
}

function fmt(n) {
  if (n === null || n === undefined) return '—';
  return Number(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function rowStatusSeverity(status) {
  return { pending: 'warn', onboarded: 'success', discarded: 'secondary' }[status] || 'secondary';
}

async function runAction(action) {
  if (selectedRows.value.length === 0) {
    toast.add({ severity: 'warn', summary: 'No rows selected', detail: 'Select at least one row first', life: 3000 });
    return;
  }
  const rowIds = selectedRows.value.map((r) => r.id);
  await api.importAction({ action, row_ids: rowIds });
  toast.add({ severity: 'success', summary: 'Updated', detail: `${rowIds.length} row(s) updated`, life: 2500 });
  await load();
}

function goToStep(index) {
  activeStepIndex.value = index;
  selectedRows.value = [];
}

function nextStep() {
  if (activeStepIndex.value < steps.length - 1) {
    goToStep(activeStepIndex.value + 1);
  } else {
    router.push({ name: 'imports' });
  }
}

onMounted(load);
</script>

<template>
  <div class="page module-accent" style="--accent-color: var(--module-imports)" v-if="importInfo">
    <div class="page-header">
      <div>
        <h1>{{ importInfo.import_number }}</h1>
        <p class="page-subtitle">
          Supplier: {{ importInfo.supplier_name }} · Product Group: {{ importInfo.product_group_name }} ·
          Imported by {{ importInfo.imported_by }}
        </p>
      </div>
      <Tag :value="importInfo.status" severity="warn" />
    </div>

    <div class="stat-strip">
      <div class="stat-pill" v-for="s in steps" :key="s.key">
        <span class="stat-value">{{ summary[s.key]?.total || 0 }}</span>
        <span class="stat-label">{{ s.label }}</span>
      </div>
    </div>

    <div class="wizard-steps">
      <button
        v-for="(s, i) in steps"
        :key="s.key"
        :class="stepClass(i)"
        @click="goToStep(i)"
        type="button"
      >
        {{ i + 1 }}. {{ s.label }}
        <span v-if="summary[s.key]" class="mono">({{ summary[s.key].pending }} pending)</span>
      </button>
    </div>

    <div class="card-block">
      <p class="page-subtitle" style="margin-bottom: 1rem">{{ activeStep.description }}</p>

      <DataTable
        :value="activeRows"
        :loading="loading"
        dataKey="id"
        v-model:selection="selectedRows"
        stripedRows
        responsiveLayout="scroll"
      >
        <Column selectionMode="multiple" style="width: 3rem" />
        <Column field="style_code" header="Style Code">
          <template #body="{ data }"><span class="mono">{{ data.style_code }}</span></template>
        </Column>
        <Column field="style_name" header="Style Name" />
        <Column field="colour" header="Colour" />
        <Column field="gender" header="Gender" />
        <Column field="factory" header="Factory" />
        <Column field="origin" header="Origin" />
        <Column field="prev_cost" header="Prev Cost">
          <template #body="{ data }"><span class="mono">{{ fmt(data.prev_cost) }}</span></template>
        </Column>
        <Column field="new_cost" header="New Cost" v-if="activeStep.key === 'existing' || activeStep.key === 'non_continuable'">
          <template #body="{ data }"><span class="mono">{{ fmt(data.new_cost) }}</span></template>
        </Column>
        <Column field="fob_price" header="FOB Price" v-if="activeStep.key === 'sample' || activeStep.key === 'new'">
          <template #body="{ data }"><span class="mono">{{ fmt(data.fob_price) }}</span></template>
        </Column>
        <Column field="sample_match" header="Sample Match" v-if="activeStep.key === 'sample'" />
        <Column field="buy_window" header="Buy Window" v-if="activeStep.key === 'new'" />
        <Column field="row_status" header="Row Status">
          <template #body="{ data }">
            <Tag :value="data.row_status" :severity="rowStatusSeverity(data.row_status)" />
          </template>
        </Column>
        <template #empty>
          <div class="empty-state">No rows in this classification.</div>
        </template>
      </DataTable>

      <div class="action-bar">
        <div class="action-buttons">
          <template v-if="activeStep.key === 'non_continuable'">
            <Button label="Update to Inline" icon="pi pi-check" @click="runAction('set_active')" />
            <Button label="Discard" icon="pi pi-times" severity="secondary" @click="runAction('discard')" />
          </template>
          <template v-else-if="activeStep.key === 'inactive'">
            <Button label="Set Inactive" icon="pi pi-ban" severity="warn" @click="runAction('set_inactive')" />
            <Button label="Keep Active" icon="pi pi-check" severity="secondary" @click="runAction('set_active')" />
          </template>
          <template v-else>
            <Button label="Onboard Selected" icon="pi pi-check" @click="runAction('onboard')" />
            <Button label="Discard Selected" icon="pi pi-times" severity="secondary" @click="runAction('discard')" />
          </template>
        </div>
        <Button
          :label="activeStepIndex === steps.length - 1 ? 'Finish' : `Continue to ${steps[activeStepIndex + 1]?.label || ''}`"
          icon="pi pi-arrow-right"
          iconPos="right"
          text
          @click="nextStep"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1rem;
  flex-wrap: wrap;
  gap: 0.75rem;
}
.action-buttons {
  display: flex;
  gap: 0.5rem;
}
</style>
