"use client";

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

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useBoard } from "@/components/board/board-context";

const TITLE_MAX = 20;

export function TodoCreatePopover({
  groupId,
  categoryId,
}: {
  groupId: string;
  categoryId: string;
}) {
  const { addTodo } = useBoard();
  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"
          >
            <Plus className="size-3.5" />
            Add to-do
          </Button>
        }
      />
      <PopoverContent className="w-72" align="start">
        <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>
            <Textarea
              id={`todo-details-${groupId}`}
              value={details}
              onChange={(e) => setDetails(e.target.value)}
              rows={3}
            />
          </div>
          <Button type="submit" className="w-full" disabled={pending || !title.trim()}>
            {pending ? "Adding…" : "Add to-do"}
          </Button>
        </form>
      </PopoverContent>
    </Popover>
  );
}
