import { useState } from "preact/hooks";
import { Badge } from "@/components/Badge";
import { resolveBadgeColor } from "@/theme/accents";
import type { RecordSpec, DataRow } from "@/types/spec";

interface CalendarViewProps {
  rows: DataRow[];
  rec: RecordSpec | undefined;
  dateField: string;
  titleField: string;
  badgeField?: string;
  onViewDetail: (table: string, id: string) => void;
  table: string;
}

const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

export function CalendarView({ rows, rec, dateField, titleField, badgeField, onViewDetail, table }: CalendarViewProps) {
  const [year, setYear] = useState(new Date().getFullYear());
  const [month, setMonth] = useState(new Date().getMonth());

  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const today = new Date();

  // Group rows by date
  const byDate: Record<string, DataRow[]> = {};
  for (const row of rows) {
    const d = String(row[dateField] || "");
    const dateKey = d.slice(0, 10); // YYYY-MM-DD
    if (!byDate[dateKey]) byDate[dateKey] = [];
    byDate[dateKey].push(row);
  }

  function prev() {
    if (month === 0) { setMonth(11); setYear(year - 1); }
    else setMonth(month - 1);
  }
  function next() {
    if (month === 11) { setMonth(0); setYear(year + 1); }
    else setMonth(month + 1);
  }

  const cells: (number | null)[] = [];
  for (let i = 0; i < firstDay; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  const choices = badgeField && rec ? rec.fields[badgeField]?.choices : null;
  const colorMap = badgeField && rec ? rec.fields[badgeField]?.colors : null;

  return (
    <div>
      {/* Month nav */}
      <div class="flex items-center justify-between mb-4">
        <button onClick={prev} class="px-3 py-1 rounded-md text-sm" style={{ color: "var(--z-muted)", border: "1px solid var(--z-border)" }}>←</button>
        <h3 class="text-sm font-semibold">{MONTHS[month]} {year}</h3>
        <button onClick={next} class="px-3 py-1 rounded-md text-sm" style={{ color: "var(--z-muted)", border: "1px solid var(--z-border)" }}>→</button>
      </div>

      {/* Day headers */}
      <div class="grid grid-cols-7 gap-px mb-1">
        {DAYS.map((d) => (
          <div key={d} class="text-center text-[var(--z-font-xs)] font-mono py-1" style={{ color: "var(--z-muted)" }}>{d}</div>
        ))}
      </div>

      {/* Calendar grid */}
      <div class="grid grid-cols-7 gap-px">
        {cells.map((day, i) => {
          if (day === null) return <div key={i} class="min-h-[80px]" />;
          const dateKey = `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
          const events = byDate[dateKey] || [];
          const isToday = today.getFullYear() === year && today.getMonth() === month && today.getDate() === day;

          return (
            <div
              key={i}
              class="min-h-[80px] p-1 rounded-md transition-colors"
              style={{ border: isToday ? "1px solid var(--z-accent-border)" : "1px solid transparent", background: isToday ? "var(--z-accent-dim)" : "transparent" }}
            >
              <div class="text-[var(--z-font-sm)] font-mono mb-1" style={{ color: isToday ? "var(--z-accent-light)" : "var(--z-muted)" }}>{day}</div>
              {events.slice(0, 3).map((ev) => {
                const badge = badgeField && ev[badgeField] ? String(ev[badgeField]) : undefined;
                const color = badge ? resolveBadgeColor(badge, choices, colorMap) : undefined;
                return (
                  <div
                    key={String(ev.id)}
                    class="text-[var(--z-font-xs)] px-1 py-0.5 rounded mb-0.5 truncate cursor-pointer"
                    style={{ background: "var(--z-card-bg)", border: "var(--z-card-border)" }}
                    onClick={() => onViewDetail(table, String(ev.id))}
                    title={String(ev[titleField] || "")}
                  >
                    {badge && <span class={`inline-block w-1.5 h-1.5 rounded-full mr-1 badge-${color}`} />}
                    {String(ev[titleField] || "—")}
                  </div>
                );
              })}
              {events.length > 3 && (
                <div class="text-[9px] font-mono" style={{ color: "var(--z-muted)" }}>+{events.length - 3} more</div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
