import { useState } from "react";
import { HexColorPicker } from "react-colorful";
import "./ColorPicker.css";

const ColorPicker = ({ color, onChange, label }) => {
  const [showPicker, setShowPicker] = useState(false);

  return (
    <div className="color-picker-container">
      <div className="color-input-wrapper">
        <input
          type="text"
          value={color || ""}
          onChange={(e) => {
            let newColor = e.target.value;
            newColor = "#" + newColor.replace(/[^0123456789abcdefABCDEF]/g, "");
            if (newColor[0] == "#" && newColor.length > 7) {
              newColor = newColor.substring(0, 7);
            }
            if (newColor[0] != "#" && newColor.length > 6) {
              newColor = newColor.substring(0, 6);
            }
            onChange(newColor);
          }}
          className="form-input color-input"
          placeholder="#000000"
        />
        <div
          className="color-preview"
          style={{ backgroundColor: color || "#ffffff" }}
          onClick={() => setShowPicker(!showPicker)}
        />
      </div>
      {showPicker && (
        <div className="color-picker-popup">
          <div
            className="color-picker-overlay"
            onClick={() => setShowPicker(false)}
          />
          <HexColorPicker
            color={color}
            onChange={(newColor) => onChange(newColor)}
          />
        </div>
      )}
    </div>
  );
};

export default ColorPicker;
