import React, { useState, useRef, useEffect } from 'react';
import { Input } from './input';
import { Button } from './button';
import { Popover, PopoverContent, PopoverTrigger } from './popover';
import { cn } from '@/lib/utils';

interface ColorPickerProps {
  value: string;
  onChange: (color: string) => void;
  label?: string;
  description?: string;
  presets?: string[];
  className?: string;
}

const DEFAULT_PRESETS = [
  '#3b82f6', // blue
  '#8b5cf6', // purple
  '#10b981', // green
  '#f59e0b', // amber
  '#ef4444', // red
  '#ec4899', // pink
  '#06b6d4', // cyan
  '#6366f1', // indigo
];

export function ColorPicker({
  value,
  onChange,
  label,
  description,
  presets = DEFAULT_PRESETS,
  className,
}: ColorPickerProps) {
  const [inputValue, setInputValue] = useState(value);
  const [open, setOpen] = useState(false);
  const colorInputRef = useRef<HTMLInputElement>(null);

  // Sync input value when prop changes
  useEffect(() => {
    setInputValue(value);
  }, [value]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = e.target.value;
    setInputValue(newValue);
    
    // Only update if valid hex color
    if (/^#[0-9A-F]{6}$/i.test(newValue)) {
      onChange(newValue);
    }
  };

  const handleInputBlur = () => {
    // Validate and fix format on blur
    let color = inputValue.trim();
    
    // Add # if missing
    if (!color.startsWith('#')) {
      color = '#' + color;
    }
    
    // Validate hex format
    if (/^#[0-9A-F]{6}$/i.test(color)) {
      setInputValue(color);
      onChange(color);
    } else {
      // Revert to last valid value
      setInputValue(value);
    }
  };

  const handleColorInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newColor = e.target.value;
    setInputValue(newColor);
    onChange(newColor);
  };

  const handlePresetClick = (color: string) => {
    setInputValue(color);
    onChange(color);
    setOpen(false);
  };

  return (
    <div className={cn('space-y-2', className)}>
      {label && (
        <label className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
          {label}
        </label>
      )}
      
      {description && (
        <p className="text-sm text-muted-foreground">{description}</p>
      )}

      <div className="flex gap-2">
        {/* Color preview and picker */}
        <Popover open={open} onOpenChange={setOpen}>
          <PopoverTrigger asChild>
            <Button
              type="button"
              variant="outline"
              className="w-12 h-10 p-0 border-2"
              style={{ backgroundColor: value }}
            >
              <span className="sr-only">Pick color</span>
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-64 p-4" align="start">
            <div className="space-y-4">
              {/* Native color picker */}
              <div>
                <label className="text-sm font-medium mb-2 block">
                  Pick a color
                </label>
                <input
                  ref={colorInputRef}
                  type="color"
                  value={value}
                  onChange={handleColorInputChange}
                  className="w-full h-10 rounded cursor-pointer"
                />
              </div>

              {/* Preset colors */}
              {presets.length > 0 && (
                <div>
                  <label className="text-sm font-medium mb-2 block">
                    Presets
                  </label>
                  <div className="grid grid-cols-4 gap-2">
                    {presets.map((preset) => (
                      <button
                        key={preset}
                        type="button"
                        className={cn(
                          'w-full h-10 rounded border-2 transition-all',
                          value === preset
                            ? 'border-primary ring-2 ring-primary/20'
                            : 'border-transparent hover:border-muted-foreground/25'
                        )}
                        style={{ backgroundColor: preset }}
                        onClick={() => handlePresetClick(preset)}
                        title={preset}
                      />
                    ))}
                  </div>
                </div>
              )}
            </div>
          </PopoverContent>
        </Popover>

        {/* Hex input */}
        <Input
          type="text"
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputBlur}
          placeholder="#3b82f6"
          className="flex-1 font-mono"
          maxLength={7}
        />
      </div>
    </div>
  );
}
