"use client";

import { cn } from "@/lib/utils";
import { Badge } from "@/components/ds";

export type CalendarAppointment = {
  id: string;
  title: string;
  start: string;
  end: string;
  status?: string;
  subtitle?: string;
};

const HOURS = Array.from({ length: 12 }, (_, i) => i + 8);

function dayKey(d: Date) {
  return d.toISOString().slice(0, 10);
}

/** Week/day appointment calendar grid — responsive, RTL-friendly. */
export function AppointmentCalendar({
  appointments,
  mode = "week",
  onSelect,
  className,
}: {
  appointments: CalendarAppointment[];
  mode?: "week" | "day";
  onSelect?: (appt: CalendarAppointment) => void;
  className?: string;
}) {
  const today = new Date();
  const start = new Date(today);
  start.setHours(0, 0, 0, 0);
  if (mode === "week") {
    const dow = start.getDay();
    start.setDate(start.getDate() - ((dow + 1) % 7));
  }

  const days: Date[] =
    mode === "day"
      ? [start]
      : Array.from({ length: 7 }, (_, i) => {
          const d = new Date(start);
          d.setDate(start.getDate() + i);
          return d;
        });

  const byDay = new Map<string, CalendarAppointment[]>();
  for (const a of appointments) {
    const k = dayKey(new Date(a.start));
    if (!byDay.has(k)) byDay.set(k, []);
    byDay.get(k)!.push(a);
  }

  return (
    <div className={cn("overflow-x-auto rounded-2xl border border-[var(--border)] bg-[var(--surface)]", className)}>
      <div className="grid min-w-[720px]" style={{ gridTemplateColumns: `64px repeat(${days.length}, 1fr)` }}>
        <div className="border-b border-[var(--border)] bg-[var(--surface-muted)] p-2" />
        {days.map((d) => (
          <div
            key={d.toISOString()}
            className="border-b border-s border-[var(--border)] bg-[var(--surface-muted)] px-2 py-2 text-center text-xs font-medium text-secondary"
          >
            {d.toLocaleDateString("fa-IR", { weekday: "short", day: "numeric", month: "short" })}
          </div>
        ))}
        {HOURS.map((hour) => (
          <div key={`row-${hour}`} className="contents">
            <div className="border-b border-[var(--border)] px-2 py-3 text-xs text-[var(--muted)]">
              {hour}:00
            </div>
            {days.map((d) => {
              const k = dayKey(d);
              const slotApps = (byDay.get(k) ?? []).filter((a) => new Date(a.start).getHours() === hour);
              return (
                <div
                  key={`${k}-${hour}`}
                  className="relative min-h-[52px] border-b border-s border-[var(--border)] p-1"
                >
                  {slotApps.map((a) => (
                    <button
                      key={a.id}
                      type="button"
                      onClick={() => onSelect?.(a)}
                      className="mb-1 block w-full rounded-lg border border-[var(--health-accent,#0d9488)]/30 bg-[var(--health-accent-soft,rgba(13,148,136,0.08))] px-2 py-1 text-start text-xs transition hover:shadow-sm"
                    >
                      <span className="font-medium text-secondary">{a.title}</span>
                      {a.subtitle ? (
                        <span className="mt-0.5 block text-[var(--muted)]">{a.subtitle}</span>
                      ) : null}
                      {a.status ? (
                        <Badge tone="default" className="mt-1">
                          {a.status}
                        </Badge>
                      ) : null}
                    </button>
                  ))}
                </div>
              );
            })}
          </div>
        ))}
      </div>
    </div>
  );
}
