"use client";

import { useRouter } from "next/navigation";
import { Pin, PinOff, Save, Trash2 } from "lucide-react";
import { useState, useTransition } from "react";
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";
import { MarkdownPreview } from "./markdown-preview";

export function NoteEditor({ note }: { note?: NoteDto }) {
  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,
          createdAt: updated.createdAt.toISOString(),
          updatedAt: updated.updatedAt.toISOString(),
          remindAt: updated.remindAt?.toISOString() ?? null,
        });
        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-5 p-4">
      <header className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <h1 className="text-2xl font-semibold">{currentNote ? currentNote.title : "New note"}</h1>
          <p className="text-sm text-muted-foreground">Markdown notes shared with the household.</p>
        </div>
        <div className="flex flex-wrap gap-2">
          {currentNote ? (
            <Button variant="outline" onClick={togglePinned} disabled={isPending}>
              {pinned ? <PinOff /> : <Pin />}
              {pinned ? "Unpin note" : "Pin note"}
            </Button>
          ) : null}
          {currentNote ? (
            <ShareButton entityType="notes.note" entityId={currentNote.id} />
          ) : null}
          {currentNote ? (
            <Button variant="destructive" onClick={removeNote} disabled={isPending}>
              <Trash2 />
              Delete note
            </Button>
          ) : null}
          <Button onClick={saveNote} disabled={!title.trim() || isPending}>
            <Save />
            Save note
          </Button>
        </div>
      </header>

      <div className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(280px,420px)]">
        <section className="grid gap-4 rounded-lg border bg-background p-4">
          <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">
            <Label htmlFor="note-body">Body</Label>
            <textarea
              id="note-body"
              aria-label="Body"
              className="min-h-80 w-full rounded-lg border border-input bg-transparent px-3 py-2 text-sm leading-6 outline-none transition-colors placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
              value={body}
              onChange={(event) => setBody(event.target.value)}
              placeholder="# Dinner ideas&#10;&#10;- Tacos&#10;- Soup"
            />
          </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-lg border bg-card p-4 text-card-foreground">
          <h2 className="mb-3 text-sm font-medium text-muted-foreground">Preview</h2>
          <MarkdownPreview markdown={body} />
        </aside>
      </div>
    </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);
}
