'use client';

import { ReactNode, useCallback, useState } from 'react';
import { Check, Copy } from 'lucide-react';
import { cn } from '@/lib/utils';

interface CopyableCellProps {
  /** 복사할 텍스트 값 */
  value: string;
  /** 셀에 표시할 내용 (기본: value) */
  children?: ReactNode;
  /** 추가 클래스 */
  className?: string;
}

/**
 * 테이블 셀 내 텍스트에 hover 시 복사 버튼을 표시하는 래퍼
 *
 * 사용법:
 * ```tsx
 * <TableCell>
 *   <CopyableCell value={item.itemCode}>{item.itemCode}</CopyableCell>
 * </TableCell>
 * ```
 */
export function CopyableCell({ value, children, className }: CopyableCellProps) {
  const [copied, setCopied] = useState(false);

  const handleCopy = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    e.preventDefault();
    navigator.clipboard.writeText(value).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    });
  }, [value]);

  return (
    <span className={cn('group/copy relative block max-w-full overflow-hidden', className)}>
      <span className="block truncate">{children ?? value}</span>
      <button
        type="button"
        onClick={handleCopy}
        className={cn(
          'absolute right-0 top-1/2 -translate-y-1/2',
          'opacity-0 group-hover/copy:opacity-100 transition-opacity',
          'pl-4 pr-0.5 py-0.5',
          'bg-gradient-to-l from-background via-background to-transparent',
          copied && 'opacity-100',
        )}
        title="복사"
      >
        {copied ? (
          <Check className="h-3.5 w-3.5 text-green-500" />
        ) : (
          <Copy className="h-3.5 w-3.5 text-muted-foreground hover:text-foreground" />
        )}
      </button>
    </span>
  );
}
