import type { CalendarEvent } from './shared';
import { CalendarDays, MapPin, Repeat } from 'lucide-react';
import { useCalendarEvents, useSelectedCollection } from './useDavData';

// Right panel of /calendar. Deliberately a grouped agenda list, not a month grid: the sidecar returns
// events as they are stored, with RRULE unexpanded, so a grid would have to invent occurrences the server
// never claimed existed. A list can show a repeating event honestly, as one entry with a "repeats" badge.

const dayKey = (ev: CalendarEvent) => (ev.start ? ev.start.slice(0, 10) : '');

const formatDay = (iso: string) => {
  if (!iso) return 'No date';
  const date = new Date(`${iso}T12:00:00`);
  if (Number.isNaN(date.getTime())) return iso;
  return date.toLocaleDateString(undefined, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
};

const formatTime = (ev: CalendarEvent) => {
  if (ev.allDay || !ev.start) return 'All day';
  const start = new Date(ev.start);
  if (Number.isNaN(start.getTime())) return '';
  const opts: Intl.DateTimeFormatOptions = { hour: '2-digit', minute: '2-digit' };
  const end = ev.end ? new Date(ev.end) : null;
  if (!end || Number.isNaN(end.getTime())) return start.toLocaleTimeString(undefined, opts);
  return `${start.toLocaleTimeString(undefined, opts)} – ${end.toLocaleTimeString(undefined, opts)}`;
};

export const CalendarView = () => {
  const { selected, isLoading: loadingCollections } = useSelectedCollection('calendar');
  const { events, isLoading, error } = useCalendarEvents(selected?.path ?? null);

  if (loadingCollections) return <Placeholder text="Loading calendars…" />;
  if (!selected) return <Placeholder text="No calendars yet. Create one from a CalDAV client." />;
  if (error) return <Placeholder text={`Could not read ${selected.displayName}: ${String(error)}`} />;
  if (isLoading) return <Placeholder text="Loading events…" />;
  if (events.length === 0) return <Placeholder text={`${selected.displayName} has no events.`} />;

  const sorted = [...events].sort((a, b) => (a.start ?? '').localeCompare(b.start ?? ''));
  const days: Array<{ key: string; events: CalendarEvent[] }> = [];
  for (const ev of sorted) {
    const key = dayKey(ev);
    const last = days[days.length - 1];
    if (last && last.key === key) last.events.push(ev);
    else days.push({ key, events: [ev] });
  }

  return (
    <div className="h-full overflow-y-auto">
      <div className="mx-auto flex max-w-3xl flex-col gap-6 p-6">
        {days.map((day) => (
          <section key={day.key} className="flex flex-col gap-2">
            <h2 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
              {formatDay(day.key)}
            </h2>
            {day.events.map((ev) => (
              <article key={ev.uid} className="flex gap-3 rounded-xl border bg-card p-3">
                <span
                  className="mt-1 h-2.5 w-2.5 shrink-0 rounded-full ring-1 ring-black/10"
                  style={{ backgroundColor: selected.color || '#94a3b8' }}
                />
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2">
                    <span className="truncate text-sm font-medium">{ev.summary || '(no title)'}</span>
                    {ev.rrule && (
                      <span
                        title={ev.rrule}
                        className="flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-[10px] text-muted-foreground"
                      >
                        <Repeat className="h-3 w-3" />
                        repeats
                      </span>
                    )}
                  </div>
                  <div className="mt-0.5 text-xs tabular-nums text-muted-foreground">{formatTime(ev)}</div>
                  {ev.location && (
                    <div className="mt-1 flex items-center gap-1 text-xs text-muted-foreground">
                      <MapPin className="h-3 w-3 shrink-0" />
                      <span className="truncate">{ev.location}</span>
                    </div>
                  )}
                  {ev.description && (
                    <p className="mt-1 whitespace-pre-wrap text-xs text-muted-foreground">{ev.description}</p>
                  )}
                </div>
              </article>
            ))}
          </section>
        ))}
      </div>
    </div>
  );
};

const Placeholder = ({ text }: { text: string }) => (
  <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center text-sm text-muted-foreground">
    <CalendarDays className="h-6 w-6 opacity-40" />
    <span>{text}</span>
  </div>
);
