<script setup>
import { ref, onMounted, watch } from 'vue';
import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import Button from 'primevue/button';
import Select from 'primevue/select';
import InputText from 'primevue/inputtext';
import InputNumber from 'primevue/inputnumber';
import DatePicker from 'primevue/datepicker';
import Checkbox from 'primevue/checkbox';
import Dialog from 'primevue/dialog';
import Tag from 'primevue/tag';
import { useToast } from 'primevue/usetoast';
import api from '../api.js';

const toast = useToast();

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

const filters = ref({ product_group_id: null, search: '', status: null });
const statusOptions = ['Active', 'Non-Replenishable', 'Pending', 'Clearance', 'Discontinued'];

async function loadFilters() {
  const { data } = await api.getProductGroups();
  productGroups.value = data;
}

async function loadCostings() {
  loading.value = true;
  const params = {};
  if (filters.value.product_group_id) params.product_group_id = filters.value.product_group_id;
  if (filters.value.search) params.search = filters.value.search;
  if (filters.value.status) params.status = filters.value.status;
  const { data } = await api.getCostings(params);
  rows.value = data;
  loading.value = false;
}

let searchTimer = null;
watch(filters, () => {
  clearTimeout(searchTimer);
  searchTimer = setTimeout(loadCostings, 250);
}, { deep: true });

function fmt(n) {
  return Number(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function statusSeverity(status) {
  return { Active: 'success', 'Non-Replenishable': 'warn', Pending: 'info', Clearance: 'warn', Discontinued: 'danger' }[status] || 'secondary';
}

// ---- Edit price modal ----
const editVisible = ref(false);
const editForm = ref({ costing_id: null, style_code: '', current_std: 0, current_group: 0, new_std_price: null, override_group_price: false, new_group_price: null, note: '' });

function openEdit(row) {
  editForm.value = {
    costing_id: row.id,
    style_code: row.style_code,
    current_std: row.std_price,
    current_group: row.group_price,
    new_std_price: row.std_price,
    override_group_price: false,
    new_group_price: row.group_price,
    note: '',
  };
  editVisible.value = true;
}

async function submitEdit() {
  try {
    await api.editPrice(editForm.value);
    toast.add({ severity: 'success', summary: 'Price updated', detail: `${editForm.value.style_code} price adjusted`, life: 3000 });
    editVisible.value = false;
    loadCostings();
  } catch (e) {
    toast.add({ severity: 'error', summary: 'Error', detail: e.response?.data?.error || 'Update failed', life: 4000 });
  }
}

// ---- Create costing modal ----
const createVisible = ref(false);
const createForm = ref({
  style_id: null, effective_date: new Date(), delivery_from: new Date(), delivery_to: new Date(),
  std_price: null, group_price: null, rrp: null, base_cost: null, duty: 0, landing: 0, freight: 0,
  overhead_package: 0, overhead_insurance: 0, rejection_cost: 0, selling_cost: 0,
});

async function openCreate() {
  createVisible.value = true;
  if (styles.value.length === 0) {
    const { data } = await api.getStyles();
    styles.value = data.map((s) => ({ ...s, label: `${s.style_code} — ${s.style_name}` }));
  }
}

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

async function submitCreate() {
  try {
    const payload = {
      ...createForm.value,
      effective_date: toDateStr(createForm.value.effective_date),
      delivery_from: toDateStr(createForm.value.delivery_from),
      delivery_to: toDateStr(createForm.value.delivery_to),
    };
    await api.createCosting(payload);
    toast.add({ severity: 'success', summary: 'Costing created', detail: 'Submitted for approval', life: 3000 });
    createVisible.value = false;
    loadCostings();
  } catch (e) {
    toast.add({ severity: 'error', summary: 'Error', detail: e.response?.data?.error || 'Create failed', life: 4000 });
  }
}

onMounted(async () => {
  await loadFilters();
  await loadCostings();
});
</script>

<template>
  <div class="page module-accent" style="--accent-color: var(--module-pricing)">
    <div class="page-header">
      <div>
        <h1>Pricing &amp; Costing</h1>
        <p class="page-subtitle">Review costings by product group, adjust prices, and create new costings for approval.</p>
      </div>
      <Button label="Create Costing" icon="pi pi-plus" @click="openCreate" />
    </div>

    <div class="filter-bar card-block">
      <Select
        v-model="filters.product_group_id"
        :options="productGroups"
        optionLabel="name"
        optionValue="id"
        placeholder="All Product Groups"
        showClear
        style="min-width: 220px"
      />
      <Select v-model="filters.status" :options="statusOptions" placeholder="All Statuses" showClear style="min-width: 180px" />
      <InputText v-model="filters.search" placeholder="Search by style code, name or colour..." style="min-width: 260px" />
    </div>

    <div class="card-block">
      <DataTable :value="rows" :loading="loading" dataKey="id" stripedRows scrollable scrollHeight="600px" responsiveLayout="scroll">
        <Column field="style_code" header="Style Code" frozen>
          <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="season" header="Season" />
        <Column field="effective_date" header="Effective Date" />
        <Column field="std_price" header="Std Price">
          <template #body="{ data }"><span class="mono">{{ fmt(data.std_price) }}</span></template>
        </Column>
        <Column field="group_price" header="Group Price">
          <template #body="{ data }"><span class="mono">{{ fmt(data.group_price) }}</span></template>
        </Column>
        <Column field="rrp" header="RRP">
          <template #body="{ data }"><span class="mono">{{ fmt(data.rrp) }}</span></template>
        </Column>
        <Column field="total_cost" header="Total Cost">
          <template #body="{ data }"><span class="mono">{{ fmt(data.total_cost) }}</span></template>
        </Column>
        <Column field="style_status" header="Status">
          <template #body="{ data }">
            <Tag :value="data.style_status" :severity="statusSeverity(data.style_status)" />
          </template>
        </Column>
        <Column header="" style="width: 90px">
          <template #body="{ data }">
            <Button icon="pi pi-pencil" text rounded aria-label="Edit price" @click="openEdit(data)" />
          </template>
        </Column>
        <template #empty>
          <div class="empty-state">No costings match these filters.</div>
        </template>
      </DataTable>
    </div>

    <!-- Edit Price modal -->
    <Dialog v-model:visible="editVisible" modal header="Edit Price" style="width: 460px">
      <p class="page-subtitle" style="margin-bottom: 1rem">
        <span class="mono">{{ editForm.style_code }}</span> — current standard
        <span class="mono">R {{ fmt(editForm.current_std) }}</span>, current group
        <span class="mono">R {{ fmt(editForm.current_group) }}</span>
      </p>

      <div class="field">
        <label>New Standard Price</label>
        <InputNumber v-model="editForm.new_std_price" mode="currency" currency="ZAR" locale="en-ZA" fluid />
      </div>

      <div class="field" style="display: flex; align-items: center; gap: 0.5rem">
        <Checkbox v-model="editForm.override_group_price" binary inputId="override" />
        <label for="override">Override Group Price (optional)</label>
      </div>

      <div class="field" v-if="editForm.override_group_price">
        <label>New Group Price</label>
        <InputNumber v-model="editForm.new_group_price" mode="currency" currency="ZAR" locale="en-ZA" fluid />
      </div>
      <p v-else class="page-subtitle" style="margin-bottom: 1rem">
        Group price will auto-calculate from the new standard price.
      </p>

      <div class="field">
        <label>Note (optional)</label>
        <InputText v-model="editForm.note" fluid placeholder="Reason for adjustment" />
      </div>

      <template #footer>
        <Button label="Cancel" text @click="editVisible = false" />
        <Button label="Save Price" @click="submitEdit" />
      </template>
    </Dialog>

    <!-- Create Costing modal -->
    <Dialog v-model:visible="createVisible" modal header="Create Costing" style="width: 560px">
      <div class="field">
        <label>Style</label>
        <Select v-model="createForm.style_id" :options="styles" optionLabel="label" optionValue="id" filter placeholder="Select a style" fluid />
      </div>

      <div class="grid-2">
        <div class="field">
          <label>Effective Date</label>
          <DatePicker v-model="createForm.effective_date" dateFormat="yy-mm-dd" fluid />
        </div>
        <div class="field">
          <label>Delivery From</label>
          <DatePicker v-model="createForm.delivery_from" dateFormat="yy-mm-dd" fluid />
        </div>
      </div>

      <div class="grid-2">
        <div class="field">
          <label>Standard Price</label>
          <InputNumber v-model="createForm.std_price" mode="currency" currency="ZAR" locale="en-ZA" fluid />
        </div>
        <div class="field">
          <label>Group Price</label>
          <InputNumber v-model="createForm.group_price" mode="currency" currency="ZAR" locale="en-ZA" fluid />
        </div>
      </div>

      <div class="grid-2">
        <div class="field">
          <label>RRP</label>
          <InputNumber v-model="createForm.rrp" mode="currency" currency="ZAR" locale="en-ZA" fluid />
        </div>
        <div class="field">
          <label>Base Cost</label>
          <InputNumber v-model="createForm.base_cost" mode="currency" currency="ZAR" locale="en-ZA" fluid />
        </div>
      </div>

      <div class="grid-3">
        <div class="field">
          <label>Duty</label>
          <InputNumber v-model="createForm.duty" mode="decimal" :minFractionDigits="2" fluid />
        </div>
        <div class="field">
          <label>Landing</label>
          <InputNumber v-model="createForm.landing" mode="decimal" :minFractionDigits="2" fluid />
        </div>
        <div class="field">
          <label>Freight</label>
          <InputNumber v-model="createForm.freight" mode="decimal" :minFractionDigits="2" fluid />
        </div>
      </div>

      <template #footer>
        <Button label="Cancel" text @click="createVisible = false" />
        <Button label="Submit for Approval" @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;
}
.grid-3 {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 1rem;
}
</style>
