"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 { useProjects } from "@/components/projects/projects-context";
import type { ProjectDTO } from "@/types/project";

const TITLE_MAX = 60;

export function RenameProjectDialog({
  project,
  open,
  onOpenChange,
}: {
  project: ProjectDTO;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const { renameProject } = useProjects();
  const [title, setTitle] = useState(project.title);
  const [pending, setPending] = useState(false);

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

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

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Rename project</DialogTitle>
        </DialogHeader>
        <div className="space-y-2">
          <Label htmlFor={`rename-project-${project.id}`}>Title</Label>
          <Input
            id={`rename-project-${project.id}`}
            value={title}
            maxLength={TITLE_MAX}
            autoFocus
            onChange={(e) => setTitle(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleSave()}
          />
        </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>
  );
}
