import React, {
  useEffect,
  useState,
} from 'react';

import {
  ChevronsUpDown,
  XIcon,
} from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
  ColorPicker,
  ColorPickerArea,
  ColorPickerContent,
  ColorPickerEyeDropper,
  ColorPickerHueSlider,
  ColorPickerInput,
  ColorPickerSwatch,
  ColorPickerTrigger,
} from '@/components/ui/color-picker';
import { Lang } from '@/lang/Lang';

import DataDescription from './components/DataDescription';
import DataLabel from './components/DataLabel';
import { ItemDataProps } from './types';

export const ColorData = (props: ItemDataProps) => {



  const [localValue, setLocalValue] = useState(props.getValue());

  useEffect(() => {
    props.setValue(localValue);
  }, [localValue]);

  const [isOpen, setIsOpen] = useState(false);

  if (props.onlyShow || !props.structure.editable) {
    return <div>
      <DataLabel {...props} />
      <div className="flex items-center gap-3 w-full">
        <div
          style={{ backgroundColor: localValue }}
          className="w-full h-10 bg-gray-200 rounded-md"></div>
      </div>
      <DataDescription {...props} />
    </div>
  }


  return (
    <React.Fragment>
      <DataLabel {...props} />

      <div className="flex items-center gap-3 w-full">
        <ColorPicker
          value={localValue}
          onValueChange={setLocalValue}
          open={isOpen}
          onOpenChange={setIsOpen}
          className="w-full"
        >
          <ColorPickerTrigger asChild>
            <Button variant="outline" className="flex items-center gap-2 w-full">
              <ColorPickerSwatch className="size-4" />
              {!localValue ? Lang.key('pick_color') : localValue}
              <ChevronsUpDown className="opacity-50" />
            </Button>
          </ColorPickerTrigger>
          <ColorPickerContent>
            <ColorPickerArea />
            <div className="flex items-center gap-2">
              <ColorPickerEyeDropper />
              <ColorPickerHueSlider />
            </div>
            <ColorPickerInput />
          </ColorPickerContent>
        </ColorPicker>

        <Button variant="outline" onClick={() => setLocalValue(null)}>
          {!!props.structure.col && props.structure.col < 12 ? <XIcon /> : Lang.key('reset')}
        </Button>
      </div>

      <DataDescription {...props} />
    </React.Fragment>
  );
}
