import React, { useState } from 'react';
import { Copy, Check } from 'lucide-react';
import type { ReactNode } from 'react';

interface KeyValueItem {
  key: string;
  value: ReactNode;
  copyable?: boolean;
}

interface KeyValueListProps {
  items: KeyValueItem[];
  layout?: 'horizontal' | 'vertical';
  className?: string;
}

export default function KeyValueList({ 
  items, 
  layout = 'horizontal', 
  className = '' 
}: KeyValueListProps) {
  return (
    <div className={`space-y-2 ${className}`}>
      {items.map((item, idx) => (
        <KeyValueRow key={`${item.key}-${idx}`} item={item} layout={layout} />
      ))}
    </div>
  );
}

function KeyValueRow({ item, layout }: { item: KeyValueItem; layout: 'horizontal' | 'vertical' }) {
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    if (typeof item.value === 'string') {
      await navigator.clipboard.writeText(item.value);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const containerClasses = layout === 'horizontal' 
    ? 'grid grid-cols-[auto_1fr] gap-2 items-center' 
    : 'flex flex-col gap-1';

  const keyClasses = layout === 'horizontal' 
    ? 'text-muted-foreground font-medium' 
    : 'text-xs uppercase tracking-wider text-muted-foreground font-semibold';

  return (
    <div className={containerClasses}>
      <span className={keyClasses}>{item.key}</span>
      <div className="flex items-center gap-2">
        <span className="text-foreground">{item.value}</span>
        {item.copyable && typeof item.value === 'string' && (
          <button 
            onClick={handleCopy}
            className="p-1 hover:bg-accent rounded transition-colors text-muted-foreground hover:text-foreground"
            title="Copy to clipboard"
          >
            {copied ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
          </button>
        )}
      </div>
    </div>
  );
}