// lib/cms/ColorPickerField.tsx
'use client';

import { useState, useRef } from 'react';

interface ColorPickerFieldProps {
  value: string;
  onChange: (value: string) => void;
}

// AMSOIL brand palette
const BRAND_COLORS = [
  { label: 'Primary Blue', value: '#093b66' },
  { label: 'Accent Orange', value: '#f8981d' },
  { label: 'Black', value: '#000000' },
  { label: 'White', value: '#ffffff' },
  { label: 'Gray', value: '#757575' },
];

function isCustomColor(color: string | undefined): boolean {
  return Boolean(color && !BRAND_COLORS.some((c) => c.value === color));
}

export function ColorPickerField({ value, onChange }: ColorPickerFieldProps) {
  // Derive whether to show custom picker from the value itself
  const isCurrentValueCustom = isCustomColor(value);
  const [showCustomPicker, setShowCustomPicker] = useState(false);
  const [localCustomValue, setLocalCustomValue] = useState(value || '#000000');
  const inputRef = useRef<HTMLInputElement>(null);

  // Show custom picker if value is custom or user explicitly opened it
  const showCustom = isCurrentValueCustom || showCustomPicker;
  // Use value for display if it's custom, otherwise use local custom value
  const customValue = isCurrentValueCustom ? value : localCustomValue;

  const handleSwatchClick = (color: string) => {
    setShowCustomPicker(false);
    onChange(color);
  };

  const handleCustomChange = (hex: string) => {
    setLocalCustomValue(hex);
    // Only update if valid hex
    if (/^#[0-9A-Fa-f]{6}$/.test(hex)) {
      onChange(hex);
    }
  };

  const isSelected = (color: string) => value === color;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
      {/* Brand color swatches */}
      <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
        {BRAND_COLORS.map((color) => (
          <button
            key={color.value}
            type="button"
            onClick={() => handleSwatchClick(color.value)}
            title={color.label}
            style={{
              width: '32px',
              height: '32px',
              borderRadius: '4px',
              border: isSelected(color.value) ? '3px solid #093b66' : '1px solid #d1d5db',
              backgroundColor: color.value,
              cursor: 'pointer',
              outline: 'none',
              boxShadow: isSelected(color.value) ? '0 0 0 2px white, 0 0 0 4px #093b66' : 'none',
            }}
          />
        ))}
        {/* Custom color toggle */}
        <button
          type="button"
          onClick={() => {
            setShowCustomPicker(true);
            setTimeout(() => inputRef.current?.focus(), 0);
          }}
          title="Custom color"
          style={{
            width: '32px',
            height: '32px',
            borderRadius: '4px',
            border: showCustomPicker ? '3px solid #093b66' : '1px solid #d1d5db',
            background: 'linear-gradient(135deg, #ff0000 0%, #00ff00 50%, #0000ff 100%)',
            cursor: 'pointer',
            outline: 'none',
            boxShadow: showCustomPicker ? '0 0 0 2px white, 0 0 0 4px #093b66' : 'none',
          }}
        />
      </div>

      {/* Custom hex input */}
      {showCustom && (
        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
          <div
            style={{
              width: '24px',
              height: '24px',
              borderRadius: '4px',
              backgroundColor: customValue,
              border: '1px solid #d1d5db',
            }}
          />
          <input
            ref={inputRef}
            type="text"
            value={customValue}
            onChange={(e) => handleCustomChange(e.target.value)}
            placeholder="#000000"
            style={{
              padding: '0.25rem 0.5rem',
              border: '1px solid #d1d5db',
              borderRadius: '4px',
              fontSize: '0.875rem',
              fontFamily: 'monospace',
              width: '90px',
            }}
          />
          <input
            type="color"
            value={customValue}
            onChange={(e) => handleCustomChange(e.target.value)}
            style={{
              width: '32px',
              height: '32px',
              padding: 0,
              border: 'none',
              cursor: 'pointer',
            }}
          />
        </div>
      )}

      {/* Current value display */}
      <div style={{ fontSize: '0.75rem', color: '#757575' }}>Current: {value || 'none'}</div>
    </div>
  );
}
