<script setup lang="ts">
import { computed } from "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];
}>();

// Normalize incoming value to YYYY-MM-DDTHH:mm for datetime-local input
const inputValue = computed<string>(() => {
  if (!props.modelValue) return "";
  const raw = String(props.modelValue);
  // Already in YYYY-MM-DDTHH:mm format
  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(raw)) {
    return raw.substring(0, 16);
  }
  // ISO with offset/Z — strip to local datetime portion
  const date = new Date(raw);
  if (isNaN(date.getTime())) return "";
  const pad = (n: number) => String(n).padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
});

function handleChange(event: Event): void {
  const value = (event.target as HTMLInputElement).value;
  emit("update:modelValue", value);
}
</script>

<template>
  <input
    :id="field.name"
    type="datetime-local"
    :value="inputValue"
    :disabled="field.readonly"
    :class="
      cn(
        'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50',
        error && 'border-destructive focus-visible:ring-destructive',
      )
    "
    @change="handleChange"
  />
</template>
