import { Link } from "@tanstack/react-router";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useState } from "react";
import { Card } from "./page";
import { Button } from "@/components/ui/button";
import type { Obligation } from "@/api/types";
import { todayIso } from "@/lib/dates";
import { cn } from "@/lib/utils";

const TONE: Record<string, string> = {
  overdue: "bg-danger-soft text-danger",
  returned: "bg-warning-soft text-warning",
  open: "bg-primary-soft text-primary",
  submitted: "bg-amber-soft text-warning",
  approved: "bg-success-soft text-success",
};
const move = (ym: string, n: number) => {
  const [y, m] = ym.split("-").map(Number);
  return new Date(Date.UTC(y!, m! - 1 + n, 1)).toISOString().slice(0, 7);
};
/** One month of due dates. */
export function ObligationCalendar({ pid, items }: { pid: string; items: Obligation[] }) {
  const today = todayIso();
  const [ym, setYm] = useState(today.slice(0, 7));
  const [y, m] = ym.split("-").map(Number);
  const first = new Date(Date.UTC(y!, m! - 1, 1));
  const days = new Date(Date.UTC(y!, m!, 0)).getUTCDate();
  const pad = (first.getUTCDay() + 6) % 7;
  const title = first.toLocaleDateString("en-GB", {
    month: "long",
    year: "numeric",
    timeZone: "UTC",
  });
  return (
    <Card
      title={title}
      actions={
        <span className="flex gap-1">
          <Button
            size="sm"
            variant="outline"
            aria-label="Previous month"
            onClick={() => setYm(move(ym, -1))}
          >
            <ChevronLeft />
          </Button>
          <Button size="sm" variant="outline" onClick={() => setYm(today.slice(0, 7))}>
            Today
          </Button>
          <Button
            size="sm"
            variant="outline"
            aria-label="Next month"
            onClick={() => setYm(move(ym, 1))}
          >
            <ChevronRight />
          </Button>
        </span>
      }
    >
      <div className="overflow-x-auto">
        <div className="grid min-w-[700px] grid-cols-7 gap-px overflow-hidden rounded-lg border bg-border">
          {["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => (
            <div key={d} className="bg-surface-2 px-2 py-1 text-[12px] font-medium">
              {d}
            </div>
          ))}
          {Array.from({ length: pad }, (_, i) => (
            <div key={`p${i}`} className="bg-card" />
          ))}
          {Array.from({ length: days }, (_, i) => {
            const date = `${ym}-${String(i + 1).padStart(2, "0")}`;
            const due = items.filter((o) => o.dueDate === date);
            return (
              <div key={date} className="min-h-24 min-w-0 bg-card p-1">
                <p className={cn("text-[12px]", date === today && "font-bold text-primary")}>
                  {i + 1}
                </p>
                {due.slice(0, 4).map((o) => (
                  <Link
                    key={o.id}
                    to="/p/$pid/obligations/$id"
                    params={{ pid, id: o.id }}
                    title={`${o.activity.name}, ${o.providerCode}, ${o.scopeLabel}, ${o.status}`}
                    className={cn(
                      "mt-0.5 block truncate rounded px-1 text-[11px]",
                      TONE[o.status] ?? "bg-surface-2",
                    )}
                  >
                    {o.providerCode}: {o.activity.name}
                  </Link>
                ))}
                {due.length > 4 && <p className="text-[11px]">and {due.length - 4} more</p>}
              </div>
            );
          })}
        </div>
      </div>
    </Card>
  );
}
