<template>
  <q-page v-if="canReadOrder" class="q-pa-md">

    <!-- =====================================================
         🔹 BAŞLIK + AKSİYONLAR
    ====================================================== -->
    <div class="row items-center justify-between q-mb-md">
      <div class="text-h6 text-weight-bold">
        Üretim İş Emirleri
      </div>

      <q-btn
        v-if="canWriteOrder"
        color="primary"
        icon="add"
        label="Yeni İş Emri"
        @click="goNew"
      />
    </div>

    <!-- =====================================================
         🔹 FİLTRE BAR (ileride genişletilir)
    ====================================================== -->
    <q-card flat bordered class="q-mb-md">
      <q-card-section class="row q-col-gutter-md">

        <div class="col-3">
          <q-input
            v-model="filters.workOrderNo"
            dense
            filled
            label="İş Emri No"
          />
        </div>

        <div class="col-3">
          <q-select
            v-model="filters.productType"
            :options="productTypes"
            dense
            filled
            label="Ürün Tipi"
            clearable
          />
        </div>

        <div class="col-3">
          <q-select
            v-model="filters.status"
            :options="statuses"
            dense
            filled
            label="Durum"
            clearable
          />
        </div>

      </q-card-section>
    </q-card>

    <!-- =====================================================
         📋 İŞ EMRİ LİSTESİ
    ====================================================== -->
    <q-table
      flat
      bordered
      row-key="id"
      :rows="filteredRows"
      :columns="columns"
      :pagination="{ rowsPerPage: 10 }"
      @row-click="goView"
    >
      <!-- 🔹 DURUM BADGE -->
      <template #body-cell-status="props">
        <q-td :props="props">
          <q-badge
            :color="statusColor(props.value)"
            outline
          >
            {{ props.value }}
          </q-badge>
        </q-td>
      </template>
    </q-table>

  </q-page>

  <q-page v-else class="q-pa-md flex flex-center">
    <div class="text-negative text-subtitle1">
      Bu module erisim yetkiniz yok.
    </div>
  </q-page>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { usePermission } from 'src/composables/usePermission'
import { normalizeSearchText } from 'src/utils/searchText'

const { canRead, canWrite } = usePermission()

const canReadOrder   = canRead('order')
const canWriteOrder  = canWrite('order')

const router = useRouter()

// =====================================================
// 🔹 TABLO KOLONLARI
// =====================================================
const columns = [
  {
    name: 'workOrderNo',
    label: 'İş Emri No',
    field: 'workOrderNo',
    align: 'left',
    sortable: true
  },
  {
    name: 'productType',
    label: 'Ürün',
    field: 'productType',
    sortable: true
  },
  {
    name: 'quantity',
    label: 'Adet',
    field: 'quantity',
    align: 'right'
  },
  {
    name: 'deliveryDate',
    label: 'Termin',
    field: 'deliveryDate'
  },
  {
    name: 'status',
    label: 'Durum',
    field: 'status'
  }
]

// =====================================================
// 🔹 MOCK DATA (backend bağlanınca kaldırılacak)
// =====================================================
const rows = ref([
  {
    id: 101,
    workOrderNo: 'UIE-2026-001',
    productType: 'CEKET',
    quantity: 120,
    deliveryDate: '2026-02-15',
    status: 'Taslak'
  },
  {
    id: 102,
    workOrderNo: 'UIE-2026-002',
    productType: 'PANTOLON',
    quantity: 300,
    deliveryDate: '2026-02-20',
    status: 'Onaylandı'
  }
])

// =====================================================
// 🔹 FİLTRELER
// =====================================================
const productTypes = ['CEKET', 'PANTOLON']
const statuses = ['Taslak', 'Onaylandı', 'Üretimde', 'Kapandı']

const filters = ref({
  workOrderNo: '',
  productType: null,
  status: null
})

const filteredRows = computed(() => {
  return rows.value.filter(r => {
    const workOrderNoNeedle = normalizeSearchText(filters.value.workOrderNo)
    if (
      workOrderNoNeedle &&
      !normalizeSearchText(r.workOrderNo).includes(workOrderNoNeedle)
    ) return false

    if (
      filters.value.productType &&
      r.productType !== filters.value.productType
    ) return false

    if (
      filters.value.status &&
      r.status !== filters.value.status
    ) return false

    return true
  })
})

// =====================================================
// 🔹 AKSİYONLAR
// =====================================================
function goNew () {
  if (!canWriteOrder.value) return
  router.push('/app/production-work-orders/new')
}

function goView (evt, row) {
  if (!canReadOrder.value) return
  router.push(`/app/production-work-orders/view/${row.id}`)
}

function statusColor (status) {
  switch (status) {
    case 'Taslak': return 'grey'
    case 'Onaylandı': return 'blue'
    case 'Üretimde': return 'orange'
    case 'Kapandı': return 'green'
    default: return 'grey'
  }
}
</script>
