"use client";

import { useCallback, useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import { toast } from "sonner";
import { AlertTriangle, CalendarClock, ChevronLeft, ChevronRight, Plus } from "lucide-react";

import { cn } from "@/lib/utils";
import { formatWeekdayDate } from "@/lib/format";
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 type { ScheduledBoardDTO, ScheduledOccurrenceDTO } from "@/types/scheduled-todo";

/** `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;
}

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

  return {
    // Overdue only ever lists incomplete occurrences -- completing one
    // removes it rather than leaving a checked-off item in the flashy list.
    overdue: completed
      ? board.overdue.filter((o) => !matchesOccurrence(o, scheduledTodoId, occurrenceDate))
      : 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);

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

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

  async function handleToggle(occurrence: ScheduledOccurrenceDTO, completed: boolean) {
    setBoard((prev) =>
      prev ? withToggledOccurrence(prev, occurrence.scheduledTodoId, occurrence.occurrenceDate, completed) : prev
    );
    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);
  }

  const overdueCount = board?.overdue.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 = board?.today.occurrences.filter((o) => !o.completed).length ?? 0;

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

      <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,
}: {
  board: ScheduledBoardDTO | null;
  onToggleOccurrence: (occurrence: ScheduledOccurrenceDTO, completed: boolean) => void;
  onEditOccurrence: (scheduledTodoId: string) => void;
  onAdd: () => void;
  onCollapse: () => void;
}) {
  return (
    <>
      <div className="flex items-center justify-between gap-2 p-3">
        <div className="flex min-w-0 items-center gap-2">
          <CalendarClock className="size-5 shrink-0 text-primary" />
          <span className="truncate text-lg font-semibold">Scheduled</span>
        </div>
        <Button
          variant="ghost"
          size="icon"
          onClick={onCollapse}
          aria-label="Collapse scheduled panel"
        >
          <ChevronRight className="size-4" />
        </Button>
      </div>

      <Separator />

      <div className="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">
            {board.overdue.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 ({board.overdue.length})
                </div>
                <ul>
                  {board.overdue.map((o) => (
                    <ScheduledTodoItem
                      key={`${o.scheduledTodoId}-${o.occurrenceDate}`}
                      occurrence={o}
                      emphasis="overdue"
                      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>
    </>
  );
}
