<script setup lang="ts">
import { computed } from "vue";
import { parseDate } from "@internationalized/date";
import { CalendarIcon } from "lucide-vue-next";
import Calendar from "@/components/ui/calendar/Calendar.vue";
import Popover from "@/components/ui/Popover.vue";
import PopoverContent from "@/components/ui/PopoverContent.vue";
import PopoverTrigger from "@/components/ui/PopoverTrigger.vue";
import UiButton from "@/components/ui/Button.vue";
import { cn } from "@/lib/utils";
import type { FieldDefinition } from "./types";

const props = defineProps<{
  field: FieldDefinition;
  modelValue?: unknown;
  error?: string;
}>();

const emit = defineEmits<{
  "update:modelValue": [value: string];
}>();

function toDateString(value: string): string {
  // Strip time portion from ISO datetime strings like "2026-03-11T00:00:00.000000Z"
  return value.split("T")[0];
}

const dateValue = computed(() => {
  if (!props.modelValue || typeof props.modelValue !== "string") {
    return undefined;
  }
  try {
    return parseDate(toDateString(props.modelValue));
  } catch {
    return undefined;
  }
});

function formatDisplayDate(value: string): string {
  try {
    return new Intl.DateTimeFormat(undefined, {
      year: "numeric",
      month: "long",
      day: "numeric",
    }).format(new Date(toDateString(value) + "T00:00:00"));
  } catch {
    return value;
  }
}

function onSelect(val: unknown) {
  emit("update:modelValue", val ? String(val) : "");
}
</script>

<template>
  <Popover>
    <PopoverTrigger as-child>
      <UiButton
        variant="outline"
        :disabled="field.readonly"
        :class="
          cn(
            'w-full justify-start text-left font-normal shadow-none',
            !modelValue && 'text-muted-foreground',
            error && 'border-destructive',
          )
        "
      >
        <CalendarIcon class="mr-2 size-4" />
        {{
          modelValue ? formatDisplayDate(modelValue as string) : "Pick a date"
        }}
      </UiButton>
    </PopoverTrigger>
    <PopoverContent class="w-auto p-0">
      <Calendar
        :model-value="dateValue"
        initial-focus
        @update:model-value="onSelect"
      />
    </PopoverContent>
  </Popover>
</template>
