"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useCallback, useRef, useEffect } from "react";
import { useTranslations } from "next-intl";
import { Pencil, Check, X, Loader2 } from "lucide-react";
import { Input } from "../ui/input.js";
import { Textarea } from "../ui/textarea.js";
import { Button } from "../ui/button.js";
import { Alert, AlertDescription } from "../ui/alert.js";
import { CheckCircle2, AlertCircle } from "lucide-react";
import { useTeamUpdate } from "../../hooks/useTeamUpdate.js";
import { sel } from "../../lib/test/index.js";
import { cn } from "../../lib/utils/index.js";
function InlineEditableField({
  value,
  fieldType,
  teamId,
  placeholder,
  multiline = false,
  disabled = false,
  className,
  onSaveSuccess
}) {
  var _a;
  const t = useTranslations("teams");
  const [isEditing, setIsEditing] = useState(false);
  const [editValue, setEditValue] = useState(value || "");
  const [validationError, setValidationError] = useState(null);
  const [showSuccess, setShowSuccess] = useState(false);
  const inputRef = useRef(null);
  const textareaRef = useRef(null);
  const updateMutation = useTeamUpdate(teamId);
  useEffect(() => {
    if (isEditing) {
      const elementToFocus = multiline ? textareaRef.current : inputRef.current;
      if (elementToFocus) {
        elementToFocus.focus();
        elementToFocus.select();
      }
    }
  }, [isEditing, multiline]);
  useEffect(() => {
    if (!isEditing) {
      setEditValue(value || "");
    }
  }, [value, isEditing]);
  const handleEdit = useCallback(() => {
    setEditValue(value || "");
    setValidationError(null);
    setIsEditing(true);
  }, [value]);
  const handleCancel = useCallback(() => {
    setEditValue(value || "");
    setValidationError(null);
    setIsEditing(false);
  }, [value]);
  const handleSave = useCallback(async () => {
    if (fieldType === "name") {
      if (!editValue.trim()) {
        setValidationError(t("validation.nameRequired", { defaultValue: "Team name is required" }));
        return;
      }
      if (editValue.trim().length < 2) {
        setValidationError(
          t("validation.nameMinLength", {
            defaultValue: "Name must be at least 2 characters"
          })
        );
        return;
      }
      if (editValue.trim().length > 100) {
        setValidationError(
          t("validation.nameMaxLength", {
            defaultValue: "Name must be at most 100 characters"
          })
        );
        return;
      }
    }
    setValidationError(null);
    try {
      await updateMutation.mutateAsync(
        fieldType === "name" ? { name: editValue.trim() } : { description: editValue.trim() || null }
      );
      setIsEditing(false);
      setShowSuccess(true);
      setTimeout(() => setShowSuccess(false), 3e3);
      onSaveSuccess == null ? void 0 : onSaveSuccess();
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : t("editTeam.error");
      setValidationError(errorMessage);
    }
  }, [editValue, fieldType, updateMutation, onSaveSuccess, t, value]);
  const handleKeyDown = useCallback(
    (e) => {
      if (e.key === "Escape") {
        handleCancel();
      }
      if (e.key === "Enter" && !multiline) {
        e.preventDefault();
        handleSave();
      }
      if (e.key === "Enter" && multiline && (e.ctrlKey || e.metaKey)) {
        e.preventDefault();
        handleSave();
      }
    },
    [handleCancel, handleSave, multiline]
  );
  const isPending = updateMutation.isPending;
  const selectors = {
    value: fieldType === "name" ? "teams.edit.name.value" : "teams.edit.description.value",
    editIcon: fieldType === "name" ? "teams.edit.name.editIcon" : "teams.edit.description.editIcon",
    input: fieldType === "name" ? "teams.edit.name.input" : "teams.edit.description.textarea",
    saveIcon: fieldType === "name" ? "teams.edit.name.saveIcon" : "teams.edit.description.saveIcon",
    cancelIcon: fieldType === "name" ? "teams.edit.name.cancelIcon" : "teams.edit.description.cancelIcon",
    error: fieldType === "name" ? "teams.edit.name.error" : "teams.edit.description.error",
    success: fieldType === "name" ? "teams.edit.name.success" : "teams.edit.description.success"
  };
  if (!isEditing) {
    return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsxs("div", { className: cn("group flex items-center gap-2", className), children: [
        /* @__PURE__ */ jsx(
          "span",
          {
            "data-cy": sel(selectors.value),
            className: cn("flex-1", !value && "text-muted-foreground italic"),
            children: value || placeholder || t("editTeam.noValue", { defaultValue: "Not set" })
          }
        ),
        !disabled && /* @__PURE__ */ jsx(
          Button,
          {
            variant: "ghost",
            size: "icon",
            className: "h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity",
            onClick: handleEdit,
            "data-cy": sel(selectors.editIcon),
            "aria-label": t("editTeam.editField", {
              field: fieldType,
              defaultValue: `Edit ${fieldType}`
            }),
            children: /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" })
          }
        )
      ] }),
      showSuccess && /* @__PURE__ */ jsxs(
        Alert,
        {
          className: "bg-green-50 text-green-900 border-green-200",
          "data-cy": sel(selectors.success),
          role: "status",
          "aria-live": "polite",
          children: [
            /* @__PURE__ */ jsx(CheckCircle2, { className: "h-4 w-4 text-green-600", "aria-hidden": "true" }),
            /* @__PURE__ */ jsx(AlertDescription, { children: t("editTeam.success") })
          ]
        }
      )
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: cn("space-y-2", className), children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-2", children: [
      multiline ? /* @__PURE__ */ jsx(
        Textarea,
        {
          ref: textareaRef,
          value: editValue,
          onChange: (e) => setEditValue(e.target.value),
          onKeyDown: handleKeyDown,
          placeholder,
          disabled: isPending,
          className: "flex-1 min-h-[60px]",
          "data-cy": sel(selectors.input),
          "aria-invalid": !!(validationError || updateMutation.error),
          "aria-describedby": validationError || updateMutation.error ? `${fieldType}-error` : void 0
        }
      ) : /* @__PURE__ */ jsx(
        Input,
        {
          ref: inputRef,
          value: editValue,
          onChange: (e) => setEditValue(e.target.value),
          onKeyDown: handleKeyDown,
          placeholder,
          disabled: isPending,
          className: "flex-1",
          "data-cy": sel(selectors.input),
          "aria-invalid": !!(validationError || updateMutation.error),
          "aria-describedby": validationError || updateMutation.error ? `${fieldType}-error` : void 0
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
        /* @__PURE__ */ jsx(
          Button,
          {
            variant: "ghost",
            size: "icon",
            className: "h-8 w-8 text-green-600 hover:text-green-700 hover:bg-green-50",
            onClick: handleSave,
            disabled: isPending,
            "data-cy": sel(selectors.saveIcon),
            "aria-label": t("editTeam.save", { defaultValue: "Save" }),
            children: isPending ? /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsx(Check, { className: "h-4 w-4" })
          }
        ),
        /* @__PURE__ */ jsx(
          Button,
          {
            variant: "ghost",
            size: "icon",
            className: "h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",
            onClick: handleCancel,
            disabled: isPending,
            "data-cy": sel(selectors.cancelIcon),
            "aria-label": t("editTeam.cancel", { defaultValue: "Cancel" }),
            children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" })
          }
        )
      ] })
    ] }),
    (validationError || updateMutation.error) && /* @__PURE__ */ jsxs(
      Alert,
      {
        variant: "destructive",
        "data-cy": sel("teams.edit.error"),
        role: "alert",
        "aria-live": "assertive",
        children: [
          /* @__PURE__ */ jsx(AlertCircle, { className: "h-4 w-4", "aria-hidden": "true" }),
          /* @__PURE__ */ jsx(
            AlertDescription,
            {
              id: `${fieldType}-error`,
              "data-cy": sel(selectors.error),
              children: validationError || ((_a = updateMutation.error) == null ? void 0 : _a.message) || t("editTeam.error")
            }
          )
        ]
      }
    )
  ] });
}
export {
  InlineEditableField
};
