"use client";

import { useEffect, useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import {
  WEEKDAY_LABELS_DE,
  WEEKDAY_LABELS_EN,
  MONTH_LABELS_DE,
  MONTH_LABELS_EN,
  dayKey,
  monthGrid,
} from "@/lib/calendarGrid";

// Rein binäre Frei/Belegt-Anzeige ohne Kundennamen oder sonstige Details —
// öffentlich einsehbar, deshalb bewusst nichts, was Rückschlüsse auf
// einzelne Kund:innen erlaubt. Client-Komponente (statt wie zuvor Server-
// Komponente), damit sich per Pfeiltasten beliebig weit nach vorn blättern
// lässt, ohne die ganze Seite neu zu laden — die Daten pro Zwei-Monats-
// Fenster kommen von /api/availability.
export function AvailabilityCalendar({ locale }: { locale: string }) {
  const t = useTranslations("availability");
  const isEn = locale === "en";
  const weekdayLabels = isEn ? WEEKDAY_LABELS_EN : WEEKDAY_LABELS_DE;
  const monthLabels = isEn ? MONTH_LABELS_EN : MONTH_LABELS_DE;

  const now = useMemo(() => new Date(), []);
  const [windowStart, setWindowStart] = useState({ year: now.getFullYear(), monthIndex: now.getMonth() });
  const [busyDays, setBusyDays] = useState<Set<string> | null>(null);

  useEffect(() => {
    let cancelled = false;
    setBusyDays(null);
    fetch(`/api/availability?year=${windowStart.year}&month=${windowStart.monthIndex}`)
      .then((r) => r.json())
      .then((data: { busyDays: string[] }) => {
        if (!cancelled) setBusyDays(new Set(data.busyDays));
      })
      .catch(() => {
        if (!cancelled) setBusyDays(new Set());
      });
    return () => {
      cancelled = true;
    };
  }, [windowStart.year, windowStart.monthIndex]);

  // Höchstens 6 Monate im Voraus einsehbar (statt beliebig weit) — die
  // Ansicht zeigt immer zwei Monate, daher darf der erste angezeigte Monat
  // maximal 5 Monate nach dem aktuellen liegen, damit der zweite (letzte)
  // angezeigte Monat nicht über +6 hinausgeht.
  const nowTotal = now.getFullYear() * 12 + now.getMonth();
  const maxWindowTotal = nowTotal + 5;

  const atEarliest = windowStart.year === now.getFullYear() && windowStart.monthIndex === now.getMonth();
  const atLatest = windowStart.year * 12 + windowStart.monthIndex >= maxWindowTotal;

  function shift(deltaMonths: number) {
    setWindowStart((prev) => {
      const prevTotal = prev.year * 12 + prev.monthIndex;
      const clampedTotal = Math.min(Math.max(prevTotal + deltaMonths, nowTotal), maxWindowTotal);
      return { year: Math.floor(clampedTotal / 12), monthIndex: clampedTotal % 12 };
    });
  }

  const secondMonth = new Date(windowStart.year, windowStart.monthIndex + 1, 1);
  const months = [
    windowStart,
    { year: secondMonth.getFullYear(), monthIndex: secondMonth.getMonth() },
  ];
  const todayKey = dayKey(now);

  return (
    <div className="rk-shell mb-14">
    <div className="max-w-7xl mx-auto">
      <p className="text-xs uppercase tracking-[0.15em] text-[var(--rk-ink-muted)] text-center mb-6">{t("title")}</p>

      <div className="flex items-center justify-center gap-4 mb-4">
        <button
          type="button"
          onClick={() => shift(-2)}
          disabled={atEarliest}
          aria-label={t("prevMonths")}
          className="text-lg leading-none text-[var(--rk-ink-muted)] hover:text-[var(--rk-ink)] disabled:opacity-20 disabled:hover:text-[var(--rk-ink-muted)] disabled:cursor-not-allowed transition-colors px-2 py-1"
        >
          ‹
        </button>
        <span className="text-xs text-[var(--rk-ink-muted)] w-52 text-center">
          {monthLabels[months[0].monthIndex]} {months[0].year} – {monthLabels[months[1].monthIndex]} {months[1].year}
        </span>
        <button
          type="button"
          onClick={() => shift(2)}
          disabled={atLatest}
          aria-label={t("nextMonths")}
          className="text-lg leading-none text-[var(--rk-ink-muted)] hover:text-[var(--rk-ink)] disabled:opacity-20 disabled:hover:text-[var(--rk-ink-muted)] disabled:cursor-not-allowed transition-colors px-2 py-1"
        >
          ›
        </button>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-8">
        {months.map(({ year, monthIndex }) => (
          <div key={`${year}-${monthIndex}`}>
            <p className="text-sm text-center mb-3 text-[var(--rk-ink)]">
              {monthLabels[monthIndex]} {year}
            </p>
            <div className="grid grid-cols-7 gap-1">
              {weekdayLabels.map((w) => (
                <div key={w} className="text-center text-[0.6rem] uppercase tracking-[0.08em] text-[var(--rk-ink-muted)] pb-1">
                  {w}
                </div>
              ))}
              {monthGrid(year, monthIndex).map((d) => {
                const key = dayKey(d);
                const inMonth = d.getMonth() === monthIndex;
                const isPast = key < todayKey;
                const busy = busyDays?.has(key) ?? false;
                return (
                  <div
                    key={key}
                    className={`aspect-square rounded flex items-center justify-center text-[0.65rem] ${
                      !inMonth || isPast
                        ? "text-[var(--rk-ink-muted)]/30"
                        : busyDays === null
                          ? "text-[var(--rk-ink-muted)]/40"
                          : busy
                            ? "bg-white/10 text-[var(--rk-ink-muted)]"
                            : "bg-emerald-400/10 text-emerald-400"
                    }`}
                  >
                    {d.getDate()}
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
      <div className="flex items-center justify-center gap-5 mt-6 text-[0.65rem] text-[var(--rk-ink-muted)]">
        <span className="flex items-center gap-1.5">
          <span className="w-2.5 h-2.5 rounded-sm bg-emerald-400/10 border border-emerald-400/30" /> {t("free")}
        </span>
        <span className="flex items-center gap-1.5">
          <span className="w-2.5 h-2.5 rounded-sm bg-white/10 border border-white/20" /> {t("busy")}
        </span>
      </div>
      <p className="text-xs text-[var(--rk-ink-muted)] text-center mt-3">{t("hint")}</p>
    </div>
    </div>
  );
}
