"use client";

import { useEffect, useRef, useState, useTransition } from "react";
import { Pencil } from "lucide-react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { renameBitacoraArchivoAction } from "@/server/actions/bitacora";

const FORBIDDEN_CHARS = /[/\\:*?"<>|]/;

export function BitacoraArchivoRenameDialog({
  archivoId,
  hitoId,
  nombreActual,
}: {
  archivoId: string;
  hitoId: string;
  nombreActual: string;
}) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [nombre, setNombre] = useState(nombreActual);
  const [clientError, setClientError] = useState<string | null>(null);
  const [pending, startTransition] = useTransition();
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (open) {
      setNombre(nombreActual);
      setClientError(null);
      setTimeout(() => inputRef.current?.select(), 50);
    }
  }, [open, nombreActual]);

  function validate(value: string): string | null {
    const trimmed = value.trim();
    if (!trimmed) return "El nombre no puede quedar vacío.";
    if (FORBIDDEN_CHARS.test(trimmed)) return 'Caracteres no permitidos: / \\ : * ? " < > |';
    return null;
  }

  function handleChange(value: string) {
    setNombre(value);
    setClientError(validate(value));
  }

  function handleSave() {
    const error = validate(nombre);
    if (error) {
      setClientError(error);
      return;
    }

    startTransition(() => {
      void renameBitacoraArchivoAction(archivoId, hitoId, nombre)
        .then((result) => {
          if (!result.ok) {
            toast.error(result.message);
            return;
          }
          toast.success(result.message);
          setOpen(false);
          router.refresh();
        })
        .catch((err: unknown) => {
          toast.error(err instanceof Error ? err.message : "No fue posible renombrar el archivo.");
        });
    });
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button
          size="icon"
          variant="ghost"
          className="h-8 w-8"
          title="Renombrar archivo"
          aria-label="Renombrar archivo"
        >
          <Pencil className="h-4 w-4" />
        </Button>
      </DialogTrigger>

      <DialogContent>
        <DialogHeader>
          <DialogTitle>Renombrar archivo</DialogTitle>
          <DialogDescription>
            Edita el nombre visible del documento. El archivo físico no se modifica ni se pierde la descarga.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-2 py-2">
          <Label htmlFor="rename-input">Nuevo nombre</Label>
          <Input
            id="rename-input"
            ref={inputRef}
            value={nombre}
            onChange={(e) => handleChange(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter" && !pending) handleSave();
              if (e.key === "Escape") setOpen(false);
            }}
            disabled={pending}
            autoComplete="off"
            spellCheck={false}
          />
          {clientError ? (
            <p className="text-xs text-destructive">{clientError}</p>
          ) : null}
          <p className="text-xs text-muted-foreground">
            La extensión original se conservará automáticamente.
          </p>
        </div>

        <DialogFooter className="flex-col gap-2 sm:flex-row sm:justify-end">
          <Button
            type="button"
            variant="outline"
            onClick={() => setOpen(false)}
            disabled={pending}
          >
            Cancelar
          </Button>
          <Button
            type="button"
            onClick={handleSave}
            disabled={pending || !!clientError || !nombre.trim()}
          >
            {pending ? "Guardando..." : "Guardar"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
