import { useState, useRef, useEffect } from "react";
import { Input } from "@/components/ui/input";
import { Copy } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";

export function EditableInput({
  value,
  onChange,
  onBlur,
  name,
  label,
  placeholder,
  className,
  inputClassName,
  maxLength,
  copyable,
  alwaysShowCopy,
  formatDisplay,
  rightAction,
}: {
  value: string;
  onChange: (val: string) => void;
  onBlur?: () => void;
  name?: string;
  label?: string;
  placeholder?: string;
  className?: string;
  inputClassName?: string;
  maxLength?: number;
  copyable?: boolean;
  alwaysShowCopy?: boolean;
  formatDisplay?: (val: string) => string;
  rightAction?: React.ReactNode;
}) {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (editing) {
      inputRef.current?.focus();
    }
  }, [editing]);

  if (editing) {
    return (
      <div
        className={cn(
          "flex h-auto items-center gap-1.5 rounded-md border border-muted-foreground/50 bg-transparent px-3 py-1 text-sm",
          className,
        )}
      >
        {label && (
          <span className="text-muted-foreground shrink-0">{label}</span>
        )}
        <Input
          ref={inputRef}
          name={name}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onBlur={() => {
            setEditing(false);
            onBlur?.();
          }}
          onKeyDown={(e) => {
            if (e.key === "Escape" || e.key === "Enter") {
              setEditing(false);
            }
          }}
          placeholder={placeholder}
          maxLength={maxLength}
          size={Math.max((value?.length || placeholder?.length || 1) + 1, 3)}
          className={cn("border-0 p-0 h-auto shadow-none focus-visible:ring-0 w-auto min-w-0", inputClassName)}
        />
      </div>
    );
  }

  return (
    <div
      className={cn(
        "flex h-auto items-center gap-1.5 rounded-md border border-muted-foreground/50 bg-transparent px-3 py-1 text-sm text-left",
        "hover:border-input hover:bg-muted/50 transition-colors group",
        className,
      )}
    >
      <button
        type="button"
        onClick={() => setEditing(true)}
        onFocus={() => setEditing(true)}
        className="flex items-center gap-1.5 flex-1 min-w-0"
      >
        {label && (
          <span className="text-muted-foreground text-xs shrink-0">{label}</span>
        )}
        <span className={cn("truncate", !value && "text-muted-foreground")}>
          {value ? (formatDisplay ? formatDisplay(value) : value) : placeholder}
        </span>
      </button>
      {copyable && value && (
        <button
          type="button"
          onClick={() => {
            navigator.clipboard.writeText(value);
            toast.success(`Copied ${label ?? "value"}`);
          }}
          className={cn("shrink-0 transition-opacity", alwaysShowCopy ? "opacity-50 hover:opacity-100" : "opacity-0 group-hover:opacity-50 hover:!opacity-100")}
        >
          <Copy className="h-3 w-3" />
        </button>
      )}
      {rightAction}
    </div>
  );
}
