"use client";

import dynamic from "next/dynamic";
import { useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { createNote } from "@/modules/notes/server/actions";

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

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
};

export function NoteCreateDialog({ open, onOpenChange }: Props) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-2xl">
        {open ? <NoteCreateForm onDone={() => onOpenChange(false)} /> : null}
      </DialogContent>
    </Dialog>
  );
}

function NoteCreateForm({ onDone }: { onDone: () => void }) {
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");
  const [remindAt, setRemindAt] = useState("");
  const [isPending, startTransition] = useTransition();

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!title.trim()) return;
    startTransition(async () => {
      await createNote({
        title: title.trim(),
        body,
        remindAt: remindAt ? new Date(remindAt) : null,
      });
      onDone();
    });
  }

  return (
    <>
      <DialogHeader>
        <DialogTitle>New note</DialogTitle>
      </DialogHeader>
      <form id="quick-add-note-form" onSubmit={handleSubmit} className="grid gap-3">
        <div className="space-y-1.5">
          <Label htmlFor="qa-note-title">Title</Label>
          <Input
            id="qa-note-title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
          />
        </div>
        <div className="space-y-1.5 min-w-0">
          <Label htmlFor="qa-note-body">Body</Label>
          <RichTextEditor
            id="qa-note-body"
            aria-label="Body"
            value={body}
            onChange={setBody}
            disabled={isPending}
            placeholder="Start writing…"
          />
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="qa-note-reminder">Reminder</Label>
          <Input
            id="qa-note-reminder"
            type="datetime-local"
            value={remindAt}
            onChange={(e) => setRemindAt(e.target.value)}
          />
        </div>
      </form>
      <DialogFooter>
        <Button type="submit" form="quick-add-note-form" disabled={!title.trim() || isPending}>
          Save note
        </Button>
      </DialogFooter>
    </>
  );
}
