'use client';

import { HexColorPicker } from 'react-colorful';
import { cn } from '@/lib/utils/cn';
import { hexToRgb } from '@/lib/color/utils/color';

interface ColorPickerProps {
  color: string;
  onChange: (color: string) => void;
  className?: string;
}

export function ColorPicker({ color, onChange, className }: ColorPickerProps) {
  const rgb = hexToRgb(color);
  const brightness = rgb ? (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000 : 0;
  const textColor = brightness > 128 ? '#000000' : '#ffffff';
  const borderColor = brightness > 128 ? 'rgba(0,0,0,0.12)' : 'rgba(255,255,255,0.2)';

  return (
    <div className={cn('flex flex-col gap-3', className)}>
      <HexColorPicker color={color} onChange={onChange} className="!w-full" />
      <input
        type="text"
        value={color}
        onChange={(e) => onChange(e.target.value)}
        placeholder="#ff0099"
        className="w-full font-mono text-xs rounded-lg px-3 py-2 outline-none transition-colors duration-200 border"
        style={{ backgroundColor: color, color: textColor, borderColor }}
        spellCheck={false}
      />
    </div>
  );
}
