/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import styled, { css } from 'styled-components';
import { rgba } from 'polished';
import { useCallback, useRef, useState } from 'react';

/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import { ReactComponent as Add } from '../../icons/add_page.svg';
import { ReactComponent as Edit } from '../../icons/edit_pencil.svg';
import { useSidebar } from '../sidebar';
import { useStory } from '../../app/story';
import generatePatternStyles from '../../utils/generatePatternStyles';
import { Panel, PanelTitle, PanelContent } from './panel';

const buttonCSS = css`
  background: transparent;
  width: 28px;
  height: 26px;
  border: 0;
  color: ${({ theme }) => rgba(theme.colors.fg.v1, 0.84)};
  cursor: pointer;
`;
const AddColorPresetButton = styled.div`
  ${buttonCSS}
  margin-right: 9px;
  svg {
    width: 26px;
    height: 28px;
  }
`;

const EditModeButton = styled.div`
  ${buttonCSS}
  svg {
    width: 16px;
    height: 16px;
  }
`;

const ExitEditMode = styled.button``;

const Color = styled.div`
  display: inline-block;
  background: ${({ color }) => color};
  width: 30px;
  height: 30px;
  border-radius: 15px;
  margin-right: 12px;
  border: 0.5px solid ${({ theme }) => rgba(theme.colors.fg.v1, 0.3)};
`;

const Colors = styled.div`
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  overflow: auto;

  ${Color}:nth-child (6n) {
    margin-right: 0;
  }
`;

// @todo Actual style :)
const RemoveColor = styled.button`
  width: 15px;
  height: 15px;
  background-color: black;
  color: white;
`;

{
  /* TODO: <Panel /> should be refactored for a better accessibility, "secondaryAction" should be a <button /> */
}
function ColorPresetPanel() {
  const {
    state: {
      story: { colorPresets },
    },
    actions: { updateStory },
  } = useStory();

  const [isEditMode, setIsEditMode] = useState(false);

  const ref = useRef();

  const {
    actions: { showColorPickerAt, hideSidebar },
  } = useSidebar();
  const openColorPicker = useCallback(
    (evt) => {
      evt.preventDefault();
      showColorPickerAt(ref.current, {
        onChange: () => null,
        hasGradient: false, // @todo Allow this, too?
        hasOpacity: true,
        onClose: hideSidebar,
      });
    },
    [showColorPickerAt, hideSidebar]
  );

  const handleDeleteColor = useCallback(
    (toDelete) => () => {
      const colors = colorPresets.filter((color) => color !== toDelete);
      updateStory({
        properties: {
          colorPresets: colors,
        },
      });
    },
    [colorPresets, updateStory]
  );

  return (
    <Panel name="colorpreset">
      <PanelTitle
        isPrimary
        secondaryAction={
          !isEditMode ? (
            <>
              <EditModeButton onClick={() => setIsEditMode(true)}>
                <Edit />
              </EditModeButton>
              <AddColorPresetButton ref={ref} onClick={openColorPicker}>
                <Add />
              </AddColorPresetButton>
            </>
          ) : (
            <ExitEditMode onClick={() => setIsEditMode(false)}>
              {__('Exit', 'web-stories')}
            </ExitEditMode>
          )
        }
      >
        {__('Color presets', 'web-stories')}
      </PanelTitle>
      {colorPresets && (
        <PanelContent isPrimary>
          <Colors>
            {colorPresets.map((color, i) => {
              return (
                <Color
                  key={`color-${i}`}
                  {...generatePatternStyles(color, 'color')}
                >
                  {isEditMode && (
                    <RemoveColor onClick={handleDeleteColor(color)}>
                      {__('X', 'web-stories')}
                    </RemoveColor>
                  )}
                </Color>
              );
            })}
          </Colors>
        </PanelContent>
      )}
    </Panel>
  );
}

export default ColorPresetPanel;

@@ -1154,24 +1154,79 @@
 ernStyles';%0A
+import %7B getDefinitionForType %7D from '../../elements';%0A
 import %7B Pan
@@ -1272,16 +1272,16 @@
 panel';%0A
-
 %0Aconst b
@@ -2424,24 +2424,50 @@
    state: %7B%0A
+      selectedElementIds,%0A
       story:
@@ -2518,16 +2518,36 @@
 ateStory
+, updateElementsById
  %7D,%0A  %7D 
@@ -3322,16 +3322,598 @@
 %5D%0A  );%0A%0A
+  const handleApplyColor = useCallback(%0A    (color) =%3E () =%3E %7B%0A      if (!isEditMode) %7B%0A        updateElementsById(%7B%0A          elementIds: selectedElementIds,%0A          properties: (currentProperties) =%3E %7B%0A            const %7B type %7D = currentProperties;%0A            // @todo Is this necessary?%0A            const %7B isMedia %7D = getDefinitionForType(type);%0A            return isMedia%0A              ? %7B%7D%0A              : %7B%0A                  backgroundColor: color,%0A                %7D;%0A          %7D,%0A        %7D);%0A      %7D%0A    %7D,%0A    %5BisEditMode, selectedElementIds, updateElementsById%5D%0A  );%0A%0A
   return
@@ -4775,16 +4775,16 @@
 -$%7Bi%7D%60%7D%0A
-
         
@@ -4832,24 +4832,76 @@
 , 'color')%7D%0A
+                  onClick=%7BhandleApplyColor(color)%7D%0A
             

Allow using color presets for background color