<script setup>
import { ref, onMounted } from 'vue';
import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import Button from 'primevue/button';
import Dialog from 'primevue/dialog';
import InputText from 'primevue/inputtext';
import Select from 'primevue/select';
import Tag from 'primevue/tag';
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';
import api from '../api.js';

const toast = useToast();
const confirm = useConfirm();

const rows = ref([]);
const loading = ref(true);
const dialogVisible = ref(false);
const isEditing = ref(false);

const statusOptions = ['Active', 'Inactive'];
const form = ref({ id: null, code: '', name: '', brand: '', status: 'Active' });

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

function openCreate() {
  isEditing.value = false;
  form.value = { id: null, code: '', name: '', brand: '', status: 'Active' };
  dialogVisible.value = true;
}

function openEdit(row) {
  isEditing.value = true;
  form.value = { ...row };
  dialogVisible.value = true;
}

async function save() {
  try {
    if (isEditing.value) {
      await api.updateProductGroup(form.value);
      toast.add({ severity: 'success', summary: 'Updated', detail: `${form.value.code} saved`, life: 3000 });
    } else {
      await api.createProductGroup(form.value);
      toast.add({ severity: 'success', summary: 'Created', detail: `${form.value.code} added`, life: 3000 });
    }
    dialogVisible.value = false;
    load();
  } catch (e) {
    toast.add({ severity: 'error', summary: 'Error', detail: e.response?.data?.error || 'Save failed', life: 4000 });
  }
}

function remove(row) {
  confirm.require({
    message: `Delete product group ${row.code}? This cannot be undone.`,
    header: 'Confirm deletion',
    icon: 'pi pi-exclamation-triangle',
    acceptLabel: 'Delete',
    rejectLabel: 'Cancel',
    acceptClass: 'p-button-danger',
    accept: async () => {
      await api.deleteProductGroup(row.id);
      toast.add({ severity: 'info', summary: 'Deleted', detail: `${row.code} removed`, life: 3000 });
      load();
    },
  });
}

onMounted(load);
</script>

<template>
  <div class="page module-accent" style="--accent-color: var(--module-product-groups)">
    <div class="page-header">
      <div>
        <h1>Product Groups</h1>
        <p class="page-subtitle">Brands and product groups that styles roll up under.</p>
      </div>
      <Button label="New Product Group" icon="pi pi-plus" @click="openCreate" />
    </div>

    <div class="card-block">
      <DataTable :value="rows" :loading="loading" dataKey="id" stripedRows responsiveLayout="scroll">
        <Column field="code" header="Code">
          <template #body="{ data }"><span class="mono">{{ data.code }}</span></template>
        </Column>
        <Column field="name" header="Name" />
        <Column field="brand" header="Brand" />
        <Column field="style_count" header="Styles" />
        <Column field="status" header="Status">
          <template #body="{ data }">
            <Tag :value="data.status" :severity="data.status === 'Active' ? 'success' : 'secondary'" />
          </template>
        </Column>
        <Column header="" style="width: 110px">
          <template #body="{ data }">
            <Button icon="pi pi-pencil" text rounded @click="openEdit(data)" />
            <Button icon="pi pi-trash" text rounded severity="danger" @click="remove(data)" />
          </template>
        </Column>
        <template #empty>
          <div class="empty-state">No product groups yet. Create one to get started.</div>
        </template>
      </DataTable>
    </div>

    <Dialog v-model:visible="dialogVisible" modal :header="isEditing ? 'Edit Product Group' : 'New Product Group'" style="width: 420px">
      <div class="field">
        <label>Code</label>
        <InputText v-model="form.code" fluid placeholder="PG-005" />
      </div>
      <div class="field">
        <label>Name</label>
        <InputText v-model="form.name" fluid placeholder="Product Group 5" />
      </div>
      <div class="field">
        <label>Brand</label>
        <InputText v-model="form.brand" fluid placeholder="Brand 1" />
      </div>
      <div class="field">
        <label>Status</label>
        <Select v-model="form.status" :options="statusOptions" fluid />
      </div>
      <template #footer>
        <Button label="Cancel" text @click="dialogVisible = false" />
        <Button label="Save" @click="save" />
      </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;
}
</style>
