import { Input } from '@/components/ui/input';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';
import { EyedropperIcon } from '@phosphor-icons/react';
import { useRef, useState } from 'react';

const PRESETS = [
  '#ef4444',
  '#f97316',
  '#eab308',
  '#22c55e',
  '#10b981',
  '#06b6d4',
  '#3b82f6',
  '#6366f1',
  '#a855f7',
  '#ec4899',
  '#dc2626',
  '#ea580c',
  '#16a34a',
  '#0284c7',
  '#7c3aed',
];

const HEX_RE = /^#[0-9a-fA-F]{6}$/;

export function ColorPicker({
  value,
  onChange,
  className,
}: {
  value: string;
  onChange: (color: string) => void;
  className?: string;
}) {
  const nativeRef = useRef<HTMLInputElement>(null);

  const [hexInput, setHexInput] = useState(value);
  const [prevValue, setPrevValue] = useState(value);

  if (prevValue !== value) {
    setPrevValue(value);
    setHexInput(value);
  }

  const handleHexChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const raw = e.target.value;
    const normalised = raw.startsWith('#') ? raw : `#${raw}`;
    setHexInput(raw);
    if (HEX_RE.test(normalised)) {
      onChange(normalised);
    }
  };

  return (
    <Popover>
      <PopoverTrigger asChild>
        <button
          type="button"
          className={cn(
            'h-9 w-10 shrink-0 cursor-pointer rounded-md border border-black/10 p-1 outline-3 outline-black/80 transition-transform',
            className,
          )}
          style={{ backgroundColor: value }}
        />
      </PopoverTrigger>

      <PopoverContent className="w-52 space-y-3 p-3" align="start">
        <div className="grid grid-cols-5 gap-1.5">
          {PRESETS.map((color) => (
            <button
              key={color}
              type="button"
              title={color}
              onClick={() => onChange(color)}
              className={cn(
                'h-7 w-full cursor-pointer rounded-md border-2 transition-transform',
                value.toLowerCase() === color.toLowerCase()
                  ? 'border-foreground shadow-sm'
                  : 'border-transparent',
              )}
              style={{ backgroundColor: color }}
            />
          ))}
        </div>

        <Separator />

        <div className="flex items-center gap-2">
          <Input
            value={hexInput}
            onChange={handleHexChange}
            maxLength={7}
            placeholder="#000000"
            className="h-8 font-mono text-xs"
          />
          <button
            type="button"
            title="Custom colour"
            onClick={() => nativeRef.current?.click()}
            className="relative flex h-8 w-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-black/10 bg-black/5 transition-colors hover:bg-black/10"
          >
            <EyedropperIcon weight="bold" className="size-4" />
            <input
              ref={nativeRef}
              type="color"
              value={value}
              onChange={(e) => onChange(e.target.value)}
              className="pointer-events-none absolute inset-0 h-full w-full opacity-0"
            />
          </button>
        </div>
      </PopoverContent>
    </Popover>
  );
}
