<script setup>
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/Components/ui/dialog";
import { Button } from "@/Components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
import { Skeleton } from "@/Components/ui/skeleton";
import { ArrowDownTrayIcon } from "@heroicons/vue/24/outline";

const props = defineProps({
  show: { type: Boolean, default: false },
  loading: { type: Boolean, default: false },
  columns: { type: Array, default: () => [] },
  rows: { type: Array, default: () => [] },
  importId: { type: Number, required: true },
});

const emit = defineEmits(["close"]);

function downloadCsv() {
  if (!props.importId) return;
  window.location.href = route("imports.missing-keyref-csv", { import: props.importId });
}
</script>

<template>
  <Dialog :open="show" @update:open="(val) => !val && emit('close')">
    <DialogContent class="max-w-6xl max-h-[85vh] overflow-hidden flex flex-col">
      <DialogHeader>
        <div class="flex items-center justify-between">
          <DialogTitle>Vrstice z neobstoječim contract.reference (KEYREF)</DialogTitle>
          <Button
            variant="outline"
            size="sm"
            @click="downloadCsv"
            class="gap-2"
          >
            <ArrowDownTrayIcon class="h-4 w-4" />
            Prenesi CSV
          </Button>
        </div>
      </DialogHeader>
      
      <div class="flex-1 overflow-auto">
        <div v-if="loading" class="space-y-3 p-4">
          <Skeleton v-for="i in 10" :key="i" class="h-12 w-full" />
        </div>
        
        <div v-else-if="!rows.length" class="py-12 text-center">
          <p class="text-sm text-gray-500">Ni zadetkov.</p>
        </div>
        
        <div v-else class="border rounded-lg">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead class="w-24"># vrstica</TableHead>
                <TableHead v-for="(c, i) in columns" :key="i">{{ c }}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              <TableRow v-for="r in rows" :key="r.id">
                <TableCell class="font-medium text-gray-500">{{ r.row_number }}</TableCell>
                <TableCell
                  v-for="(c, i) in columns"
                  :key="i"
                  class="whitespace-pre-wrap wrap-break-word"
                >
                  {{ r.values?.[i] ?? "" }}
                </TableCell>
              </TableRow>
            </TableBody>
          </Table>
        </div>
      </div>
      
      <div class="border-t pt-4 flex justify-end gap-2">
        <Button variant="secondary" @click="emit('close')">Zapri</Button>
      </div>
    </DialogContent>
  </Dialog>
</template>
