"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 { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { ColorSwatchPicker } from "@/components/board/color-swatch-picker";
import { useBoard } from "@/components/board/board-context";
import { useBoardView } from "@/components/board/board-view-provider";
import { NEW_GROUP_HOLD_MS, useHoldOnComplete } from "@/components/hold-on-complete";
import { DEFAULT_GROUP_COLOR_KEY, type GroupColorKey } from "@/lib/colors";

const TITLE_MAX = 20;

export function AddGroupPopover({ categoryId }: { categoryId: string }) {
  const { addGroup } = useBoard();
  const { view } = useBoardView();
  const { beginHold } = useHoldOnComplete();
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState("");
  const [color, setColor] = useState<GroupColorKey>(DEFAULT_GROUP_COLOR_KEY);
  const [pending, setPending] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const trimmed = title.trim();
    if (!trimmed) return;
    setPending(true);
    const group = await addGroup(categoryId, trimmed, color);
    setPending(false);
    if (group) {
      if (view === "compact") beginHold(group.id, NEW_GROUP_HOLD_MS);
      setTitle("");
      setColor(DEFAULT_GROUP_COLOR_KEY);
      setOpen(false);
    }
  }

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger
        render={
          <Button
            variant="ghost"
            className="w-full justify-start gap-2 rounded-lg text-muted-foreground/90 hover:text-foreground"
          >
            <Plus className="size-4" />
            Group
          </Button>
        }
      />
      <PopoverContent className="w-72" align="start">
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor={`group-title-${categoryId}`}>Title</Label>
            <Input
              id={`group-title-${categoryId}`}
              value={title}
              maxLength={TITLE_MAX}
              autoFocus
              onChange={(e) => setTitle(e.target.value)}
              placeholder="e.g. Groceries"
            />
            <p className="text-right text-xs text-muted-foreground">
              {title.length}/{TITLE_MAX}
            </p>
          </div>
          <div className="space-y-2">
            <Label>Color</Label>
            <ColorSwatchPicker value={color} onChange={setColor} />
          </div>
          <Button type="submit" className="w-full" disabled={pending || !title.trim()}>
            {pending ? "Creating…" : "Create group"}
          </Button>
        </form>
      </PopoverContent>
    </Popover>
  );
}
