'use client';

import { Calendar } from 'lucide-react';
import { useRef } from 'react';
import {
  formatDateForDateTimeInput,
  parseDateTimeInput,
} from '@/lib/date-utils';

interface DateTimeInputProps {
  value?: Date;
  onChange: (date: Date | undefined) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  onFocus?: () => void;
}

export function DateTimeInput({
  value,
  onChange,
  placeholder,
  disabled = false,
  className = '',
  onFocus,
}: DateTimeInputProps) {
  const inputRef = useRef<HTMLInputElement>(null);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = e.target.value
      ? parseDateTimeInput(e.target.value)
      : undefined;
    onChange(newValue);
  };

  const handleCalendarClick = () => {
    if (!disabled && inputRef.current) {
      // Déclencher le calendrier natif du navigateur
      inputRef.current.showPicker?.();
    }
  };

  return (
    <div className={`relative flex items-center ${className}`}>
      <Calendar
        size={16}
        className="absolute left-3 text-[var(--muted-foreground)] cursor-pointer z-10 hover:text-[var(--primary)] transition-colors"
        onClick={handleCalendarClick}
      />
      <input
        ref={inputRef}
        type="datetime-local"
        value={value ? formatDateForDateTimeInput(value) : ''}
        onChange={handleChange}
        onFocus={onFocus}
        disabled={disabled}
        placeholder={placeholder}
        className="w-full pl-10 pr-3 py-2 border border-[var(--border)] rounded-md bg-[var(--input)] text-[var(--foreground)] placeholder-[var(--muted-foreground)] focus:outline-none focus:ring-2 focus:ring-[var(--primary)] focus:border-[var(--primary)] disabled:opacity-50 disabled:cursor-not-allowed font-mono text-sm [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-datetime-edit-ampm-field]:hidden [&::-webkit-inner-spin-button]:hidden [&::-webkit-outer-spin-button]:hidden"
        style={{
          colorScheme: 'light',
          WebkitAppearance: 'none',
          MozAppearance: 'textfield',
        }}
      />
    </div>
  );
}
