/**
 * DateField Component
 *
 * 날짜 선택 필드 (date, date-range)
 */

'use client';

import { useState } from 'react';
import { format } from 'date-fns';
import { ko } from 'date-fns/locale';
import { CalendarIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import { Label } from '@/components/ui/label';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import type { DynamicFieldProps } from '../types';
import { cn } from '@/lib/utils';

export function DateField({
  field,
  value,
  error,
  onChange,
  onBlur,
  disabled,
}: DynamicFieldProps) {
  const [open, setOpen] = useState(false);

  // 값을 Date 객체로 변환
  const dateValue = value ? new Date(value as string) : undefined;
  const isValidDate = dateValue && !isNaN(dateValue.getTime());

  const handleSelect = (date: Date | undefined) => {
    if (date) {
      // ISO 문자열로 변환 (YYYY-MM-DD)
      onChange(format(date, 'yyyy-MM-dd'));
    } else {
      onChange(null);
    }
    setOpen(false);
    onBlur();
  };

  return (
    <div className="space-y-2">
      <Label
        htmlFor={field.field_key}
        className={cn(
          'text-sm font-medium',
          field.is_required && "after:content-['*'] after:ml-0.5 after:text-red-500"
        )}
      >
        {field.field_name}
      </Label>

      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            id={field.field_key}
            variant="outline"
            disabled={disabled || field.is_readonly}
            className={cn(
              'w-full justify-start text-left font-normal',
              !isValidDate && 'text-muted-foreground',
              error && 'border-red-500 focus:ring-red-500',
              field.is_readonly && 'bg-gray-50 text-gray-500'
            )}
          >
            <CalendarIcon className="mr-2 h-4 w-4" />
            {isValidDate
              ? format(dateValue, 'yyyy년 MM월 dd일', { locale: ko })
              : field.placeholder || '날짜를 선택하세요'}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0" align="start">
          <Calendar
            mode="single"
            selected={isValidDate ? dateValue : undefined}
            onSelect={handleSelect}
            locale={ko}
            initialFocus
          />
        </PopoverContent>
      </Popover>

      {field.help_text && !error && (
        <p className="text-xs text-muted-foreground">{field.help_text}</p>
      )}

      {error && <p className="text-xs text-red-500">{error}</p>}
    </div>
  );
}

export default DateField;