"use client";

import { isToday, isSameMonth, format } from "date-fns";
import type { CalendarEvent, GoogleCachedEvent } from "@/lib/types";

interface DayCellProps {
  date: Date;
  currentMonth: Date;
  isSelected: boolean;
  events: CalendarEvent[];
  googleEvents: GoogleCachedEvent[];
  calendarColors: Record<string, string>;
  onSelect: (date: Date) => void;
}

export default function DayCell({
  date,
  currentMonth,
  isSelected,
  events,
  googleEvents,
  calendarColors,
  onSelect,
}: DayCellProps) {
  const inMonth = isSameMonth(date, currentMonth);
  const today = isToday(date);
  const allEvents = [
    ...events.map((e) => ({
      id: e.id,
      title: e.title,
      color: calendarColors[e.calendar_id] || "#6b7280",
      allDay: e.all_day === 1,
      time: e.all_day ? null : format(new Date(e.start_time), "h:mm a"),
    })),
    ...googleEvents.map((e) => ({
      id: e.id,
      title: e.title,
      color: "#ef4444",
      allDay: e.all_day === 1,
      time: e.all_day ? null : format(new Date(e.start_time), "h:mm a"),
    })),
  ];

  const maxVisible = 3;
  const visible = allEvents.slice(0, maxVisible);
  const overflow = allEvents.length - maxVisible;

  return (
    <button
      onClick={() => onSelect(date)}
      className={`
        min-h-[80px] p-1 text-left border border-zinc-200 dark:border-zinc-700 transition-colors
        ${!inMonth ? "opacity-40" : ""}
        ${isSelected ? "bg-blue-50 dark:bg-blue-950/30 border-blue-300 dark:border-blue-700" : "hover:bg-zinc-50 dark:hover:bg-zinc-800/50"}
      `}
    >
      <div className="flex items-center justify-between mb-0.5">
        <span
          className={`
            text-xs font-medium w-6 h-6 flex items-center justify-center rounded-full
            ${today ? "bg-blue-500 text-white" : ""}
          `}
        >
          {format(date, "d")}
        </span>
      </div>
      <div className="flex flex-col gap-0.5">
        {visible.map((evt) => (
          <div
            key={evt.id}
            className="text-[10px] leading-tight truncate px-1 py-0.5 rounded"
            style={{ backgroundColor: evt.color + "20", color: evt.color }}
          >
            {evt.time && <span className="font-medium">{evt.time} </span>}
            {evt.title}
          </div>
        ))}
        {overflow > 0 && (
          <div className="text-[10px] text-zinc-500 px-1">+{overflow} more</div>
        )}
      </div>
    </button>
  );
}
