import { useCallback, useEffect, useMemo, useState } from 'react';
import { CalendarDays, ChevronLeft, ChevronRight, Circle, RefreshCw } from 'lucide-react';
import api from '../services/api';
import {
  getJalaliWeekday,
  jalaliMonthLength,
  jalaliToIso,
  todayJalaliParts,
} from '../utils/date';

const monthNames = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'];
const weekdays = ['ش', 'ی', 'د', 'س', 'چ', 'پ', 'ج'];
const typeLabels = { meeting: 'جلسه', task: 'تسک', sprint: 'اسپرینت', project: 'پروژه', action_item: 'اقدام' };

function moveMonth(view, delta) {
  let jm = view.jm + delta;
  let jy = view.jy;
  if (jm > 12) { jm = 1; jy += 1; }
  if (jm < 1) { jm = 12; jy -= 1; }
  return { jy, jm };
}

export default function CalendarPopover({ onSelectEvent }) {
  const today = useMemo(() => todayJalaliParts(), []);
  const [view, setView] = useState({ jy: today.jy, jm: today.jm });
  const [selectedIso, setSelectedIso] = useState(jalaliToIso(today.jy, today.jm, today.jd));
  const [events, setEvents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [activeTypes, setActiveTypes] = useState(Object.keys(typeLabels));
  const [agendaPage, setAgendaPage] = useState(0);

  const monthLength = jalaliMonthLength(view.jy, view.jm);
  const firstWeekday = getJalaliWeekday(view.jy, view.jm, 1);
  const from = jalaliToIso(view.jy, view.jm, 1);
  const to = jalaliToIso(view.jy, view.jm, monthLength);

  const loadEvents = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const { data } = await api.get('/calendar/events', { params: { from, to } });
      setEvents(data.data || []);
    } catch {
      setError('دریافت رویدادها ناموفق بود.');
    } finally {
      setLoading(false);
    }
  }, [from, to]);

  useEffect(() => { loadEvents(); }, [loadEvents]);

  const eventsByDate = useMemo(() => events.reduce((result, event) => {
    const date = String(event.start_at || '').slice(0, 10);
    if (!result[date]) result[date] = [];
    result[date].push(event);
    return result;
  }, {}), [events]);

  const selectedEvents = (eventsByDate[selectedIso] || []).filter((event) => activeTypes.includes(event.event_type));
  const agendaPageSize = 2;
  const agendaPageCount = Math.max(1, Math.ceil(selectedEvents.length / agendaPageSize));
  const visibleEvents = selectedEvents.slice(agendaPage * agendaPageSize, agendaPage * agendaPageSize + agendaPageSize);
  const cells = [
    ...Array.from({ length: firstWeekday }, () => null),
    ...Array.from({ length: monthLength }, (_, index) => index + 1),
  ];

  const goToday = () => {
    setView({ jy: today.jy, jm: today.jm });
    setSelectedIso(jalaliToIso(today.jy, today.jm, today.jd));
  };

  const toggleType = (type) => {
    setActiveTypes((current) => current.includes(type) ? current.filter((item) => item !== type) : [...current, type]);
  };

  useEffect(() => { setAgendaPage(0); }, [selectedIso, activeTypes]);

  return (
    <section className="calendar-popover" aria-label="تقویم رویدادها">
      <header className="calendar-popover-head">
        <div>
          <strong>{monthNames[view.jm - 1]} {view.jy}</strong>
          <span>{events.length} رویداد</span>
        </div>
        <div className="calendar-controls">
          <button type="button" onClick={() => setView(moveMonth(view, -1))} aria-label="ماه قبل"><ChevronRight size={18} /></button>
          <button type="button" className="calendar-today" onClick={goToday}>امروز</button>
          <button type="button" onClick={() => setView(moveMonth(view, 1))} aria-label="ماه بعد"><ChevronLeft size={18} /></button>
        </div>
      </header>

      <div className="calendar-weekdays">
        {weekdays.map((day) => <span key={day}>{day}</span>)}
      </div>
      <div className="calendar-grid">
        {cells.map((day, index) => {
          if (!day) return <span key={`blank-${index}`} className="calendar-day blank" />;
          const iso = jalaliToIso(view.jy, view.jm, day);
          const dayEvents = (eventsByDate[iso] || []).filter((event) => activeTypes.includes(event.event_type));
          const isToday = iso === jalaliToIso(today.jy, today.jm, today.jd);
          return (
            <button
              type="button"
              key={iso}
              className={`calendar-day ${selectedIso === iso ? 'selected' : ''} ${isToday ? 'today' : ''}`}
              onClick={() => setSelectedIso(iso)}
              aria-label={`${day} ${monthNames[view.jm - 1]}، ${dayEvents.length} رویداد`}
            >
              <span>{day}</span>
              {dayEvents.length > 0 && <i>{dayEvents.slice(0, 3).map((event) => <b key={event.id} className={`tone-${event.color_token}`} />)}</i>}
            </button>
          );
        })}
      </div>

      <div className="calendar-filters" aria-label="فیلتر نوع رویداد">
        {Object.entries(typeLabels).map(([type, label]) => (
          <button type="button" key={type} className={activeTypes.includes(type) ? 'active' : ''} onClick={() => toggleType(type)}>
            <Circle size={8} fill="currentColor" />{label}
          </button>
        ))}
      </div>

      <div className="calendar-agenda">
        <div className="calendar-agenda-title">
          <strong>برنامه روز</strong>
          <span>{selectedEvents.length} مورد</span>
        </div>
        {loading ? (
          <div className="calendar-state"><RefreshCw className="spin" size={18} /> در حال دریافت...</div>
        ) : error ? (
          <button type="button" className="calendar-state error" onClick={loadEvents}>{error} تلاش دوباره</button>
        ) : selectedEvents.length === 0 ? (
          <div className="calendar-state"><CalendarDays size={20} /> رویدادی برای این روز وجود ندارد.</div>
        ) : (
          <>
            {visibleEvents.map((event) => (
              <button type="button" className="calendar-event" key={event.id} onClick={() => onSelectEvent(event)}>
                <i className={`tone-${event.color_token}`} />
                <span>
                  <strong>{event.title}</strong>
                  <small>{typeLabels[event.event_type]}{event.project?.title ? ` · ${event.project.title}` : ''}</small>
                </span>
                <ChevronLeft size={16} />
              </button>
            ))}
            {agendaPageCount > 1 && (
              <div className="popover-pagination">
                <button type="button" disabled={agendaPage === 0} onClick={() => setAgendaPage((page) => Math.max(0, page - 1))}><ChevronRight size={16} /> قبلی</button>
                <span>{agendaPage + 1} از {agendaPageCount}</span>
                <button type="button" disabled={agendaPage >= agendaPageCount - 1} onClick={() => setAgendaPage((page) => Math.min(agendaPageCount - 1, page + 1))}>بعدی <ChevronLeft size={16} /></button>
              </div>
            )}
          </>
        )}
      </div>
    </section>
  );
}
