"use client";

import Link from "next/link";
import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Plus } from "lucide-react";
import { SCHEDULE, statusLabel, statusColor, scheduleItemToContentId, type ScheduledItem } from "@/lib/mock-data";

const DAYS = [
  { short: "Lun", date: "21" },
  { short: "Mar", date: "22" },
  { short: "Mer", date: "23" },
  { short: "Jeu", date: "24" },
  { short: "Ven", date: "25" },
  { short: "Sam", date: "26" },
  { short: "Dim", date: "27" },
];

const HOURS = [8, 10, 12, 14, 16, 18];

// Mardi = index 1 = "aujourd'hui" (mock)
const TODAY_INDEX = 1;

const FORMAT_COLORS: Record<ScheduledItem["format"], string> = {
  article: "bg-indigo-500/10 border-indigo-500/25 text-indigo-300",
  "fiche-produit": "bg-purple-500/10 border-purple-500/25 text-purple-300",
  faq: "bg-sky-500/10 border-sky-500/25 text-sky-300",
  pillar: "bg-amber-500/10 border-amber-500/25 text-amber-300",
  guide: "bg-emerald-500/10 border-emerald-500/25 text-emerald-300",
};

const FORMAT_LABELS: Record<ScheduledItem["format"], string> = {
  article: "Article",
  "fiche-produit": "Fiche",
  faq: "FAQ",
  pillar: "Pillar",
  guide: "Guide",
};

function ScheduleCard({ item, index }: { item: ScheduledItem; index: number }) {
  return (
    <Link href={`/contenus/${scheduleItemToContentId(item)}`} className="block">
      <motion.div
        initial={{ opacity: 0, y: 8 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: index * 0.06, duration: 0.3 }}
        whileHover={{ y: -2, boxShadow: "0 8px 24px rgba(0,0,0,0.4)" }}
        className={`p-2.5 rounded-lg border cursor-pointer ${FORMAT_COLORS[item.format]} transition-shadow`}
      >
        <div className="font-mono text-[10px] text-text-dimmer mb-1">{item.hour}h00</div>
        <div className="text-[11.5px] text-text font-medium leading-snug line-clamp-2 mb-2">
          {item.title}
        </div>
        <div className="flex items-center gap-1.5 flex-wrap">
          <span className={`inline-block px-1.5 py-0.5 rounded text-[10px] border font-medium ${FORMAT_COLORS[item.format]}`}>
            {FORMAT_LABELS[item.format]}
          </span>
          <span className={`inline-block px-1.5 py-0.5 rounded-full text-[10px] border ${statusColor(item.status)}`}>
            {statusLabel(item.status)}
          </span>
        </div>
      </motion.div>
    </Link>
  );
}

function DayColumn({ dayIndex, day, showItems }: { dayIndex: number; day: { short: string; date: string }; showItems: boolean }) {
  const [hoveredHour, setHoveredHour] = useState<number | null>(null);
  const isToday = dayIndex === TODAY_INDEX;
  const items = showItems ? SCHEDULE.filter((s) => s.day === dayIndex) : [];

  return (
    <div className="flex flex-col min-w-0">
      {/* Header — hauteur fixe h-20 pour aligner toutes les colonnes */}
      <div className={`h-20 flex flex-col justify-center items-center text-center border-b mb-3 ${isToday ? "border-accent/40" : "border-border"}`}>
        <div className={`text-[11px] uppercase tracking-wider font-medium ${isToday ? "text-accent-light" : "text-text-dim"}`}>
          {day.short}
        </div>
        <div className={`text-[18px] font-semibold mt-0.5 ${isToday ? "text-accent-light" : "text-text"}`}>
          {day.date}
        </div>
        {/* Réservation de place badge — toujours présent, invisible si non-aujourd'hui */}
        <span className={`inline-block mt-1 px-2 py-0.5 rounded-full text-[9px] font-medium border ${isToday ? "bg-accent/20 text-accent-light border-accent/30" : "invisible border-transparent"}`}>
          Aujourd&apos;hui
        </span>
      </div>

      {/* Items */}
      <div className="flex flex-col gap-2 flex-1">
        {items.map((item, i) => (
          <ScheduleCard key={item.id} item={item} index={i} />
        ))}

        {/* Slots vides */}
        {HOURS.filter((h) => !items.find((s) => s.hour === h)).slice(0, 2).map((h) => (
          <div
            key={h}
            className="relative"
            onMouseEnter={() => setHoveredHour(h)}
            onMouseLeave={() => setHoveredHour(null)}
          >
            <div
              className={`h-8 rounded-lg border border-dashed transition-colors ${
                hoveredHour === h ? "border-accent/40 bg-accent/5" : "border-border/40"
              }`}
            />
            {hoveredHour === h && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="absolute inset-0 flex items-center justify-center gap-1 text-[11px] text-accent-light"
              >
                <Plus className="w-3 h-3" />
                <span>{h}h</span>
              </motion.div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

type CalendarGridProps = {
  weekOffset?: number;
};

export function CalendarGrid({ weekOffset = 0 }: CalendarGridProps) {
  // weekOffset non-null → afficher les items seulement pour la semaine courante (mock statique)
  // Pour un vrai produit on filtrerait par date ici ; en proto on affiche toujours les mêmes données
  const showItems = weekOffset === 0;

  return (
    <>
      {/* Desktop grid */}
      <div className="hidden md:grid grid-cols-7 gap-3 h-[650px] overflow-y-auto p-4 bg-bg-card border border-border rounded-xl">
        {DAYS.map((day, i) => (
          <DayColumn key={i} dayIndex={i} day={day} showItems={showItems} />
        ))}
      </div>

      {/* Mobile accordéon */}
      <div className="md:hidden flex flex-col gap-2">
        {DAYS.map((day, i) => (
          <MobileDayAccordion key={i} dayIndex={i} day={day} showItems={showItems} />
        ))}
      </div>
    </>
  );
}

function MobileDayAccordion({ dayIndex, day, showItems }: { dayIndex: number; day: { short: string; date: string }; showItems: boolean }) {
  const [open, setOpen] = useState(dayIndex === TODAY_INDEX);
  const isToday = dayIndex === TODAY_INDEX;
  const items = showItems ? SCHEDULE.filter((s) => s.day === dayIndex) : [];

  return (
    <div className={`border rounded-xl overflow-hidden ${isToday ? "border-accent/30" : "border-border"}`}>
      <button
        onClick={() => setOpen(!open)}
        className={`w-full flex items-center justify-between px-4 py-3 text-left transition-colors ${open ? "bg-bg-card" : "bg-bg-card/50 hover:bg-bg-card"}`}
      >
        <div className="flex items-center gap-3">
          <span className={`text-[13px] font-medium ${isToday ? "text-accent-light" : "text-text"}`}>
            {day.short} {day.date} avril
          </span>
          {isToday && <span className="px-2 py-0.5 rounded-full text-[9px] bg-accent/20 text-accent-light border border-accent/30">Aujourd&apos;hui</span>}
        </div>
        <div className="flex items-center gap-2">
          <span className="text-[11px] text-text-dim">{items.length} item{items.length !== 1 ? "s" : ""}</span>
          <motion.div animate={{ rotate: open ? 90 : 0 }}>
            <Plus className="w-4 h-4 text-text-dimmer" />
          </motion.div>
        </div>
      </button>

      <AnimatePresence initial={false}>
        {open && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.25 }}
            className="overflow-hidden"
          >
            <div className="p-3 flex flex-col gap-2 border-t border-border">
              {items.length === 0 ? (
                <div className="py-6 text-center text-[12px] text-text-dimmer">Aucun contenu planifié</div>
              ) : (
                items.map((item, i) => <ScheduleCard key={item.id} item={item} index={i} />)
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

