import * as React from 'react'
import { Input } from './input'
import { FieldLabel, FieldHint, FieldError } from './field'
import { cn } from '@/lib/utils'

/**
 * DatePicker — MVP native HTML date input wrapper. Замена @nstart/ui DatePicker
 * (тот же label/value/onChange API).
 *
 * <p>Сейчас простой &lt;input type="date"&gt; — браузерный picker (CSS hard
 * styling limited, но functional). Phase 4 Stage 3.8b: заменить на
 * react-day-picker если потребуется branded look или date range.
 *
 * <p>Format: ISO yyyy-mm-dd. onChange получает Date|null.
 */

export type DatePickerProps = {
  label?: React.ReactNode
  hint?: React.ReactNode
  error?: React.ReactNode
  required?: boolean
  value?: Date | string | null
  /** Receives Date or null on clear. */
  onChange?: (date: Date | null) => void
  /** Min / max bounds (ISO string yyyy-mm-dd or Date). */
  min?: Date | string
  max?: Date | string
  id?: string
  disabled?: boolean
  /** Wrapper className. */
  rootClassName?: string
  inputClassName?: string
}

const toIso = (v: Date | string | null | undefined): string => {
  if (!v) return ''
  if (typeof v === 'string') return v.slice(0, 10)
  if (v instanceof Date && !isNaN(v.getTime())) return v.toISOString().slice(0, 10)
  return ''
}

export function DatePicker({
  label,
  hint,
  error,
  required,
  value,
  onChange,
  min,
  max,
  id,
  disabled,
  rootClassName,
  inputClassName,
}: DatePickerProps) {
  const autoId = React.useId()
  const inputId = id ?? autoId
  const hintId = hint ? `${inputId}-hint` : undefined
  const errorId = error ? `${inputId}-error` : undefined

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const raw = e.target.value
    if (!raw) {
      onChange?.(null)
      return
    }
    const d = new Date(raw + 'T00:00:00')
    onChange?.(isNaN(d.getTime()) ? null : d)
  }

  return (
    <div className={cn('flex flex-col gap-1', rootClassName)}>
      {label && (
        <FieldLabel htmlFor={inputId} required={required}>
          {label}
        </FieldLabel>
      )}
      <Input
        id={inputId}
        type="date"
        value={toIso(value)}
        onChange={handleChange}
        min={toIso(min)}
        max={toIso(max)}
        disabled={disabled}
        required={required}
        aria-invalid={error ? true : undefined}
        aria-describedby={[hintId, errorId].filter(Boolean).join(' ') || undefined}
        className={cn(error ? 'border-pink focus-visible:ring-pink/40' : '', inputClassName)}
      />
      {hint && !error && <FieldHint id={hintId}>{hint}</FieldHint>}
      {error && <FieldError id={errorId}>{error}</FieldError>}
    </div>
  )
}
