"use client";

import { useMemo, useState } from "react";
import {
  mergeScheduleForDays,
  type PublicTruckEvent,
  type PublicTruckRecurrence,
} from "@/lib/truck-schedule-shared";
import {
  formatWeekRangeLabel,
  getWeekDays,
  type WeekDay,
} from "@/lib/week-calendar";
import { WaffleMenuImage } from "./WaffleMenuImage";

type Props = {
  events: PublicTruckEvent[];
  recurrences: PublicTruckRecurrence[];
};

/** Plus d’événements → colonne plus large ; jour vide → colonne compacte. */
function dayColumnFlex(eventCount: number): number {
  if (eventCount === 0) return 0.42;
  if (eventCount === 1) return 1;
  return 1 + (eventCount - 1) * 0.38;
}

export function WeekScheduleCalendar({ events, recurrences }: Props) {
  const [weekOffset, setWeekOffset] = useState(0);

  const days = useMemo(
    () => getWeekDays(new Date(), weekOffset),
    [weekOffset]
  );

  const byDate = useMemo(() => {
    const merged = mergeScheduleForDays(events, recurrences, days);
    const map = new Map<string, PublicTruckEvent[]>();
    for (const ev of merged) {
      const list = map.get(ev.eventDate) ?? [];
      list.push(ev);
      map.set(ev.eventDate, list);
    }
    return map;
  }, [events, recurrences, days]);

  const rangeLabel = formatWeekRangeLabel(days);

  return (
    <div className="mt-8">
      <div className="mb-6 flex flex-col items-center justify-between gap-4 sm:flex-row">
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => setWeekOffset((w) => w - 1)}
            className="rounded-full border border-chocolat/15 bg-white px-3 py-2 text-sm font-medium text-chocolat hover:bg-cream"
            aria-label="Semaine précédente"
          >
            ←
          </button>
          <button
            type="button"
            onClick={() => setWeekOffset(0)}
            className="rounded-full border border-chocolat/15 bg-white px-4 py-2 text-sm font-medium text-chocolat hover:bg-cream"
          >
            Cette semaine
          </button>
          <button
            type="button"
            onClick={() => setWeekOffset((w) => w + 1)}
            className="rounded-full border border-chocolat/15 bg-white px-3 py-2 text-sm font-medium text-chocolat hover:bg-cream"
            aria-label="Semaine suivante"
          >
            →
          </button>
        </div>
        <p className="text-sm font-medium capitalize text-chocolat">{rangeLabel}</p>
      </div>

      <div className="grid auto-rows-auto gap-3 sm:grid-cols-2 lg:flex lg:items-stretch lg:gap-2.5 xl:gap-3">
        {days.map((day) => {
          const dayEvents = byDate.get(day.date) ?? [];
          return (
            <DayColumn
              key={day.date}
              day={day}
              events={dayEvents}
              flexGrow={dayColumnFlex(dayEvents.length)}
            />
          );
        })}
      </div>
    </div>
  );
}

function DayColumn({
  day,
  events,
  flexGrow,
}: {
  day: WeekDay;
  events: PublicTruckEvent[];
  flexGrow: number;
}) {
  const hasEvents = events.length > 0;

  return (
    <article
      style={{ flex: `${flexGrow} 1 0%` }}
      className={`flex min-w-0 flex-col overflow-hidden rounded-2xl border transition-all duration-300 ${
        day.isToday
          ? "border-gaufre/40 bg-white shadow-[0_8px_28px_-10px_rgba(243,156,18,0.22)] ring-1 ring-gaufre/20 hover:shadow-[0_12px_36px_-10px_rgba(243,156,18,0.28)]"
          : "border-chocolat/12 bg-white shadow-[0_4px_20px_-8px_rgba(61,43,31,0.12)] hover:shadow-[0_8px_28px_-8px_rgba(61,43,31,0.16)]"
      } ${
        hasEvents
          ? "min-h-[200px] lg:min-h-[220px]"
          : "self-start lg:min-h-[220px] lg:self-stretch"
      }`}
    >
      <header
        className={`shrink-0 border-b px-3 py-2.5 text-center ${
          day.isToday
            ? "border-gaufre/20 bg-gaufre/5"
            : "border-chocolat/8 bg-cream/30"
        }`}
      >
        <div className="flex items-center justify-center gap-1.5">
          <p className="text-[10px] font-semibold uppercase tracking-wider text-muted">
            {day.label}
          </p>
          {hasEvents ? (
            <span
              className="rounded-full bg-gaufre/20 px-1.5 py-0.5 text-[10px] font-bold leading-none text-chocolat"
              aria-label={`${events.length} événement${events.length > 1 ? "s" : ""}`}
            >
              {events.length}
            </span>
          ) : null}
        </div>
        <p
          className={`mt-0.5 text-xl font-bold leading-none ${
            day.isToday ? "text-gaufre" : "text-chocolat"
          }`}
        >
          {day.dayNum}
        </p>
      </header>

      <ul
        className={`flex min-h-0 flex-col ${
          hasEvents
            ? "flex-1 gap-3 p-2.5"
            : "px-2.5 py-2 lg:flex-1 lg:items-center lg:justify-center lg:p-2.5"
        }`}
      >
        {hasEvents ? (
          events.map((ev) => <EventCard key={ev.id} event={ev} />)
        ) : (
          <li className="text-center text-xs text-muted" aria-hidden>
            —
          </li>
        )}
      </ul>
    </article>
  );
}

function EventCard({ event: ev }: { event: PublicTruckEvent }) {
  const isRecurring = ev.id.startsWith("recur-");

  return (
    <li className="w-full min-w-0 overflow-hidden rounded-xl border border-chocolat/10 bg-white shadow-sm ring-1 ring-chocolat/5">
      {ev.imageUrl ? (
        <div className="relative aspect-[5/2] w-full bg-chocolat/5 lg:aspect-[16/10]">
          <WaffleMenuImage src={ev.imageUrl} alt={ev.location} />
        </div>
      ) : null}
      <div className="w-full px-3 py-2.5 text-left text-xs">
        {isRecurring ? (
          <p className="mb-1 text-[10px] font-semibold uppercase tracking-wide text-gaufre">
            Récurrent
          </p>
        ) : null}
        {ev.timeLabel ? (
          <p className="font-semibold text-gaufre">{ev.timeLabel}</p>
        ) : null}
        <p className="mt-0.5 font-medium leading-snug text-chocolat">
          {ev.location}
        </p>
        {ev.note ? (
          <p className="mt-1 leading-snug text-muted">{ev.note}</p>
        ) : null}
      </div>
    </li>
  );
}
