"use client";

import { useState } from "react";
import { useTheme } from "next-themes";
import { NotebookPen, Pencil } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { MDEditor, MarkdownPreview } from "@/components/markdown/markdown-widgets";
import { useBoard } from "@/components/board/board-context";
import type { GroupDTO } from "@/types/board";

export function NotesDialog({ group }: { group: GroupDTO }) {
  const { saveNote } = useBoard();
  const { resolvedTheme } = useTheme();
  const colorMode = resolvedTheme === "dark" ? "dark" : "light";

  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(group.noteContent);
  const [pending, setPending] = useState(false);

  function handleOpenChange(next: boolean) {
    setOpen(next);
    if (next) {
      setDraft(group.noteContent);
      setEditing(false);
    }
  }

  async function handleSave() {
    setPending(true);
    const ok = await saveNote(group.id, group.categoryId, draft);
    setPending(false);
    if (ok) setEditing(false);
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <Button
        variant="ghost"
        size="icon"
        className="size-7 shrink-0"
        aria-label={`Notes for ${group.title}`}
        onClick={() => handleOpenChange(true)}
      >
        <NotebookPen className="size-4" />
      </Button>
      <DialogContent className="sm:max-w-2xl" data-color-mode={colorMode}>
        <DialogHeader>
          <DialogTitle>{group.title} — Notes</DialogTitle>
        </DialogHeader>

        {editing ? (
          <MDEditor value={draft} onChange={(v) => setDraft(v ?? "")} height={360} />
        ) : draft ? (
          <div className="max-h-[60vh] overflow-y-auto rounded-md border p-4">
            <MarkdownPreview source={draft} />
          </div>
        ) : (
          <p className="rounded-md border border-dashed p-8 text-center text-sm text-muted-foreground">
            No notes yet. Click Edit to add some.
          </p>
        )}

        <DialogFooter>
          {editing ? (
            <>
              <Button variant="outline" onClick={() => setEditing(false)} disabled={pending}>
                Cancel
              </Button>
              <Button onClick={handleSave} disabled={pending}>
                {pending ? "Saving…" : "Save"}
              </Button>
            </>
          ) : (
            <Button variant="outline" onClick={() => setEditing(true)} className="gap-2">
              <Pencil className="size-4" />
              Edit
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
