<script setup>
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/Components/ui/table";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/Components/ui/select";
import { Checkbox } from "@/Components/ui/checkbox";
import { Input } from "@/Components/ui/input";
import { Badge } from "@/Components/ui/badge";
import { ScrollArea } from "@/Components/ui/scroll-area";

const props = defineProps({
  rows: Array,
  entityOptions: Array,
  isCompleted: Boolean,
  detected: Object,
  detectedNote: String,
  duplicateTargets: Object,
  missingCritical: Array,
  mappingSaved: Boolean,
  mappingSavedCount: Number,
  mappingError: String,
  show: { type: Boolean, default: true },
  fieldsForEntity: Function,
});
const emits = defineEmits(["update:rows", "save"]);

function duplicateTarget(row) {
  if (!row || !row.entity || !row.field) return false;
  return props.duplicateTargets?.has?.(row.entity + "." + row.field) || false;
}
</script>
<template>
  <div v-if="show && rows?.length" class="pt-4">
    <div class="flex items-center justify-between mb-2">
      <h3 class="font-semibold">
        Detected Columns
        <Badge variant="outline" class="ml-2 text-[10px]">{{
          detected?.has_header ? "header" : "positional"
        }}</Badge>
      </h3>
      <div class="text-xs text-muted-foreground">
        detected: {{ detected?.columns?.length || 0 }}, rows: {{ rows.length }},
        delimiter: {{ detected?.delimiter || "auto" }}
      </div>
    </div>
    <p v-if="detectedNote" class="text-xs text-muted-foreground mb-2">
      {{ detectedNote }}
    </p>
    <div class="relative border rounded-lg">
      <ScrollArea class="h-[420px]">
        <Table>
          <TableHeader class="sticky top-0 z-10 bg-background">
            <TableRow class="hover:bg-transparent">
              <TableHead class="w-[180px] bg-muted/95 backdrop-blur"
                >Source column</TableHead
              >
              <TableHead class="w-[150px] bg-muted/95 backdrop-blur">Entity</TableHead>
              <TableHead class="w-[150px] bg-muted/95 backdrop-blur">Field</TableHead>
              <TableHead class="w-[140px] bg-muted/95 backdrop-blur">Meta key</TableHead>
              <TableHead class="w-[120px] bg-muted/95 backdrop-blur">Meta type</TableHead>
              <TableHead class="w-[120px] bg-muted/95 backdrop-blur">Transform</TableHead>
              <TableHead class="w-[130px] bg-muted/95 backdrop-blur"
                >Apply mode</TableHead
              >
              <TableHead class="w-[60px] text-center bg-muted/95 backdrop-blur"
                >Skip</TableHead
              >
            </TableRow>
          </TableHeader>
          <TableBody>
            <TableRow
              v-for="(row, idx) in rows"
              :key="idx"
              :class="duplicateTarget(row) ? 'bg-destructive/10' : ''"
            >
              <TableCell class="font-medium">{{ row.source_column }}</TableCell>
              <TableCell>
                <Select
                  :model-value="row.entity || ''"
                  @update:model-value="(val) => (row.entity = val || '')"
                  :disabled="isCompleted"
                >
                  <SelectTrigger class="h-8 text-xs">
                    <SelectValue placeholder="Select entity..." />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectGroup>
                      <SelectItem
                        v-for="opt in entityOptions"
                        :key="opt.value"
                        :value="opt.value"
                        >{{ opt.label }}</SelectItem
                      >
                    </SelectGroup>
                  </SelectContent>
                </Select>
              </TableCell>
              <TableCell>
                <Select
                  :model-value="row.field || ''"
                  @update:model-value="(val) => (row.field = val || '')"
                  :disabled="isCompleted"
                  :class="duplicateTarget(row) ? 'border-destructive' : ''"
                >
                  <SelectTrigger
                    class="h-8 text-xs"
                    :class="
                      duplicateTarget(row) ? 'border-destructive bg-destructive/10' : ''
                    "
                  >
                    <SelectValue placeholder="Select field..." />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectGroup>
                      <SelectItem
                        v-for="f in fieldsForEntity(row.entity)"
                        :key="f"
                        :value="f"
                        >{{ f }}</SelectItem
                      >
                    </SelectGroup>
                  </SelectContent>
                </Select>
              </TableCell>
              <TableCell>
                <Input
                  v-if="row.field === 'meta'"
                  v-model="(row.options ||= {}).key"
                  type="text"
                  class="h-8 text-xs"
                  placeholder="e.g. monthly_rent"
                  :disabled="isCompleted"
                />
                <span v-else class="text-muted-foreground text-xs">—</span>
              </TableCell>
              <TableCell>
                <Select
                  v-if="row.field === 'meta'"
                  :model-value="(row.options ||= {}).type || 'string'"
                  @update:model-value="(val) => ((row.options ||= {}).type = val)"
                  :disabled="isCompleted"
                >
                  <SelectTrigger class="h-8 text-xs">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectGroup>
                      <SelectItem value="string">string</SelectItem>
                      <SelectItem value="number">number</SelectItem>
                      <SelectItem value="date">date</SelectItem>
                      <SelectItem value="boolean">boolean</SelectItem>
                    </SelectGroup>
                  </SelectContent>
                </Select>
                <span v-else class="text-muted-foreground text-xs">—</span>
              </TableCell>
              <TableCell>
                <Select
                  :model-value="row.transform || 'none'"
                  @update:model-value="
                    (val) => (row.transform = val === 'none' ? '' : val)
                  "
                  :disabled="isCompleted"
                >
                  <SelectTrigger class="h-8 text-xs">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectGroup>
                      <SelectItem value="none">None</SelectItem>
                      <SelectItem value="trim">Trim</SelectItem>
                      <SelectItem value="upper">Uppercase</SelectItem>
                      <SelectItem value="lower">Lowercase</SelectItem>
                    </SelectGroup>
                  </SelectContent>
                </Select>
              </TableCell>
              <TableCell>
                <Select
                  :model-value="row.apply_mode || 'both'"
                  @update:model-value="(val) => (row.apply_mode = val)"
                  :disabled="isCompleted"
                >
                  <SelectTrigger class="h-8 text-xs">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectGroup>
                      <SelectItem value="keyref">Keyref</SelectItem>
                      <SelectItem value="both">Both</SelectItem>
                      <SelectItem value="insert">Insert only</SelectItem>
                      <SelectItem value="update">Update only</SelectItem>
                    </SelectGroup>
                  </SelectContent>
                </Select>
              </TableCell>
              <TableCell class="text-center">
                <Checkbox
                  :model-value="row.skip"
                  @update:model-value="(val) => (row.skip = val)"
                  :disabled="isCompleted"
                />
              </TableCell>
            </TableRow>
          </TableBody>
        </Table>
      </ScrollArea>
    </div>
    <div
      v-if="mappingSaved"
      class="text-sm text-emerald-700 mt-2 flex items-center gap-2"
    >
      <Badge variant="default" class="bg-emerald-600">Saved</Badge>
      <span>{{ mappingSavedCount }} mappings saved</span>
    </div>
    <div v-else-if="mappingError" class="text-sm text-destructive mt-2">
      {{ mappingError }}
    </div>
    <div v-if="missingCritical?.length" class="mt-2">
      <Badge variant="destructive" class="text-xs"
        >Missing critical: {{ missingCritical.join(", ") }}</Badge
      >
    </div>
  </div>
</template>
