"use client";

import { useState } from "react";
import { Plus } from "lucide-react";

import { Button } from "@/components/ui/button";
import { colorModeFromTheme } from "@/components/theme/use-dark-theme";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { MDEditor } from "@/components/markdown/markdown-widgets";
import { useBoard } from "@/components/board/board-context";

const TITLE_MAX = 20;

export function TodoCreatePopover({
  groupId,
  categoryId,
}: {
  groupId: string;
  categoryId: string;
}) {
  const { addTodo } = useBoard();
  const colorMode = colorModeFromTheme();

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

  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) {
      setTitle("");
      setDetails("");
      setOpen(false);
    }
  }

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger
        render={
          <Button
            variant="ghost"
            size="sm"
            className="w-full justify-start gap-2 text-muted-foreground/90 hover:text-foreground"
          >
            <Plus className="size-3.5" />
            Add to-do
          </Button>
        }
      />
      <PopoverContent className="w-96" align="start" data-color-mode={colorMode}>
        <form onSubmit={handleSubmit} className="space-y-3">
          <div className="space-y-2">
            <Label htmlFor={`todo-title-${groupId}`}>Title</Label>
            <Input
              id={`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={`todo-details-${groupId}`}>Details (optional)</Label>
            <MDEditor
              value={details}
              onChange={(v) => setDetails(v ?? "")}
              height={160}
              textareaProps={{ id: `todo-details-${groupId}` }}
            />
          </div>
          <Button type="submit" className="w-full" disabled={pending || !title.trim()}>
            {pending ? "Adding…" : "Add to-do"}
          </Button>
        </form>
      </PopoverContent>
    </Popover>
  );
}
