<script setup>
import AppLayout from "@/Layouts/AppLayout.vue";
import AppCard from "@/Components/app/ui/card/AppCard.vue";
import CardTitle from "@/Components/ui/card/CardTitle.vue";
import { Button } from "@/Components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/Components/ui/dialog";
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogFooter,
} from "@/Components/ui/alert-dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/Components/ui/select";
import { Checkbox } from "@/Components/ui/checkbox";
import InputLabel from "@/Components/InputLabel.vue";
import InputError from "@/Components/InputError.vue";
import DataTableClient from "@/Components/DataTable/DataTableClient.vue";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/Components/ui/dropdown-menu";
import { useForm, router } from "@inertiajs/vue3";
import { ref, nextTick } from "vue";
import {
  MoreHorizontal,
  Pencil,
  Trash,
  FileText,
  Badge as BadgeIcon,
  Check as CheckIcon,
} from "lucide-vue-next";

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 showEdit = ref(false);
const editing = ref(null);
const editFormIsInitial = ref(false);
const editFormActive = ref(false);
const editForm = useForm({ segment_id: null, is_initial: false, active: false });
const openEdit = (row) => {
  editing.value = row;
  editForm.clearErrors();

  // Set values
  editForm.segment_id = row?.segment_id ?? row?.segment?.id ?? null;
  editFormIsInitial.value = row.is_initial === 1 || row.is_initial === true;
  editFormActive.value = row.active === 1 || row.active === true;

  showEdit.value = true;
};
const closeEdit = () => {
  showEdit.value = false;
  editing.value = null;
  editFormIsInitial.value = false;
  editFormActive.value = false;
  editForm.reset();
  editForm.clearErrors();
};
const submitEdit = () => {
  if (!editing.value) return;
  editForm.is_initial = editFormIsInitial.value;
  editForm.active = editFormActive.value;
  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(),
  });
};

// DataTable state
const sort = ref({ key: null, direction: null });
const page = ref(1);
const pageSize = ref(25);
const columns = [
  { key: "id", label: "ID", sortable: true, class: "w-16" },
  { key: "type", label: "Type", sortable: false },
  { key: "segment", label: "Segment", sortable: false },
  { key: "active", label: "Active", sortable: false, class: "w-24" },
];
</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">
        <AppCard
          title=""
          padding="none"
          class="p-0! gap-0"
          header-class="py-3! px-4 gap-0 text-muted-foreground"
          body-class=""
        >
          <template #header>
            <div class="flex items-center justify-between w-full">
              <div class="flex items-center gap-2">
                <FileText :size="18" />
                <CardTitle class="uppercase">Contract configurations</CardTitle>
              </div>
              <Button @click="openCreate">+ New</Button>
            </div>
          </template>
          <DataTableClient
            :columns="columns"
            :rows="configs"
            :sort="sort"
            :search="''"
            :page="page"
            :pageSize="pageSize"
            :showToolbar="false"
            :showPagination="true"
            @update:sort="(v) => (sort = v)"
            @update:page="(v) => (page = v)"
            @update:pageSize="(v) => (pageSize = v)"
          >
            <template #cell-type="{ row }">
              {{ row.type?.name }}
            </template>
            <template #cell-segment="{ row }">
              <div class="flex items-center gap-2">
                {{ row.segment?.name }}
                <CheckIcon v-if="row.is_initial" class="w-5 h-5 text-primary" />
              </div>
            </template>
            <template #cell-active="{ row }">
              <div class="flex items-center">
                <div
                  class="w-3 h-3 rounded-full"
                  :class="row.active ? 'bg-green-500' : 'bg-red-500'"
                ></div>
              </div>
            </template>
            <template #actions="{ row }">
              <DropdownMenu>
                <DropdownMenuTrigger as-child>
                  <Button variant="ghost" size="icon">
                    <MoreHorizontal class="w-4 h-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuItem @click="openEdit(row)">
                    <Pencil class="w-4 h-4 mr-2" />
                    Uredi
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    @click="confirmDelete(row)"
                    class="text-red-600 focus:text-red-600"
                  >
                    <Trash class="w-4 h-4 mr-2" />
                    Izbriši
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </template>
          </DataTableClient>
        </AppCard>
      </div>
    </div>

    <!-- create modal -->
    <Dialog v-model:open="showCreate">
      <DialogContent class="max-w-xl">
        <DialogHeader>
          <DialogTitle>New Contract Configuration</DialogTitle>
        </DialogHeader>
        <div class="space-y-4">
          <div>
            <InputLabel for="type">Contract Type</InputLabel>
            <Select v-model="createForm.contract_type_id">
              <SelectTrigger id="type" class="w-full">
                <SelectValue placeholder="-- select type --" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem v-for="t in types" :key="t.id" :value="t.id">
                  {{ t.name }}
                </SelectItem>
              </SelectContent>
            </Select>
            <InputError :message="createForm.errors.contract_type_id" class="mt-1" />
          </div>
          <div>
            <InputLabel for="segment">Segment</InputLabel>
            <Select v-model="createForm.segment_id">
              <SelectTrigger id="segment" class="w-full">
                <SelectValue placeholder="-- select segment --" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem v-for="s in segments" :key="s.id" :value="s.id">
                  {{ s.name }}
                </SelectItem>
              </SelectContent>
            </Select>
            <InputError :message="createForm.errors.segment_id" class="mt-1" />
            <div class="mt-3 flex items-center gap-2">
              <Checkbox id="is_initial" v-model="createForm.is_initial" />
              <InputLabel for="is_initial" class="text-sm font-normal cursor-pointer"
                >Mark as initial</InputLabel
              >
            </div>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" @click="closeCreate">Cancel</Button>
          <Button
            @click="submitCreate"
            :disabled="
              createForm.processing ||
              !createForm.contract_type_id ||
              !createForm.segment_id
            "
            >Create</Button
          >
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <!-- simple inline edit dialog -->
    <Dialog v-model:open="showEdit">
      <DialogContent class="max-w-xl">
        <DialogHeader>
          <DialogTitle>Edit Configuration</DialogTitle>
        </DialogHeader>
        <div class="space-y-4">
          <div>
            <InputLabel>Segment</InputLabel>
            <Select v-model="editForm.segment_id">
              <SelectTrigger class="w-full">
                <SelectValue placeholder="-- select segment --" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem v-for="s in segments" :key="s.id" :value="s.id">
                  {{ s.name }}
                </SelectItem>
              </SelectContent>
            </Select>
            <InputError :message="editForm.errors.segment_id" class="mt-1" />
          </div>
          <div class="flex items-center gap-2">
            <Checkbox id="is_initial_edit" v-model="editFormIsInitial" />
            <InputLabel for="is_initial_edit" class="text-sm font-normal cursor-pointer"
              >Initial</InputLabel
            >
          </div>
          <div class="flex items-center gap-2">
            <Checkbox id="active" v-model="editFormActive" />
            <InputLabel for="active" class="text-sm font-normal cursor-pointer"
              >Active</InputLabel
            >
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" @click="closeEdit">Cancel</Button>
          <Button
            @click="submitEdit"
            :disabled="editForm.processing || !editForm.segment_id"
            >Save</Button
          >
        </DialogFooter>
      </DialogContent>
    </Dialog>
  </AppLayout>
  <AlertDialog v-model:open="showDelete">
    <AlertDialogContent>
      <AlertDialogHeader>
        <AlertDialogTitle>Delete configuration</AlertDialogTitle>
      </AlertDialogHeader>
      <div class="text-sm text-muted-foreground">
        Are you sure you want to delete configuration for type "{{
          toDelete?.type?.name
        }}"?
      </div>
      <AlertDialogFooter>
        <Button variant="outline" @click="cancelDelete">Cancel</Button>
        <Button variant="destructive" @click="destroyConfig">Delete</Button>
      </AlertDialogFooter>
    </AlertDialogContent>
  </AlertDialog>
</template>
