"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { usePathname } from "next/navigation";
import { toast } from "sonner";
import { AlertTriangle, Bell, BellOff, CalendarClock, ChevronLeft, ChevronRight, Plus } from "lucide-react";
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";

import { cn } from "@/lib/utils";
import { formatWeekdayDate } from "@/lib/format";
import { isTimeDuePast } from "@/lib/time-of-day";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useScheduledPanel } from "@/components/scheduled/scheduled-panel-provider";
import { ScheduledTodoItem } from "@/components/scheduled/scheduled-todo-item";
import { ScheduledTodoDialog } from "@/components/scheduled/scheduled-todo-dialog";
import { getScheduledBoard, toggleScheduledOccurrence } from "@/lib/actions/scheduled-todos";
import { useHoldOnComplete, type HoldPhase } from "@/components/hold-on-complete";
import { useScheduledNotifications } from "@/components/scheduled/use-scheduled-notifications";
import type { ScheduledBoardDTO, ScheduledDayDTO, ScheduledOccurrenceDTO } from "@/types/scheduled-todo";

// How often the client re-checks whether any of today's occurrences have
// crossed their time due -- fine-grained enough that "overdue" shows up
// within a minute of actually being overdue, without polling constantly.
const TIME_DUE_CHECK_INTERVAL_MS = 60_000;

function occurrenceKey(scheduledTodoId: string, occurrenceDate: string) {
  return `${scheduledTodoId}-${occurrenceDate}`;
}

/** `layout.tsx` is shared by Home and every Project board, so the panel
 * derives its own scope from the URL rather than a prop threaded down from
 * a page it doesn't render (see the plan notes on why this fetches
 * client-side instead of taking initial data as a prop like KanbanBoard). */
function projectIdFromPathname(pathname: string): string | null {
  const match = /^\/projects\/([^/]+)/.exec(pathname);
  return match ? match[1] : null;
}

function matchesOccurrence(o: ScheduledOccurrenceDTO, scheduledTodoId: string, occurrenceDate: string) {
  return o.scheduledTodoId === scheduledTodoId && o.occurrenceDate === occurrenceDate;
}

/**
 * Promotes today's own occurrences into Overdue once their time due has
 * passed, without waiting for the date to roll over -- the server only
 * buckets by date (it doesn't know the viewer's timezone), so same-day
 * time comparisons happen here against the browser's own clock instead.
 * `holds` keeps a freshly-checked-off one here through its fade, same as
 * ExpandedPanel's own visibleOverdue filter does for "real" overdue rows
 * (see useHoldOnComplete) -- once the hold ends it settles back into
 * `remaining` for good, indistinguishable from any other completed
 * Today item.
 */
function splitTodayByTimeDue(
  today: ScheduledDayDTO,
  now: Date,
  holds: Map<string, HoldPhase>
): { overdueToday: ScheduledOccurrenceDTO[]; remaining: ScheduledOccurrenceDTO[] } {
  const overdueToday: ScheduledOccurrenceDTO[] = [];
  const remaining: ScheduledOccurrenceDTO[] = [];

  for (const o of today.occurrences) {
    const pastDue = !!o.timeDue && isTimeDuePast(today.date, o.timeDue, now);
    const key = occurrenceKey(o.scheduledTodoId, o.occurrenceDate);
    if (pastDue && (!o.completed || holds.has(key))) {
      overdueToday.push(o);
    } else {
      remaining.push(o);
    }
  }

  return { overdueToday, remaining };
}

function withToggledOccurrence(
  board: ScheduledBoardDTO,
  scheduledTodoId: string,
  occurrenceDate: string,
  completed: boolean
): ScheduledBoardDTO {
  const flip = (o: ScheduledOccurrenceDTO) =>
    matchesOccurrence(o, scheduledTodoId, occurrenceDate) ? { ...o, completed } : o;

  // Overdue only ever lists incomplete occurrences -- flip it here just
  // like the other sections, and let ExpandedPanel's own hold-aware filter
  // (see useHoldOnComplete) decide when a freshly-completed one actually
  // drops out of the list, rather than yanking it out the instant it's
  // checked.
  return {
    overdue: board.overdue.map(flip),
    today: { ...board.today, occurrences: board.today.occurrences.map(flip) },
    upcoming: board.upcoming.map((day) => ({ ...day, occurrences: day.occurrences.map(flip) })),
  };
}

export function ScheduledPanel() {
  const { collapsed, toggle } = useScheduledPanel();
  const pathname = usePathname();
  const projectId = projectIdFromPathname(pathname);

  const [board, setBoard] = useState<ScheduledBoardDTO | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  // Mobile bottom sheet (the dock bar below opens it). Kept separate from
  // `dialogOpen` -- that one is the add/edit form dialog.
  const [sheetOpen, setSheetOpen] = useState(false);
  const { holds, beginHold, cancelHold } = useHoldOnComplete();

  const refresh = useCallback(() => {
    getScheduledBoard(projectId)
      .then(setBoard)
      .catch(() => setBoard(null));
  }, [projectId]);

  useEffect(() => {
    setBoard(null);
    refresh();
  }, [refresh]);

  // Ticks on its own so a today occurrence with a time due crosses into
  // Overdue live, without needing a click or a page refresh to notice.
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), TIME_DUE_CHECK_INTERVAL_MS);
    return () => clearInterval(id);
  }, []);

  // The board actually rendered -- board.today with anything past its time
  // due moved into board.overdue (see splitTodayByTimeDue). Recomputed from
  // the raw board on every render rather than stored, so toggling an
  // occurrence or the clock ticking forward both stay in sync automatically.
  const displayBoard = useMemo<ScheduledBoardDTO | null>(() => {
    if (!board) return null;
    const { overdueToday, remaining } = splitTodayByTimeDue(board.today, now, holds);
    return {
      ...board,
      overdue: [...board.overdue, ...overdueToday],
      today: { ...board.today, occurrences: remaining },
    };
  }, [board, now, holds]);

  // Fed the raw board (not displayBoard) -- it does its own pastDue check
  // against board.today directly, independent of the hold-aware promotion
  // above.
  const notifications = useScheduledNotifications(board, now);

  async function handleToggleNotifications() {
    if (notifications.enabled) {
      notifications.disable();
      return;
    }
    if (notifications.permission === "denied") {
      toast.error("Notifications are blocked for this site -- enable them in your browser's site settings.");
      return;
    }
    const granted = await notifications.requestEnable();
    if (granted) {
      toast.success("You'll get a notification when a scheduled to-do's time due passes.");
    } else {
      toast.error("Notification permission wasn't granted.");
    }
  }

  async function handleToggle(occurrence: ScheduledOccurrenceDTO, completed: boolean) {
    setBoard((prev) =>
      prev ? withToggledOccurrence(prev, occurrence.scheduledTodoId, occurrence.occurrenceDate, completed) : prev
    );
    // Only the Overdue section actually consults these holds (see
    // ExpandedPanel), so it's harmless to key one for every occurrence --
    // checking off a Today/Upcoming item just starts a hold nothing ever
    // looks at, which quietly expires on its own.
    const key = occurrenceKey(occurrence.scheduledTodoId, occurrence.occurrenceDate);
    if (completed) beginHold(key);
    else cancelHold(key);
    try {
      await toggleScheduledOccurrence(occurrence.scheduledTodoId, occurrence.occurrenceDate, completed);
    } catch {
      toast.error("Couldn't update scheduled to-do. Try again.");
      refresh();
    }
  }

  function handleEdit(scheduledTodoId: string) {
    setEditingId(scheduledTodoId);
    setDialogOpen(true);
  }

  function handleAdd() {
    setEditingId(null);
    setDialogOpen(true);
  }

  // Reflects true remaining work, not the hold-delayed view -- the
  // collapsed rail's badge should drop the instant something's checked off,
  // even while Overdue's own list still shows it fading out. Counted off
  // displayBoard so a today item past its time due counts as overdue here
  // too, not as still-due-today.
  const overdueCount = displayBoard?.overdue.filter((o) => !o.completed).length ?? 0;
  // Today's occurrences list includes already-checked-off ones (so they can
  // still be toggled back), unlike overdue -- so this needs its own filter
  // rather than just `board.today.occurrences.length`.
  const todayCount = displayBoard?.today.occurrences.filter((o) => !o.completed).length ?? 0;

  return (
    <>
      <aside
        className={cn(
          "hidden h-screen flex-col border-l bg-sidebar text-sidebar-foreground transition-[width] duration-200 md:flex",
          collapsed ? "w-16" : "w-80"
        )}
      >
        {collapsed ? (
          <CollapsedRail
            overdueCount={overdueCount}
            todayCount={todayCount}
            onAdd={handleAdd}
            onExpand={toggle}
          />
        ) : (
          <ExpandedPanel
            board={displayBoard}
            onToggleOccurrence={handleToggle}
            onEditOccurrence={handleEdit}
            onAdd={handleAdd}
            onCollapse={toggle}
            notificationsSupported={notifications.supported}
            notificationsEnabled={notifications.enabled}
            onToggleNotifications={handleToggleNotifications}
          />
        )}
      </aside>

      {/* Mobile (< md) entry point: a dock bar that sits at the bottom of
          the app column (in-flow, so nothing overlaps it) carrying the
          same overdue/today urgency signals as the desktop collapsed
          rail. It opens the full panel as a bottom sheet below rather
          than dedicating permanent screen width to it. */}
      <nav
        aria-label="Scheduled to-dos"
        className="shrink-0 border-t bg-sidebar text-sidebar-foreground md:hidden"
      >
        <button
          type="button"
          onClick={() => setSheetOpen(true)}
          className="flex h-14 w-full items-center justify-center gap-2 transition-colors active:bg-accent/60"
        >
          <CalendarClock className="size-5" />
          <span className="text-sm font-semibold">Scheduled</span>
          {overdueCount > 0 && (
            <span
              className="relative flex size-5 items-center justify-center"
              aria-label={`${overdueCount} overdue`}
            >
              <span className="absolute inline-flex size-full animate-ping rounded-full bg-destructive opacity-75" />
              <span className="relative flex size-5 items-center justify-center rounded-full bg-destructive text-[10px] font-bold text-white">
                {overdueCount > 9 ? "9+" : overdueCount}
              </span>
            </span>
          )}
          {todayCount > 0 && (
            <span
              className="flex size-5 animate-pulse items-center justify-center rounded-full bg-white text-[10px] font-bold text-black shadow-sm ring-1 ring-border"
              aria-label={`${todayCount} due today`}
            >
              {todayCount > 9 ? "9+" : todayCount}
            </span>
          )}
        </button>
        {/* Room for the iPhone home indicator so the bar never tucks under it. */}
        <div style={{ paddingBottom: "env(safe-area-inset-bottom)" }} />
      </nav>

      <DialogPrimitive.Root open={sheetOpen} onOpenChange={setSheetOpen}>
        <DialogPrimitive.Portal>
          <DialogPrimitive.Backdrop
            className="fixed inset-0 z-40 bg-black/60 duration-100 data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0 md:hidden"
          />
          <DialogPrimitive.Popup
            className={cn(
              "fixed inset-x-0 bottom-0 z-50 flex flex-col rounded-t-2xl bg-popover text-popover-foreground shadow-2xl duration-200 md:hidden",
              "data-open:animate-in data-open:fade-in-0 data-open:slide-in-from-bottom",
              "data-closed:animate-out data-closed:fade-out-0 data-closed:slide-out-to-bottom"
            )}
          >
            <DialogPrimitive.Title className="sr-only">Scheduled to-dos</DialogPrimitive.Title>
            {/* Grabber -- visual affordance that this is a sheet, not the whole screen. */}
            <div className="mx-auto mt-2 h-1 w-10 shrink-0 rounded-full bg-foreground/20" aria-hidden />
            <div className="flex max-h-[85dvh] min-h-0 flex-col">
              <ExpandedPanel
                board={displayBoard}
                onToggleOccurrence={handleToggle}
                onEditOccurrence={handleEdit}
                onAdd={handleAdd}
                onCollapse={() => setSheetOpen(false)}
                notificationsSupported={notifications.supported}
                notificationsEnabled={notifications.enabled}
                onToggleNotifications={handleToggleNotifications}
              />
            </div>
          </DialogPrimitive.Popup>
        </DialogPrimitive.Portal>
      </DialogPrimitive.Root>

      <ScheduledTodoDialog
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        projectId={projectId}
        scheduledTodoId={editingId}
        onSaved={refresh}
        onDeleted={refresh}
      />
    </>
  );
}

function CollapsedRail({
  overdueCount,
  todayCount,
  onAdd,
  onExpand,
}: {
  overdueCount: number;
  todayCount: number;
  onAdd: () => void;
  onExpand: () => void;
}) {
  return (
    <>
      <div className="flex flex-col items-center gap-1.5 p-3">
        <Tooltip>
          <TooltipTrigger
            render={
              <button
                type="button"
                onClick={onExpand}
                className="flex size-8 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-accent-foreground"
                aria-label="Expand scheduled to-dos"
              >
                <CalendarClock className="size-5" />
              </button>
            }
          />
          <TooltipContent side="left">Scheduled to-dos</TooltipContent>
        </Tooltip>

        {/* Sits right below the calendar icon rather than as a corner
            overlay -- a ping ring behind the solid circle makes overdue
            work as loud/eye-catching as possible. */}
        {overdueCount > 0 && (
          <Tooltip>
            <TooltipTrigger
              render={
                <button
                  type="button"
                  onClick={onExpand}
                  className="relative flex size-5 items-center justify-center"
                  aria-label={`${overdueCount} overdue`}
                >
                  <span className="absolute inline-flex size-full animate-ping rounded-full bg-destructive opacity-75" />
                  <span className="relative flex size-5 items-center justify-center rounded-full bg-destructive text-[10px] font-bold text-white">
                    {overdueCount > 9 ? "9+" : overdueCount}
                  </span>
                </button>
              }
            />
            <TooltipContent side="left">{overdueCount} overdue</TooltipContent>
          </Tooltip>
        )}

        {/* Below the overdue circle when both are present, otherwise right
            below the calendar icon -- a plain opacity pulse (no ping ring)
            keeps it visibly calmer than overdue's. */}
        {todayCount > 0 && (
          <Tooltip>
            <TooltipTrigger
              render={
                <button
                  type="button"
                  onClick={onExpand}
                  className="flex size-5 animate-pulse items-center justify-center rounded-full bg-white text-[10px] font-bold text-black shadow-sm ring-1 ring-border"
                  aria-label={`${todayCount} due today`}
                >
                  {todayCount > 9 ? "9+" : todayCount}
                </button>
              }
            />
            <TooltipContent side="left">{todayCount} due today</TooltipContent>
          </Tooltip>
        )}
      </div>

      <div className="flex flex-1 flex-col items-center justify-end gap-1 p-2">
        <Tooltip>
          <TooltipTrigger
            render={
              <Button variant="ghost" size="icon" onClick={onAdd} aria-label="Add scheduled to-do">
                <Plus className="size-4" />
              </Button>
            }
          />
          <TooltipContent side="left">Add Scheduled To-Do</TooltipContent>
        </Tooltip>

        <Button variant="ghost" size="icon" onClick={onExpand} aria-label="Expand scheduled panel">
          <ChevronLeft className="size-4" />
        </Button>
      </div>
    </>
  );
}

function ExpandedPanel({
  board,
  onToggleOccurrence,
  onEditOccurrence,
  onAdd,
  onCollapse,
  notificationsSupported,
  notificationsEnabled,
  onToggleNotifications,
}: {
  board: ScheduledBoardDTO | null;
  onToggleOccurrence: (occurrence: ScheduledOccurrenceDTO, completed: boolean) => void;
  onEditOccurrence: (scheduledTodoId: string) => void;
  onAdd: () => void;
  onCollapse: () => void;
  notificationsSupported: boolean;
  notificationsEnabled: boolean;
  onToggleNotifications: () => void;
}) {
  const { holds } = useHoldOnComplete();

  // A freshly-checked-off occurrence lingers here through its hold (see
  // useHoldOnComplete) instead of dropping out the instant it's completed;
  // once its hold expires it's gone for good, same as before. The header
  // count below counts this same list, so it never disagrees with what's
  // actually on screen -- unlike the collapsed rail's badge, which drops
  // the instant something's checked off (see ScheduledPanel's overdueCount).
  const visibleOverdue =
    board?.overdue.filter(
      (o) => !o.completed || holds.has(occurrenceKey(o.scheduledTodoId, o.occurrenceDate))
    ) ?? [];

  return (
    <>
      <div className="flex items-center justify-between gap-2 px-3 py-3">
        <div className="flex min-w-0 items-center gap-2.5">
          <span className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
            <CalendarClock className="size-4" />
          </span>
          <span className="truncate font-heading text-[15px] font-semibold tracking-tight">Scheduled</span>
        </div>
        <div className="flex shrink-0 items-center gap-1">
          {notificationsSupported && (
            <Tooltip>
              <TooltipTrigger
                render={
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={onToggleNotifications}
                    aria-label={notificationsEnabled ? "Turn off notifications" : "Turn on notifications"}
                  >
                    {notificationsEnabled ? (
                      <Bell className="size-4" />
                    ) : (
                      <BellOff className="size-4 text-muted-foreground" />
                    )}
                  </Button>
                }
              />
              <TooltipContent side="left">
                {notificationsEnabled ? "Notifications on" : "Notify me when something's due"}
              </TooltipContent>
            </Tooltip>
          )}
          <Button
            variant="ghost"
            size="icon"
            onClick={onCollapse}
            aria-label="Collapse scheduled panel"
          >
            <ChevronRight className="size-4" />
          </Button>
        </div>
      </div>

      <Separator />

      <div className="min-h-0 flex-1 overflow-y-auto p-3">
        {!board ? (
          <p className="p-2 text-center text-sm text-muted-foreground">Loading…</p>
        ) : (
          <div className="space-y-5">
            {visibleOverdue.length > 0 && (
              <section className="rounded-lg border-2 border-destructive bg-destructive/10 p-3">
                <div className="mb-1.5 flex items-center gap-1.5 text-sm font-bold text-destructive">
                  <AlertTriangle className="size-4 animate-pulse" />
                  Overdue ({visibleOverdue.length})
                </div>
                <ul>
                  {visibleOverdue.map((o) => (
                    <ScheduledTodoItem
                      key={`${o.scheduledTodoId}-${o.occurrenceDate}`}
                      occurrence={o}
                      emphasis="overdue"
                      holdPhase={holds.get(occurrenceKey(o.scheduledTodoId, o.occurrenceDate))}
                      onToggle={(completed) => onToggleOccurrence(o, completed)}
                      onEdit={() => onEditOccurrence(o.scheduledTodoId)}
                    />
                  ))}
                </ul>
              </section>
            )}

            <section>
              <h3 className="mb-1.5 text-sm font-bold text-foreground">
                Today — {formatWeekdayDate(board.today.date)}
              </h3>
              {board.today.occurrences.length > 0 ? (
                <ul>
                  {board.today.occurrences.map((o) => (
                    <ScheduledTodoItem
                      key={`${o.scheduledTodoId}-${o.occurrenceDate}`}
                      occurrence={o}
                      emphasis="today"
                      onToggle={(completed) => onToggleOccurrence(o, completed)}
                      onEdit={() => onEditOccurrence(o.scheduledTodoId)}
                    />
                  ))}
                </ul>
              ) : (
                <p className="text-xs text-muted-foreground">Nothing scheduled today.</p>
              )}
            </section>

            {board.upcoming.map((day, index) => (
              // Fades a little more for each day further from today, so
              // today reads as the loudest thing in the column.
              <section key={day.date} style={{ opacity: Math.max(0.35, 1 - (index + 1) * 0.13) }}>
                <h3 className="mb-1.5 text-sm font-semibold text-muted-foreground">
                  {formatWeekdayDate(day.date)}
                </h3>
                {day.occurrences.length > 0 ? (
                  <ul>
                    {day.occurrences.map((o) => (
                      <ScheduledTodoItem
                        key={`${o.scheduledTodoId}-${o.occurrenceDate}`}
                        occurrence={o}
                        onToggle={(completed) => onToggleOccurrence(o, completed)}
                        onEdit={() => onEditOccurrence(o.scheduledTodoId)}
                      />
                    ))}
                  </ul>
                ) : (
                  <p className="text-xs text-muted-foreground">Nothing scheduled.</p>
                )}
              </section>
            ))}
          </div>
        )}
      </div>

      <Separator />

      <div className="p-2">
        <Button
          variant="ghost"
          className="w-full justify-start gap-2 text-muted-foreground"
          onClick={onAdd}
        >
          <Plus className="size-4" />
          Add Scheduled To-Do
        </Button>
      </div>
    </>
  );
}
