"use client";

import dynamic from "next/dynamic";
import { useRouter } from "next/navigation";
import { Pin, PinOff, Save, Trash2 } from "lucide-react";
import { useState, useTransition } from "react";
import { EntityComments } from "@/components/comments/entity-comments";
import { RichTextContent } from "@/components/rich-text";
import { DetailBackLink } from "@/components/detail-back-link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ShareButton } from "@/components/share-button";
import type { NoteDto } from "../server/queries";
import { createNote, deleteNote, setNotePinned, updateNote } from "../server/actions";

const RichTextEditor = dynamic(
  () => import("@/components/rich-text/rich-text-editor").then((mod) => mod.RichTextEditor),
  {
    ssr: false,
    loading: () => (
      <div className="min-h-80 rounded-[var(--r-md)] border-[0.5px] px-3 py-2 text-sm muted animate-pulse">
        Loading editor…
      </div>
    ),
  },
);

export function NoteEditor({ note, currentUserId }: { note?: NoteDto; currentUserId?: string }) {
  const router = useRouter();
  const [currentNote, setCurrentNote] = useState(note);
  const [title, setTitle] = useState(note?.title ?? "");
  const [body, setBody] = useState(note?.body ?? "");
  const [remindAt, setRemindAt] = useState(toLocalDateTimeValue(note?.remindAt ?? null));
  const [isPending, startTransition] = useTransition();

  const pinned = currentNote?.pinned ?? false;

  function saveNote() {
    startTransition(async () => {
      if (currentNote) {
        const updated = await updateNote({
          id: currentNote.id,
          title,
          body,
          remindAt: remindAt ? new Date(remindAt) : null,
        });
        setCurrentNote(updated);
        return;
      }

      const created = await createNote({
        title,
        body,
        remindAt: remindAt ? new Date(remindAt) : null,
      });
      router.push(`/notes/${created.id}`);
    });
  }

  function togglePinned() {
    if (!currentNote) return;
    startTransition(async () => {
      setCurrentNote(await setNotePinned({ id: currentNote.id, pinned: !pinned }));
    });
  }

  function removeNote() {
    if (!currentNote) return;
    startTransition(async () => {
      await deleteNote({ id: currentNote.id });
      router.push("/notes");
    });
  }

  return (
    <div className="mx-auto grid w-full max-w-6xl gap-4 min-w-0">
      <DetailBackLink href="/notes" label="Notes" />
      <header className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div className="flex items-center gap-2 min-w-0 flex-1">
          {pinned && <Pin className="size-3.5 text-[var(--accent)]" />}
          <h2 className="serif text-[24px] font-medium tracking-tight truncate">
            {currentNote ? currentNote.title : "New note"}
          </h2>
        </div>
        <div className="flex flex-wrap gap-2">
          {currentNote ? (
            <Button variant="outline" size="sm" onClick={togglePinned} disabled={isPending}>
              {pinned ? <PinOff className="size-3.5" /> : <Pin className="size-3.5" />}
              {pinned ? "Unpin note" : "Pin note"}
            </Button>
          ) : null}
          {currentNote ? <ShareButton entityType="notes.note" entityId={currentNote.id} /> : null}
          {currentNote ? (
            <Button variant="destructive" size="sm" onClick={removeNote} disabled={isPending}>
              <Trash2 className="size-3.5" />
              Delete note
            </Button>
          ) : null}
          <Button size="sm" onClick={saveNote} disabled={!title.trim() || isPending}>
            <Save className="size-3.5" />
            Save note
          </Button>
        </div>
      </header>

      <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(280px,420px)] min-w-0">
        <section
          className="grid gap-4 rounded-[var(--r-lg)] border-[0.5px] bg-[var(--card)] p-4 shadow-[var(--shadow-1)] min-w-0"
          style={{ borderColor: "var(--hair)" }}
        >
          <div className="space-y-1.5">
            <Label htmlFor="note-title">Title</Label>
            <Input
              id="note-title"
              value={title}
              onChange={(event) => setTitle(event.target.value)}
            />
          </div>
          <div className="space-y-1.5 min-w-0">
            <Label htmlFor="note-body">Body</Label>
            <RichTextEditor
              id="note-body"
              aria-label="Body"
              value={body}
              onChange={setBody}
              disabled={isPending}
              placeholder="Start writing…"
            />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="note-reminder">Reminder</Label>
            <Input
              id="note-reminder"
              type="datetime-local"
              value={remindAt}
              onChange={(event) => setRemindAt(event.target.value)}
            />
          </div>
        </section>

        <aside
          className="rounded-[var(--r-lg)] border-[0.5px] bg-[var(--card)] p-4 text-[var(--ink)] shadow-[var(--shadow-1)] min-w-0"
          style={{ borderColor: "var(--hair)" }}
          aria-label="Preview"
        >
          <div className="eyebrow mb-3">Preview</div>
          <RichTextContent html={body} />
        </aside>
      </div>

      {currentNote && currentUserId ? (
        <EntityComments
          entityType="notes.note"
          entityId={currentNote.id}
          currentUserId={currentUserId}
        />
      ) : null}
    </div>
  );
}

function toLocalDateTimeValue(value: string | null) {
  if (!value) return "";
  const date = new Date(value);
  const local = new Date(date.getTime() - date.getTimezoneOffset() * 60_000);
  return local.toISOString().slice(0, 16);
}
