import {useRef, useState} from 'react';
import {ColorPicker} from './color-picker';
import {DialogFooter} from '../overlays/dialog/dialog-footer';
import {Button} from '../buttons/button';
import {useDialogContext} from '../overlays/dialog/dialog-context';
import {Dialog} from '../overlays/dialog/dialog';
import {Trans} from '../../i18n/trans';

interface ColorPickerDialogProps {
  defaultValue?: string;
  onChange?: (color: string) => void;
}
export function ColorPickerDialog({
  defaultValue,
  onChange,
}: ColorPickerDialogProps) {
  const {close} = useDialogContext();
  const [value, setValue] = useState(defaultValue || '');
  const initialValue = useRef(defaultValue);

  return (
    <Dialog size="w-auto">
      <ColorPicker
        defaultValue={value}
        onChange={newValue => {
          setValue(newValue);
          onChange?.(newValue);
        }}
        showInput
      />
      <DialogFooter dividerTop>
        <Button
          variant="text"
          size="xs"
          onClick={() => {
            close(initialValue.current);
          }}
        >
          <Trans message="Cancel" />
        </Button>
        <Button
          variant="flat"
          color="primary"
          size="xs"
          onClick={() => {
            close(value);
          }}
        >
          <Trans message="Apply" />
        </Button>
      </DialogFooter>
    </Dialog>
  );
}
