'use client';

import { useState, useRef, useEffect } from 'react';
import { hexToRgb, rgbToHsv, hsvToRgb, rgbToHex, isValidHex, normalizeHex } from '@/lib/color-utils';

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

export function ColorPicker({ color, onChange }: ColorPickerProps) {
  const svPickerRef = useRef<HTMLDivElement>(null);
  const huePickerRef = useRef<HTMLDivElement>(null);

  const rgb = hexToRgb(color);
  const hsv = rgbToHsv(rgb.r, rgb.g, rgb.b);

  const [hue, setHue] = useState(hsv.h);
  const [saturation, setSaturation] = useState(hsv.s);
  const [value, setValue] = useState(hsv.v);
  const [hexInput, setHexInput] = useState(color);

  const [isDraggingSV, setIsDraggingSV] = useState(false);
  const [isDraggingHue, setIsDraggingHue] = useState(false);

  useEffect(() => {
    const rgb = hexToRgb(color);
    const hsv = rgbToHsv(rgb.r, rgb.g, rgb.b);
    setHue(hsv.h);
    setSaturation(hsv.s);
    setValue(hsv.v);
    setHexInput(color);
  }, [color]);

  const updateColor = (h: number, s: number, v: number) => {
    const rgb = hsvToRgb(h, s, v);
    const hex = rgbToHex(rgb.r, rgb.g, rgb.b);
    onChange(hex);
  };

  const handleSVPointerDown = (e: React.PointerEvent) => {
    setIsDraggingSV(true);
    handleSVMove(e);
  };

  const handleSVMove = (e: React.PointerEvent) => {
    if (!svPickerRef.current) return;

    const rect = svPickerRef.current.getBoundingClientRect();
    const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width));
    const y = Math.max(0, Math.min(e.clientY - rect.top, rect.height));

    const newS = (x / rect.width) * 100;
    const newV = 100 - (y / rect.height) * 100;

    setSaturation(newS);
    setValue(newV);
    updateColor(hue, newS, newV);
  };

  const handleHuePointerDown = (e: React.PointerEvent) => {
    setIsDraggingHue(true);
    handleHueMove(e);
  };

  const handleHueMove = (e: React.PointerEvent) => {
    if (!huePickerRef.current) return;

    const rect = huePickerRef.current.getBoundingClientRect();
    const y = Math.max(0, Math.min(e.clientY - rect.top, rect.height));
    const newH = (y / rect.height) * 360;

    setHue(newH);
    updateColor(newH, saturation, value);
  };

  const handlePointerMove = (e: React.PointerEvent) => {
    if (isDraggingSV) handleSVMove(e);
    if (isDraggingHue) handleHueMove(e);
  };

  const handlePointerUp = () => {
    setIsDraggingSV(false);
    setIsDraggingHue(false);
  };

  const handleHexChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setHexInput(value);

    if (isValidHex(value)) {
      const normalized = normalizeHex(value);
      const rgb = hexToRgb(normalized);
      const hsv = rgbToHsv(rgb.r, rgb.g, rgb.b);
      setHue(hsv.h);
      setSaturation(hsv.s);
      setValue(hsv.v);
      onChange(normalized);
    }
  };

  const hueBackground = `linear-gradient(to bottom,
    #ff0000 0%,
    #ffff00 17%,
    #00ff00 33%,
    #00ffff 50%,
    #0000ff 67%,
    #ff00ff 83%,
    #ff0000 100%)`;

  const hueColor = hsvToRgb(hue, 100, 100);
  const hueHex = rgbToHex(hueColor.r, hueColor.g, hueColor.b);

  return (
    <div
      className="space-y-3"
      onPointerMove={handlePointerMove}
      onPointerUp={handlePointerUp}
      onPointerLeave={handlePointerUp}
    >
      {/* Saturation/Value picker */}
      <div className="flex gap-3">
        <div
          ref={svPickerRef}
          className="relative h-40 w-full rounded-md cursor-crosshair"
          style={{
            background: `
              linear-gradient(to top, #000, transparent),
              linear-gradient(to right, #fff, ${hueHex})
            `,
          }}
          onPointerDown={handleSVPointerDown}
        >
          <div
            className="absolute w-4 h-4 border-2 border-white rounded-full shadow-lg pointer-events-none"
            style={{
              left: `${saturation}%`,
              top: `${100 - value}%`,
              transform: 'translate(-50%, -50%)',
            }}
          />
        </div>

        {/* Hue picker */}
        <div
          ref={huePickerRef}
          className="relative w-6 h-40 rounded-md cursor-pointer"
          style={{ background: hueBackground }}
          onPointerDown={handleHuePointerDown}
        >
          <div
            className="absolute left-0 right-0 h-1 border-2 border-white shadow-lg pointer-events-none"
            style={{
              top: `${(hue / 360) * 100}%`,
              transform: 'translateY(-50%)',
            }}
          />
        </div>
      </div>

      {/* Hex input */}
      <div className="space-y-1">
        <label className="text-xs font-medium text-muted-foreground">Hex</label>
        <input
          type="text"
          value={hexInput}
          onChange={handleHexChange}
          className="w-full px-3 py-1.5 text-sm font-mono rounded-md border border-border bg-background text-foreground uppercase"
          placeholder="#000000"
        />
      </div>

      {/* RGB display */}
      <div className="grid grid-cols-3 gap-2 text-xs">
        <div>
          <span className="text-muted-foreground">R:</span>{' '}
          <span className="font-mono">{rgb.r}</span>
        </div>
        <div>
          <span className="text-muted-foreground">G:</span>{' '}
          <span className="font-mono">{rgb.g}</span>
        </div>
        <div>
          <span className="text-muted-foreground">B:</span>{' '}
          <span className="font-mono">{rgb.b}</span>
        </div>
      </div>
    </div>
  );
}
