<script setup>
import AppLayout from '@/Layouts/AppLayout.vue'
import SectionTitle from '@/Components/SectionTitle.vue'
import PrimaryButton from '@/Components/PrimaryButton.vue'
import DialogModal from '@/Components/DialogModal.vue'
import ConfirmationModal from '@/Components/ConfirmationModal.vue'
import InputLabel from '@/Components/InputLabel.vue'
import InputError from '@/Components/InputError.vue'
import { useForm, router } from '@inertiajs/vue3'
import { ref } from 'vue'

const props = defineProps({
  configs: Array,
  types: Array,
  segments: Array,
})

// create modal
const showCreate = ref(false)
const openCreate = () => { showCreate.value = true }
const closeCreate = () => { showCreate.value = false; createForm.reset() }
const createForm = useForm({ contract_type_id: null, segment_id: null, is_initial: false })
const submitCreate = () => {
  createForm.post(route('settings.contractConfigs.store'), {
    preserveScroll: true,
    onSuccess: () => closeCreate(),
  })
}

// inline edit
const editing = ref(null)
const editForm = useForm({ segment_id: null, is_initial: false, active: true })
const openEdit = (row) => { editing.value = row; editForm.segment_id = row?.segment_id ?? row?.segment?.id; editForm.is_initial = !!row.is_initial; editForm.active = !!row.active }
const closeEdit = () => { editing.value = null }
const submitEdit = () => {
  if (!editing.value) return
  editForm.put(route('settings.contractConfigs.update', editing.value.id), {
    preserveScroll: true,
    onSuccess: () => closeEdit(),
  })
}

// delete confirmation
const showDelete = ref(false)
const toDelete = ref(null)
const confirmDelete = (row) => { toDelete.value = row; showDelete.value = true }
const cancelDelete = () => { toDelete.value = null; showDelete.value = false }
const destroyConfig = () => {
  if (!toDelete.value) return
  router.delete(route('settings.contractConfigs.destroy', toDelete.value.id), {
    preserveScroll: true,
    onFinish: () => cancelDelete(),
  })
}
</script>

<template>
  <AppLayout title="Settings: Contract Configurations">
    <template #header />
    <div class="pt-12">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg border-l-4 border-indigo-400">
          <div class="p-4 flex items-center justify-between">
            <SectionTitle>
              <template #title>Contract configurations</template>
            </SectionTitle>
            <PrimaryButton @click="openCreate">+ New</PrimaryButton>
          </div>
          <div class="px-4 pb-4">
            <table class="min-w-full text-left text-sm">
              <thead>
                <tr class="border-b">
                  <th class="py-2 pr-4">Type</th>
                  <th class="py-2 pr-4">Segment</th>
                  <th class="py-2 pr-4">Active</th>
                  <th class="py-2 pr-4 text-right">Actions</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="cfg in configs" :key="cfg.id" class="border-b last:border-0">
                  <td class="py-2 pr-4">{{ cfg.type?.name }}</td>
                  <td class="py-2 pr-4">{{ cfg.segment?.name }} <span v-if="cfg.is_initial" class="ml-2 text-xs text-indigo-600">(initial)</span></td>
                  <td class="py-2 pr-4">{{ cfg.active ? 'Yes' : 'No' }}</td>
      <td class="py-2 pr-4 text-right">
            <button class="px-2 py-1 text-indigo-600 hover:underline" @click="openEdit(cfg)">Edit</button>
            <button class="ml-2 px-2 py-1 text-red-600 hover:underline" @click="confirmDelete(cfg)">Delete</button>
                  </td>
                </tr>
                <tr v-if="!configs || configs.length === 0">
                  <td colspan="4" class="py-6 text-center text-gray-500">No configurations.</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- create modal -->
    <DialogModal :show="showCreate" @close="closeCreate">
      <template #title>New Contract Configuration</template>
      <template #content>
        <div class="space-y-4">
          <div>
            <InputLabel for="type">Contract Type</InputLabel>
            <select id="type" v-model="createForm.contract_type_id" class="mt-1 w-full rounded border-gray-300 focus:border-indigo-500 focus:ring-indigo-500">
              <option :value="null" disabled>-- select type --</option>
              <option v-for="t in types" :key="t.id" :value="t.id">{{ t.name }}</option>
            </select>
            <InputError :message="createForm.errors.contract_type_id" />
          </div>
          <div>
            <InputLabel for="segment">Segment</InputLabel>
            <select id="segment" v-model="createForm.segment_id" class="mt-1 w-full rounded border-gray-300 focus:border-indigo-500 focus:ring-indigo-500">
              <option :value="null" disabled>-- select segment --</option>
              <option v-for="s in segments" :key="s.id" :value="s.id">{{ s.name }}</option>
            </select>
            <InputError :message="createForm.errors.segment_id" />
            <div class="mt-3 flex items-center gap-2">
              <input id="is_initial" type="checkbox" v-model="createForm.is_initial" class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500">
              <label for="is_initial" class="text-sm text-gray-700">Mark as initial</label>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <button class="px-4 py-2 rounded bg-gray-200" @click="closeCreate">Cancel</button>
  <PrimaryButton class="ml-2" :disabled="createForm.processing || !createForm.contract_type_id || !createForm.segment_id" @click="submitCreate">Create</PrimaryButton>
      </template>
    </DialogModal>

    <!-- simple inline edit dialog -->
    <DialogModal :show="!!editing" @close="closeEdit">
      <template #title>Edit Configuration</template>
      <template #content>
        <div class="space-y-4">
          <div>
            <InputLabel>Segment</InputLabel>
            <select v-model="editForm.segment_id" class="mt-1 w-full rounded border-gray-300 focus:border-indigo-500 focus:ring-indigo-500">
              <option v-for="s in segments" :key="s.id" :value="s.id">{{ s.name }}</option>
            </select>
            <InputError :message="editForm.errors.segment_id" />
          </div>
          <div class="flex items-center gap-2">
            <input id="is_initial_edit" type="checkbox" v-model="editForm.is_initial" class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500">
            <label for="is_initial_edit" class="text-sm text-gray-700">Initial</label>
          </div>
          <div class="flex items-center gap-2">
            <input id="active" type="checkbox" v-model="editForm.active" class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500">
            <label for="active" class="text-sm text-gray-700">Active</label>
          </div>
        </div>
      </template>
      <template #footer>
        <button class="px-4 py-2 rounded bg-gray-200" @click="closeEdit">Cancel</button>
  <PrimaryButton class="ml-2" :disabled="editForm.processing || !editForm.segment_id" @click="submitEdit">Save</PrimaryButton>
      </template>
    </DialogModal>
  </AppLayout>
  <ConfirmationModal :show="showDelete" @close="cancelDelete">
    <template #title>
      Delete configuration
    </template>
    <template #content>
      Are you sure you want to delete configuration for type "{{ toDelete?.type?.name }}"?
    </template>
    <template #footer>
      <button @click="cancelDelete" class="px-4 py-2 rounded bg-gray-200 hover:bg-gray-300 me-2">Cancel</button>
      <PrimaryButton @click="destroyConfig">Delete</PrimaryButton>
    </template>
  </ConfirmationModal>
</template>
