"use client";

import { useState } from "react";
import { useTheme } from "next-themes";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { MDEditor } from "@/components/markdown/markdown-widgets";
import { useBoard } from "@/components/board/board-context";

const TITLE_MAX = 20;

// Same fields and `addTodo` call as TodoCreatePopover's inline form, but as
// a controlled Dialog instead of owning its own popover trigger -- this is
// opened from the compact view's "+" dropdown menu rather than from an
// inline "+ Add to-do" button.
export function TodoCreateDialog({
  groupId,
  categoryId,
  open,
  onOpenChange,
}: {
  groupId: string;
  categoryId: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const { addTodo } = useBoard();
  const { resolvedTheme } = useTheme();
  const colorMode = resolvedTheme === "dark" ? "dark" : "light";

  const [title, setTitle] = useState("");
  const [details, setDetails] = useState("");
  const [pending, setPending] = useState(false);

  function handleOpenChange(next: boolean) {
    if (!next) {
      setTitle("");
      setDetails("");
    }
    onOpenChange(next);
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const trimmed = title.trim();
    if (!trimmed) return;
    setPending(true);
    const ok = await addTodo(groupId, categoryId, trimmed, details.trim() || undefined);
    setPending(false);
    if (ok) handleOpenChange(false);
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-lg" data-color-mode={colorMode}>
        <DialogHeader>
          <DialogTitle>Add to-do</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor={`create-todo-title-${groupId}`}>Title</Label>
            <Input
              id={`create-todo-title-${groupId}`}
              value={title}
              maxLength={TITLE_MAX}
              autoFocus
              onChange={(e) => setTitle(e.target.value)}
              placeholder="e.g. Buy milk"
            />
            <p className="text-right text-xs text-muted-foreground">
              {title.length}/{TITLE_MAX}
            </p>
          </div>
          <div className="space-y-2">
            <Label htmlFor={`create-todo-details-${groupId}`}>Details (optional)</Label>
            <MDEditor
              value={details}
              onChange={(v) => setDetails(v ?? "")}
              height={160}
              textareaProps={{ id: `create-todo-details-${groupId}` }}
            />
          </div>
          <DialogFooter>
            <Button type="submit" disabled={pending || !title.trim()}>
              {pending ? "Adding…" : "Add to-do"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
