"use client";

import * as React from "react";

import { History, StickyNote, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";
import { requestDashboardDelete } from "@/lib/dashboard-mutations.client";
import { toastApiError } from "@/lib/toast-api-error";

import type { OrderNote } from "../schema";

type OrderNotesPanelProps = {
  notes: OrderNote[];
  statusLabels: Record<string, string>;
  /** Allow deleting internal notes (edit form / detail page). */
  canDelete?: boolean;
};

function describeNote(note: OrderNote, statusLabels: Record<string, string>) {
  if (note.type !== "S") return note.text;

  const from = statusLabels[note.fromStatus] ?? note.fromStatus;
  const to = statusLabels[note.toStatus] ?? note.toStatus;
  return `Status changed from ${from || "—"} to ${to || "—"}`;
}

/** Order history: internal notes plus automatic status changes. */
export function OrderNotesPanel({ notes: initialNotes, statusLabels, canDelete = true }: OrderNotesPanelProps) {
  const [notes, setNotes] = React.useState(initialNotes);
  const [deletingId, setDeletingId] = React.useState<number | null>(null);

  if (notes.length === 0) {
    return <p className="text-muted-foreground text-sm">No notes yet.</p>;
  }

  const handleDelete = async (noteId: number) => {
    setDeletingId(noteId);
    try {
      await requestDashboardDelete(
        FRONTEND_ROUTES.plansOrders.orders.deleteNote,
        noteId,
        "Note could not be deleted.",
      );
      setNotes((current) => current.filter((note) => note.id !== noteId));
      toast.success("Note deleted.");
    } catch (error) {
      toastApiError(error, "Note could not be deleted.");
    } finally {
      setDeletingId(null);
    }
  };

  return (
    <ul className="space-y-2">
      {notes.map((note) => (
        <li key={note.id} className="flex items-start gap-3 rounded-lg border bg-muted/20 px-3 py-2">
          {note.type === "S" ? (
            <History className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
          ) : (
            <StickyNote className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
          )}
          <div className="min-w-0 flex-1">
            <p className="whitespace-pre-line text-sm">{describeNote(note, statusLabels)}</p>
            <p className="text-muted-foreground text-xs">
              {[note.author, note.dateAdded].filter(Boolean).join(" · ")}
            </p>
          </div>
          {canDelete && note.type !== "S" ? (
            <Button
              type="button"
              variant="ghost"
              size="icon-sm"
              className="size-7 text-rose-600 hover:bg-rose-50 hover:text-rose-700"
              disabled={deletingId === note.id}
              aria-label="Delete note"
              onClick={() => void handleDelete(note.id)}
            >
              <Trash2 className="size-3.5" />
            </Button>
          ) : null}
        </li>
      ))}
    </ul>
  );
}
