import { useEffect, useMemo } from 'react';
import useShiftPlanningStore from '../store/shiftPlanningStore';
import { MonthNav } from './MonthNav';
import { MonthCalendar } from './MonthCalendar';
import type { AvailableShiftSlot, MyShiftSlot } from '../api/types';

export function ShiftPlanning() {
  const period = useShiftPlanningStore((s) => s.period);
  const available = useShiftPlanningStore((s) => s.available);
  const mine = useShiftPlanningStore((s) => s.mine);
  const busy = useShiftPlanningStore((s) => s.busy);
  const error = useShiftPlanningStore((s) => s.error);
  const load = useShiftPlanningStore((s) => s.load);
  const prevPeriod = useShiftPlanningStore((s) => s.prevPeriod);
  const nextPeriod = useShiftPlanningStore((s) => s.nextPeriod);
  const signup = useShiftPlanningStore((s) => s.signup);
  const cancel = useShiftPlanningStore((s) => s.cancel);

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

  const byDate = useMemo(() => {
    const map = new Map<string, { mine: MyShiftSlot[]; available: AvailableShiftSlot[] }>();
    const entryFor = (date: string) => {
      let entry = map.get(date);
      if (!entry) {
        entry = { mine: [], available: [] };
        map.set(date, entry);
      }
      return entry;
    };
    mine?.forEach((slot) => entryFor(slot.date).mine.push(slot));
    available?.forEach((slot) => entryFor(slot.date).available.push(slot));
    return map;
  }, [mine, available]);

  function renderDay(dateStr: string) {
    const entry = byDate.get(dateStr);
    if (!entry) return null;
    return (
      <>
        {entry.mine.map((slot) => (
          <button
            key={`mine-${slot.slot_id}`}
            className="calendar-slot is-mine"
            disabled={busy}
            title="Zrušit přihlášení"
            onClick={() => cancel(slot.slot_id)}
          >
            {slot.start_time}–{slot.end_time}
          </button>
        ))}
        {entry.available.map((slot) => (
          <button
            key={`avail-${slot.slot_id}`}
            className="calendar-slot"
            disabled={busy}
            title="Přihlásit se"
            onClick={() => signup(slot.slot_id)}
          >
            {slot.start_time}–{slot.end_time} ({slot.free_places}/{slot.capacity})
          </button>
        ))}
      </>
    );
  }

  return (
    <div className="panel">
      <p className="panel-title">Plánování směn</p>
      <MonthNav month={period} onPrev={prevPeriod} onNext={nextPeriod} />
      {error && <div className="login-error">{error}</div>}

      {available === null || mine === null ? (
        <div className="empty-line">&gt; načítám…</div>
      ) : (
        <MonthCalendar month={period} renderDay={renderDay} />
      )}

      <p className="row-meta" style={{ marginTop: '0.5rem' }}>
        Tučně = moje směna, klikni pro zrušení &middot; ostatní = volná směna, klikni pro přihlášení
      </p>
    </div>
  );
}
