"use client";

import { motion } from "framer-motion";
import { MONTH_SCHEDULE, type ScheduledItemWithDate } from "@/lib/mock-data";
import { MonthDayCell } from "./MonthDayCell";

// Aujourd'hui (mock) = mardi 22 avril 2026
const TODAY = new Date(2026, 3, 22); // month 0-indexed

const DAY_HEADERS = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"];

function toDateKey(d: Date): string {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}

function isSameDay(a: Date, b: Date): boolean {
  return a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate();
}

function buildCalendarDays(year: number, month: number): Date[] {
  // month 0-indexed
  const firstDay = new Date(year, month, 1);
  // ISO weekday: 0=dimanche, 1=lundi … adapt to lundi=0
  const firstDow = (firstDay.getDay() + 6) % 7; // 0=lun … 6=dim
  const lastDay = new Date(year, month + 1, 0);
  const lastDate = lastDay.getDate();

  const days: Date[] = [];

  // Jours de la semaine précédente
  for (let i = firstDow - 1; i >= 0; i--) {
    days.push(new Date(year, month, -i));
  }

  // Jours du mois courant
  for (let d = 1; d <= lastDate; d++) {
    days.push(new Date(year, month, d));
  }

  // Compléter jusqu'à multiple de 7
  while (days.length % 7 !== 0) {
    days.push(new Date(year, month + 1, days.length - lastDate - firstDow + 1));
  }

  return days;
}

// Indexer les items par date
function buildItemIndex(items: ScheduledItemWithDate[]): Record<string, ScheduledItemWithDate[]> {
  const idx: Record<string, ScheduledItemWithDate[]> = {};
  for (const item of items) {
    if (!idx[item.date]) idx[item.date] = [];
    idx[item.date].push(item);
  }
  return idx;
}

type Props = {
  year: number;
  month: number; // 0-indexed
};

export function MonthView({ year, month }: Props) {
  const days = buildCalendarDays(year, month);
  const itemIndex = buildItemIndex(MONTH_SCHEDULE);

  return (
    <div className="bg-bg-card border border-border rounded-xl overflow-hidden">
      {/* Header jours */}
      <div className="grid grid-cols-7 border-b border-border">
        {DAY_HEADERS.map((h) => (
          <div key={h} className="py-2.5 text-center text-[11px] font-medium text-text-dim uppercase tracking-wider">
            {h}
          </div>
        ))}
      </div>

      {/* Grille cellules */}
      <div className="grid grid-cols-7 gap-px bg-border">
        {days.map((date, i) => {
          const key = toDateKey(date);
          const items = itemIndex[key] ?? [];
          const isCurrentMonth = date.getMonth() === month;
          const isToday = isSameDay(date, TODAY);

          return (
            <div key={key + i} className="bg-bg p-1.5">
              <MonthDayCell
                date={date}
                isToday={isToday}
                isCurrentMonth={isCurrentMonth}
                items={items}
                animIndex={i}
              />
            </div>
          );
        })}
      </div>

      {/* Mobile : liste verticale par semaine */}
      <div className="md:hidden mt-2 px-3 pb-3 flex flex-col gap-4">
        {Array.from({ length: days.length / 7 }, (_, wi) => {
          const week = days.slice(wi * 7, wi * 7 + 7);
          const hasItems = week.some((d) => (itemIndex[toDateKey(d)] ?? []).length > 0);
          if (!hasItems) return null;
          return (
            <motion.div
              key={wi}
              initial={{ opacity: 0, y: 6 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: wi * 0.07 }}
              className="border border-border rounded-lg overflow-hidden"
            >
              <div className="px-3 py-2 bg-bg-card text-[11px] font-medium text-text-dim border-b border-border">
                Semaine du {week[0].getDate()} au {week[6].getDate()}
              </div>
              <div className="p-2 flex flex-col gap-1">
                {week.flatMap((d) =>
                  (itemIndex[toDateKey(d)] ?? []).map((item) => (
                    <div key={item.id} className="text-[11px] text-text px-2 py-1 border border-border rounded flex gap-2 items-center">
                      <span className="text-text-dim font-mono">{d.getDate()}</span>
                      <span className="flex-1 truncate">{item.title}</span>
                    </div>
                  ))
                )}
              </div>
            </motion.div>
          );
        })}
      </div>
    </div>
  );
}
