"use client";

import { useState } from "react";

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 { useBoard } from "@/components/board/board-context";
import type { GroupDTO } from "@/types/board";

const TITLE_MAX = 20;

export function EditGroupDialog({
  group,
  open,
  onOpenChange,
}: {
  group: GroupDTO;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const { editGroup } = useBoard();
  const [title, setTitle] = useState(group.title);
  const [pending, setPending] = useState(false);

  function handleOpenChange(next: boolean) {
    if (next) setTitle(group.title);
    onOpenChange(next);
  }

  async function handleSave() {
    const trimmed = title.trim();
    if (!trimmed) return;
    setPending(true);
    await editGroup(group.id, group.categoryId, { title: trimmed });
    setPending(false);
    onOpenChange(false);
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Rename group</DialogTitle>
        </DialogHeader>
        <div className="space-y-2">
          <Label htmlFor={`edit-group-title-${group.id}`}>Title</Label>
          <Input
            id={`edit-group-title-${group.id}`}
            value={title}
            maxLength={TITLE_MAX}
            autoFocus
            onChange={(e) => setTitle(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleSave()}
          />
          <p className="text-right text-xs text-muted-foreground">
            {title.length}/{TITLE_MAX}
          </p>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={pending}>
            Cancel
          </Button>
          <Button onClick={handleSave} disabled={pending || !title.trim()}>
            {pending ? "Saving…" : "Save"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
