import { useEffect, useMemo, useRef, useState } from 'react';
import { CalendarDays, ChevronLeft, ChevronRight, X } from 'lucide-react';
import {
  getJalaliWeekday,
  isoToJalali,
  isoToJalaliParts,
  jalaliMonthLength,
  jalaliToIso,
  todayJalaliParts,
} from '../utils/date';

const monthNames = [
  'فروردین',
  'اردیبهشت',
  'خرداد',
  'تیر',
  'مرداد',
  'شهریور',
  'مهر',
  'آبان',
  'آذر',
  'دی',
  'بهمن',
  'اسفند',
];
const weekDays = ['ش', 'ی', 'د', 'س', 'چ', 'پ', 'ج'];

export default function PersianDateInput({ value, onChange, className = '', placeholder = 'انتخاب تاریخ', ...props }) {
  const today = todayJalaliParts();
  const selected = isoToJalaliParts(value);
  const [open, setOpen] = useState(false);
  const [view, setView] = useState(selected || today);
  const wrapRef = useRef(null);

  useEffect(() => {
    if (selected) setView(selected);
  }, [value]);

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (wrapRef.current && !wrapRef.current.contains(event.target)) setOpen(false);
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const days = useMemo(() => {
    const firstWeekday = getJalaliWeekday(view.jy, view.jm, 1);
    const length = jalaliMonthLength(view.jy, view.jm);
    return [
      ...Array.from({ length: firstWeekday }, () => null),
      ...Array.from({ length }, (_, index) => index + 1),
    ];
  }, [view]);

  const moveMonth = (offset) => {
    setView((current) => {
      let jm = current.jm + offset;
      let jy = current.jy;
      if (jm < 1) { jm = 12; jy -= 1; }
      if (jm > 12) { jm = 1; jy += 1; }
      return { jy, jm, jd: 1 };
    });
  };

  const pickDay = (day) => {
    const iso = jalaliToIso(view.jy, view.jm, day);
    onChange(iso);
    setOpen(false);
  };

  const clearDate = (event) => {
    event.stopPropagation();
    onChange('');
    setOpen(false);
  };

  const displayValue = isoToJalali(value);

  return (
    <div className="persian-date-picker" ref={wrapRef}>
      <button type="button" className={`form-input persian-date-input${className ? ` ${className}` : ''}`} onClick={() => setOpen(!open)} {...props}>
        <CalendarDays size={16} />
        <span>{displayValue || placeholder}</span>
        {value && <X size={14} className="persian-date-clear" onClick={clearDate} />}
      </button>
      {open && (
        <div className="persian-date-popover">
          <div className="persian-date-head">
            <button type="button" onClick={() => moveMonth(-1)}><ChevronRight size={16} /></button>
            <strong>{monthNames[view.jm - 1]} {view.jy}</strong>
            <button type="button" onClick={() => moveMonth(1)}><ChevronLeft size={16} /></button>
          </div>
          <div className="persian-date-weekdays">
            {weekDays.map((day) => <span key={day}>{day}</span>)}
          </div>
          <div className="persian-date-grid">
            {days.map((day, index) => {
              const isSelected = selected && day === selected.jd && view.jm === selected.jm && view.jy === selected.jy;
              const isToday = today && day === today.jd && view.jm === today.jm && view.jy === today.jy;
              return day ? (
                <button key={`${view.jy}-${view.jm}-${day}`} type="button" className={`${isSelected ? 'selected' : ''}${isToday ? ' today' : ''}`} onClick={() => pickDay(day)}>
                  {day}
                </button>
              ) : <span key={`empty-${index}`} />;
            })}
          </div>
          <div className="persian-date-footer">
            <button type="button" className="btn btn-sm btn-secondary" onClick={() => setView(today)}>امروز</button>
            <button type="button" className="btn btn-sm btn-outline" onClick={() => setOpen(false)}>بستن</button>
          </div>
        </div>
      )}
    </div>
  );
}
