import { useState } from 'react';
import { CalendarDaysIcon, XMarkIcon } from '@heroicons/react/24/outline';
import { formatDate } from '../../lib/utils';
import PersianCalendar from './PersianCalendar';

interface Props {
  value: string;                 // YYYY-MM-DD میلادی
  onChange: (v: string) => void;
  placeholder?: string;
  height?: number;
  minWidth?: number;
  /** انتخاب سال→ماه→روز را فعال می‌کند (پیش‌فرض خاموش). */
  enableYearPicker?: boolean;
}

export default function PersianDatePicker({ value, onChange, placeholder = 'انتخاب تاریخ', height = 38, minWidth = 148, enableYearPicker = false }: Props) {
  const [open, setOpen] = useState(false);

  return (
    <div style={{ position: 'relative', display: 'inline-block' }}>
      <div
        onClick={() => setOpen((o) => !o)}
        style={{
          display: 'flex', alignItems: 'center', gap: 7,
          height, padding: '0 10px', borderRadius: 'var(--r-sm)',
          border: '1px solid var(--border)', background: 'var(--surface)',
          cursor: 'pointer', fontSize: 13, color: value ? 'var(--text)' : 'var(--text-3)',
          userSelect: 'none', minWidth, whiteSpace: 'nowrap',
        }}
      >
        <CalendarDaysIcon style={{ width: 15, height: 15, color: 'var(--text-3)', flexShrink: 0 }} />
        <span style={{ flex: 1 }}>{value ? formatDate(value) : placeholder}</span>
        {value && (
          <span
            onClick={(e) => { e.stopPropagation(); onChange(''); }}
            style={{ display: 'flex', alignItems: 'center', cursor: 'pointer', color: 'var(--text-3)' }}
          >
            <XMarkIcon style={{ width: 13, height: 13 }} />
          </span>
        )}
      </div>

      {open && (
        <PersianCalendar
          value={value}
          onChange={(v) => { onChange(v); setOpen(false); }}
          onClose={() => setOpen(false)}
          enableYearPicker={enableYearPicker}
        />
      )}
    </div>
  );
}
