'use client';

import { HexColorPicker } from 'react-colorful';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
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 handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    // Allow partial input while typing
    onChange(value);
  };

  // Determine text color based on background brightness
  const getContrastColor = (hex: string) => {
    const rgb = hexToRgb(hex);
    if (!rgb) return 'inherit';
    const brightness = (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
    return brightness > 128 ? '#000000' : '#ffffff';
  };

  const textColor = getContrastColor(color);

  return (
    <div className={cn('flex flex-col items-center justify-center space-y-3', className)}>
      <div className="w-full max-w-[200px] space-y-3">
        <HexColorPicker color={color} onChange={onChange} className="!w-full" />
        <div className="space-y-1.5">
          <Label htmlFor="color-input" className="text-xs">
            Hex Value
          </Label>
          <Input
            id="color-input"
            type="text"
            value={color}
            onChange={handleInputChange}
            placeholder="#ff0099"
            className="font-mono text-xs transition-colors duration-200"
            style={{
              backgroundColor: color,
              color: textColor,
              borderColor: textColor === '#000000' ? 'rgba(0,0,0,0.1)' : 'rgba(255,255,255,0.2)'
            }}
          />
        </div>
      </div>
    </div>
  );
}
